Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/dictobject.c
Line
Count
Source
1
/* Dictionary object implementation using a hash table */
2
3
/* The distribution includes a separate file, Objects/dictnotes.txt,
4
   describing explorations into dictionary design and optimization.
5
   It covers typical dictionary use patterns, the parameters for
6
   tuning dictionaries, and several ideas for possible optimizations.
7
*/
8
9
/* PyDictKeysObject
10
11
This implements the dictionary's hashtable.
12
13
As of Python 3.6, this is compact and ordered. Basic idea is described here:
14
* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
15
* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
16
17
layout:
18
19
+---------------------+
20
| dk_refcnt           |
21
| dk_log2_size        |
22
| dk_log2_index_bytes |
23
| dk_kind             |
24
| dk_version          |
25
| dk_usable           |
26
| dk_nentries         |
27
+---------------------+
28
| dk_indices[]        |
29
|                     |
30
+---------------------+
31
| dk_entries[]        |
32
|                     |
33
+---------------------+
34
35
dk_indices is actual hashtable.  It holds index in entries, or DKIX_EMPTY(-1)
36
or DKIX_DUMMY(-2).
37
Size of indices is dk_size.  Type of each index in indices varies with dk_size:
38
39
* int8  for          dk_size <= 128
40
* int16 for 256   <= dk_size <= 2**15
41
* int32 for 2**16 <= dk_size <= 2**31
42
* int64 for 2**32 <= dk_size
43
44
dk_entries is array of PyDictKeyEntry when dk_kind == DICT_KEYS_GENERAL or
45
PyDictUnicodeEntry otherwise. Its length is USABLE_FRACTION(dk_size).
46
47
NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
48
dk_indices entry is signed integer and int16 is used for table which
49
dk_size == 256.
50
*/
51
52
53
/*
54
The DictObject can be in one of two forms.
55
56
Either:
57
  A combined table:
58
    ma_values == NULL, dk_refcnt == 1.
59
    Values are stored in the me_value field of the PyDictKeyEntry.
60
Or:
61
  A split table:
62
    ma_values != NULL, dk_refcnt >= 1
63
    Values are stored in the ma_values array.
64
    Only string (unicode) keys are allowed.
65
66
There are four kinds of slots in the table (slot is index, and
67
DK_ENTRIES(keys)[index] if index >= 0):
68
69
1. Unused.  index == DKIX_EMPTY
70
   Does not hold an active (key, value) pair now and never did.  Unused can
71
   transition to Active upon key insertion.  This is each slot's initial state.
72
73
2. Active.  index >= 0, me_key != NULL and me_value != NULL
74
   Holds an active (key, value) pair.  Active can transition to Dummy or
75
   Pending upon key deletion (for combined and split tables respectively).
76
   This is the only case in which me_value != NULL.
77
78
3. Dummy.  index == DKIX_DUMMY  (combined only)
79
   Previously held an active (key, value) pair, but that was deleted and an
80
   active pair has not yet overwritten the slot.  Dummy can transition to
81
   Active upon key insertion.  Dummy slots cannot be made Unused again
82
   else the probe sequence in case of collision would have no way to know
83
   they were once active.
84
   In free-threaded builds dummy slots are not re-used to allow lock-free
85
   lookups to proceed safely.
86
87
4. Pending. index >= 0, key != NULL, and value == NULL  (split only)
88
   Not yet inserted in split-table.
89
*/
90
91
/*
92
Preserving insertion order
93
94
It's simple for combined table.  Since dk_entries is mostly append only, we can
95
get insertion order by just iterating dk_entries.
96
97
One exception is .popitem().  It removes last item in dk_entries and decrement
98
dk_nentries to achieve amortized O(1).  Since there are DKIX_DUMMY remains in
99
dk_indices, we can't increment dk_usable even though dk_nentries is
100
decremented.
101
102
To preserve the order in a split table, a bit vector is used to record the
103
insertion order. When a key is inserted the bit vector is shifted up by 4 bits
104
and the index of the key is stored in the low 4 bits.
105
As a consequence of this, split keys have a maximum size of 16.
106
*/
107
108
/* PyDict_MINSIZE is the starting size for any new dict.
109
 * 8 allows dicts with no more than 5 active entries; experiments suggested
110
 * this suffices for the majority of dicts (consisting mostly of usually-small
111
 * dicts created to pass keyword arguments).
112
 * Making this 8, rather than 4 reduces the number of resizes for most
113
 * dictionaries, without any significant extra memory use.
114
 */
115
297M
#define PyDict_LOG_MINSIZE 3
116
50.7M
#define PyDict_MINSIZE 8
117
118
#include "Python.h"
119
#include "pycore_bitutils.h"      // _Py_bit_length
120
#include "pycore_call.h"          // _PyObject_CallNoArgs()
121
#include "pycore_ceval.h"         // _PyEval_GetBuiltin()
122
#include "pycore_code.h"          // stats
123
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION, Py_END_CRITICAL_SECTION
124
#include "pycore_dict.h"          // export _PyDict_SizeOf()
125
#include "pycore_freelist.h"      // _PyFreeListState_GET()
126
#include "pycore_gc.h"            // _PyObject_GC_IS_TRACKED()
127
#include "pycore_object.h"        // _PyObject_GC_TRACK(), _PyDebugAllocatorStats()
128
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_SSIZE_RELAXED
129
#include "pycore_pyerrors.h"      // _PyErr_GetRaisedException()
130
#include "pycore_pystate.h"       // _PyThreadState_GET()
131
#include "pycore_setobject.h"     // _PySet_NextEntry()
132
#include "pycore_tuple.h"         // _PyTuple_Recycle()
133
#include "pycore_unicodeobject.h" // _PyUnicode_InternImmortal()
134
135
#include "stringlib/eq.h"                // unicode_eq()
136
#include <stdbool.h>
137
138
// Forward declarations
139
static PyObject* frozendict_new(PyTypeObject *type, PyObject *args,
140
                                PyObject *kwds);
141
static PyObject* frozendict_new_untracked(PyTypeObject *type);
142
static PyObject* dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
143
static PyObject* dict_new_untracked(PyTypeObject *type);
144
static int dict_merge(PyObject *a, PyObject *b, int override, PyObject **dupkey);
145
static int dict_contains(PyObject *op, PyObject *key);
146
static int dict_merge_from_seq2(PyObject *d, PyObject *seq2, int override);
147
148
149
/*[clinic input]
150
class dict "PyDictObject *" "&PyDict_Type"
151
class frozendict "PyFrozenDictObject *" "&PyFrozenDict_Type"
152
[clinic start generated code]*/
153
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5dfa93bac68e7c54]*/
154
155
156
/*
157
To ensure the lookup algorithm terminates, there must be at least one Unused
158
slot (NULL key) in the table.
159
To avoid slowing down lookups on a near-full table, we resize the table when
160
it's USABLE_FRACTION (currently two-thirds) full.
161
*/
162
163
#ifdef Py_GIL_DISABLED
164
165
static inline void
166
ASSERT_DICT_LOCKED(PyObject *op)
167
{
168
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);
169
}
170
#define ASSERT_DICT_LOCKED(op) ASSERT_DICT_LOCKED(_Py_CAST(PyObject*, op))
171
#define ASSERT_WORLD_STOPPED_OR_DICT_LOCKED(op)                         \
172
    if (!_PyInterpreterState_GET()->stoptheworld.world_stopped) {       \
173
        ASSERT_DICT_LOCKED(op);                                         \
174
    }
175
#define ASSERT_WORLD_STOPPED_OR_OBJ_LOCKED(op)                         \
176
    if (!_PyInterpreterState_GET()->stoptheworld.world_stopped) {      \
177
        _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(op);                 \
178
    }
179
180
#define IS_DICT_SHARED(mp) _PyObject_GC_IS_SHARED(mp)
181
#define SET_DICT_SHARED(mp) _PyObject_GC_SET_SHARED(mp)
182
#define LOAD_INDEX(keys, size, idx) _Py_atomic_load_int##size##_relaxed(&((const int##size##_t*)keys->dk_indices)[idx]);
183
#define STORE_INDEX(keys, size, idx, value) _Py_atomic_store_int##size##_relaxed(&((int##size##_t*)keys->dk_indices)[idx], (int##size##_t)value);
184
#define ASSERT_OWNED_OR_SHARED(mp) \
185
    assert(_Py_IsOwnedByCurrentThread((PyObject *)mp) || IS_DICT_SHARED(mp));
186
187
#define LOCK_KEYS_IF_SPLIT(keys, kind) \
188
        if (kind == DICT_KEYS_SPLIT) { \
189
            LOCK_KEYS(keys);           \
190
        }
191
192
#define UNLOCK_KEYS_IF_SPLIT(keys, kind) \
193
        if (kind == DICT_KEYS_SPLIT) {   \
194
            UNLOCK_KEYS(keys);           \
195
        }
196
197
static inline Py_ssize_t
198
load_keys_nentries(PyDictObject *mp)
199
{
200
    PyDictKeysObject *keys = _Py_atomic_load_ptr(&mp->ma_keys);
201
    return _Py_atomic_load_ssize(&keys->dk_nentries);
202
}
203
204
static inline void
205
set_keys(PyDictObject *mp, PyDictKeysObject *keys)
206
{
207
    ASSERT_OWNED_OR_SHARED(mp);
208
    _Py_atomic_store_ptr_release(&mp->ma_keys, keys);
209
}
210
211
static inline void
212
set_values(PyDictObject *mp, PyDictValues *values)
213
{
214
    ASSERT_OWNED_OR_SHARED(mp);
215
    _Py_atomic_store_ptr_release(&mp->ma_values, values);
216
}
217
218
// gh-151593: The _Py_LOCK_DONT_DETACH flag ensures that the outer critical
219
// section is not dropped if there is some contention on the keys lock.
220
// It also means that it will be important that LOCK_KEYS() is essentially the
221
// "inner-most" code and that we don't call Py_DECREF() or similar while
222
// holding the keys lock.
223
//
224
// We are not allowed to acquire other locks within LOCK_KEYS(). For example,
225
// PyType_Modified() must not be called within LOCK_KEYS() since it acquires
226
// the type lock.
227
#define LOCK_KEYS(keys) PyMutex_LockFlags(&keys->dk_mutex, _Py_LOCK_DONT_DETACH)
228
#define UNLOCK_KEYS(keys) PyMutex_Unlock(&keys->dk_mutex)
229
230
#define ASSERT_KEYS_LOCKED(keys) assert(PyMutex_IsLocked(&keys->dk_mutex))
231
#define LOAD_SHARED_KEY(key) _Py_atomic_load_ptr_acquire(&key)
232
#define STORE_SHARED_KEY(key, value) _Py_atomic_store_ptr_release(&key, value)
233
// Inc refs the keys object, giving the previous value
234
#define INCREF_KEYS(dk)  _Py_atomic_add_ssize(&dk->dk_refcnt, 1)
235
// Dec refs the keys object, giving the previous value
236
#define DECREF_KEYS(dk)  _Py_atomic_add_ssize(&dk->dk_refcnt, -1)
237
#define LOAD_KEYS_NENTRIES(keys) _Py_atomic_load_ssize_relaxed(&keys->dk_nentries)
238
239
#define INCREF_KEYS_FT(dk) dictkeys_incref(dk)
240
#define DECREF_KEYS_FT(dk, shared) dictkeys_decref(dk, shared)
241
242
static inline void split_keys_entry_added(PyDictKeysObject *keys)
243
{
244
    ASSERT_KEYS_LOCKED(keys);
245
246
    // We increase before we decrease so we never get too small of a value
247
    // when we're racing with reads
248
    _Py_atomic_store_ssize_relaxed(&keys->dk_nentries, keys->dk_nentries + 1);
249
    _Py_atomic_store_ssize_release(&keys->dk_usable, keys->dk_usable - 1);
250
}
251
252
#else /* Py_GIL_DISABLED */
253
254
#define ASSERT_DICT_LOCKED(op)
255
#define ASSERT_WORLD_STOPPED_OR_DICT_LOCKED(op)
256
#define ASSERT_WORLD_STOPPED_OR_OBJ_LOCKED(op)
257
#define LOCK_KEYS(keys)
258
#define UNLOCK_KEYS(keys)
259
#define ASSERT_KEYS_LOCKED(keys)
260
2
#define LOAD_SHARED_KEY(key) key
261
1.61M
#define STORE_SHARED_KEY(key, value) key = value
262
740k
#define INCREF_KEYS(dk)  dk->dk_refcnt++
263
56.4M
#define DECREF_KEYS(dk)  dk->dk_refcnt--
264
846
#define LOAD_KEYS_NENTRIES(keys) keys->dk_nentries
265
#define INCREF_KEYS_FT(dk)
266
#define DECREF_KEYS_FT(dk, shared)
267
#define LOCK_KEYS_IF_SPLIT(keys, kind)
268
#define UNLOCK_KEYS_IF_SPLIT(keys, kind)
269
10.8M
#define IS_DICT_SHARED(mp) (false)
270
#define SET_DICT_SHARED(mp)
271
3.90G
#define LOAD_INDEX(keys, size, idx) ((const int##size##_t*)(keys->dk_indices))[idx]
272
274M
#define STORE_INDEX(keys, size, idx, value) ((int##size##_t*)(keys->dk_indices))[idx] = (int##size##_t)value
273
274
static inline void split_keys_entry_added(PyDictKeysObject *keys)
275
1.61M
{
276
1.61M
    keys->dk_usable--;
277
1.61M
    keys->dk_nentries++;
278
1.61M
}
279
280
static inline void
281
set_keys(PyDictObject *mp, PyDictKeysObject *keys)
282
10.8M
{
283
10.8M
    mp->ma_keys = keys;
284
10.8M
}
285
286
static inline void
287
set_values(PyDictObject *mp, PyDictValues *values)
288
655k
{
289
655k
    mp->ma_values = values;
290
655k
}
291
292
static inline Py_ssize_t
293
load_keys_nentries(PyDictObject *mp)
294
0
{
295
0
    return mp->ma_keys->dk_nentries;
296
0
}
297
298
299
#endif
300
301
#ifndef NDEBUG
302
// Check if it's possible to modify a dictionary.
303
// Usage: assert(can_modify_dict(mp)).
304
static inline int
305
can_modify_dict(PyDictObject *mp)
306
{
307
    if (PyFrozenDict_Check(mp)) {
308
        // gh-151722: A frozendict must not be tracked by the GC
309
        // when it's being modified.
310
        assert(!_PyObject_GC_IS_TRACKED(mp));
311
312
        // No locking required to modify a newly created frozendict
313
        // since it's only accessible from the current thread.
314
        assert(PyUnstable_Object_IsUniquelyReferenced(_PyObject_CAST(mp)));
315
    }
316
    else {
317
        // Locking is only required if the dictionary is not
318
        // uniquely referenced.
319
        ASSERT_DICT_LOCKED(mp);
320
    }
321
    return 1;
322
}
323
#endif
324
325
#define _PyAnyDict_CAST(op) \
326
801M
    (assert(PyAnyDict_Check(op)), _Py_CAST(PyDictObject*, op))
327
328
8.87M
#define GET_USED(ep) FT_ATOMIC_LOAD_SSIZE_RELAXED((ep)->ma_used)
329
330
115M
#define STORE_KEY(ep, key) FT_ATOMIC_STORE_PTR_RELEASE((ep)->me_key, key)
331
201M
#define STORE_VALUE(ep, value) FT_ATOMIC_STORE_PTR_RELEASE((ep)->me_value, value)
332
228k
#define STORE_SPLIT_VALUE(mp, idx, value) FT_ATOMIC_STORE_PTR_RELEASE(mp->ma_values->values[idx], value)
333
78.0M
#define STORE_HASH(ep, hash) FT_ATOMIC_STORE_SSIZE_RELAXED((ep)->me_hash, hash)
334
119M
#define STORE_KEYS_USABLE(keys, usable) FT_ATOMIC_STORE_SSIZE_RELAXED(keys->dk_usable, usable)
335
119M
#define STORE_KEYS_NENTRIES(keys, nentries) FT_ATOMIC_STORE_SSIZE_RELAXED(keys->dk_nentries, nentries)
336
170M
#define STORE_USED(mp, used) FT_ATOMIC_STORE_SSIZE_RELAXED(mp->ma_used, used)
337
338
493M
#define PERTURB_SHIFT 5
339
340
/*
341
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
342
function, in the sense of simulating randomness.  Python doesn't:  its most
343
important hash functions (for ints) are very regular in common
344
cases:
345
346
  >>>[hash(i) for i in range(4)]
347
  [0, 1, 2, 3]
348
349
This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
350
the low-order i bits as the initial table index is extremely fast, and there
351
are no collisions at all for dicts indexed by a contiguous range of ints. So
352
this gives better-than-random behavior in common cases, and that's very
353
desirable.
354
355
OTOH, when collisions occur, the tendency to fill contiguous slices of the
356
hash table makes a good collision resolution strategy crucial.  Taking only
357
the last i bits of the hash code is also vulnerable:  for example, consider
358
the list [i << 16 for i in range(20000)] as a set of keys.  Since ints are
359
their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
360
 of every hash code are all 0:  they *all* map to the same table index.
361
362
But catering to unusual cases should not slow the usual ones, so we just take
363
the last i bits anyway.  It's up to collision resolution to do the rest.  If
364
we *usually* find the key we're looking for on the first try (and, it turns
365
out, we usually do -- the table load factor is kept under 2/3, so the odds
366
are solidly in our favor), then it makes best sense to keep the initial index
367
computation dirt cheap.
368
369
The first half of collision resolution is to visit table indices via this
370
recurrence:
371
372
    j = ((5*j) + 1) mod 2**i
373
374
For any initial j in range(2**i), repeating that 2**i times generates each
375
int in range(2**i) exactly once (see any text on random-number generation for
376
proof).  By itself, this doesn't help much:  like linear probing (setting
377
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
378
order.  This would be bad, except that's not the only thing we do, and it's
379
actually *good* in the common cases where hash keys are consecutive.  In an
380
example that's really too small to make this entirely clear, for a table of
381
size 2**3 the order of indices is:
382
383
    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
384
385
If two things come in at index 5, the first place we look after is index 2,
386
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
387
Linear probing is deadly in this case because there the fixed probe order
388
is the *same* as the order consecutive keys are likely to arrive.  But it's
389
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
390
and certain that consecutive hash codes do not.
391
392
The other half of the strategy is to get the other bits of the hash code
393
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
394
full hash code, and changing the recurrence to:
395
396
    perturb >>= PERTURB_SHIFT;
397
    j = (5*j) + 1 + perturb;
398
    use j % 2**i as the next table index;
399
400
Now the probe sequence depends (eventually) on every bit in the hash code,
401
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
402
because it quickly magnifies small differences in the bits that didn't affect
403
the initial index.  Note that because perturb is unsigned, if the recurrence
404
is executed often enough perturb eventually becomes and remains 0.  At that
405
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
406
that's certain to find an empty slot eventually (since it generates every int
407
in range(2**i), and we make sure there's always at least one empty slot).
408
409
Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
410
small so that the high bits of the hash code continue to affect the probe
411
sequence across iterations; but you want it large so that in really bad cases
412
the high-order hash bits have an effect on early iterations.  5 was "the
413
best" in minimizing total collisions across experiments Tim Peters ran (on
414
both normal and pathological cases), but 4 and 6 weren't significantly worse.
415
416
Historical: Reimer Behrends contributed the idea of using a polynomial-based
417
approach, using repeated multiplication by x in GF(2**n) where an irreducible
418
polynomial for each table size was chosen such that x was a primitive root.
419
Christian Tismer later extended that to use division by x instead, as an
420
efficient way to get the high bits of the hash code into play.  This scheme
421
also gave excellent collision statistics, but was more expensive:  two
422
if-tests were required inside the loop; computing "the next" index took about
423
the same number of operations but without as much potential parallelism
424
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
425
above, and then shifting perturb can be done while the table index is being
426
masked); and the PyDictObject struct required a member to hold the table's
427
polynomial.  In Tim's experiments the current scheme ran faster, produced
428
equally good collision statistics, needed less code & used less memory.
429
430
*/
431
432
static int dictresize(PyDictObject *mp, uint8_t log_newsize, int unicode);
433
434
static PyObject* dict_iter(PyObject *dict);
435
436
static int
437
setitem_lock_held(PyDictObject *mp, PyObject *key, PyObject *value);
438
static int
439
dict_setdefault_ref_lock_held(PyObject *d, PyObject *key, PyObject *default_value,
440
                    PyObject **result, int incref_result);
441
442
#ifndef NDEBUG
443
static int _PyObject_InlineValuesConsistencyCheck(PyObject *obj);
444
#endif
445
446
#include "clinic/dictobject.c.h"
447
448
449
static inline Py_hash_t
450
unicode_get_hash(PyObject *o)
451
506M
{
452
506M
    return PyUnstable_Unicode_GET_CACHED_HASH(o);
453
506M
}
454
455
/* Print summary info about the state of the optimized allocator */
456
void
457
_PyDict_DebugMallocStats(FILE *out)
458
0
{
459
0
    _PyDebugAllocatorStats(out, "free PyDictObject",
460
0
                           _Py_FREELIST_SIZE(dicts),
461
0
                           _PyType_PreHeaderSize(&PyDict_Type) + sizeof(PyDictObject));
462
0
    _PyDebugAllocatorStats(out, "free PyDictKeysObject",
463
0
                           _Py_FREELIST_SIZE(dictkeys),
464
0
                           sizeof(PyDictKeysObject));
465
0
}
466
467
3.31G
#define DK_MASK(dk) (DK_SIZE(dk)-1)
468
469
#define _Py_DICT_IMMORTAL_INITIAL_REFCNT PY_SSIZE_T_MIN
470
471
static void free_keys_object(PyDictKeysObject *keys, bool use_qsbr);
472
473
/* PyDictKeysObject has refcounts like PyObject does, so we have the
474
   following two functions to mirror what Py_INCREF() and Py_DECREF() do.
475
   (Keep in mind that PyDictKeysObject isn't actually a PyObject.)
476
   Likewise a PyDictKeysObject can be immortal (e.g. Py_EMPTY_KEYS),
477
   so we apply a naive version of what Py_INCREF() and Py_DECREF() do
478
   for immortal objects. */
479
480
static inline void
481
dictkeys_incref(PyDictKeysObject *dk)
482
740k
{
483
740k
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(dk->dk_refcnt) < 0) {
484
0
        assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(dk->dk_refcnt) == _Py_DICT_IMMORTAL_INITIAL_REFCNT);
485
0
        return;
486
0
    }
487
#ifdef Py_REF_DEBUG
488
    _Py_IncRefTotal(_PyThreadState_GET());
489
#endif
490
740k
    INCREF_KEYS(dk);
491
740k
}
492
493
static inline void
494
dictkeys_decref(PyDictKeysObject *dk, bool use_qsbr)
495
158M
{
496
158M
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(dk->dk_refcnt) < 0) {
497
102M
        assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(dk->dk_refcnt) == _Py_DICT_IMMORTAL_INITIAL_REFCNT);
498
102M
        return;
499
102M
    }
500
158M
    assert(FT_ATOMIC_LOAD_SSIZE(dk->dk_refcnt) > 0);
501
#ifdef Py_REF_DEBUG
502
    _Py_DecRefTotal(_PyThreadState_GET());
503
#endif
504
56.4M
    if (DECREF_KEYS(dk) == 1) {
505
55.6M
        if (DK_IS_UNICODE(dk)) {
506
51.4M
            PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(dk);
507
51.4M
            Py_ssize_t i, n;
508
142M
            for (i = 0, n = dk->dk_nentries; i < n; i++) {
509
91.0M
                Py_XDECREF(entries[i].me_key);
510
91.0M
                Py_XDECREF(entries[i].me_value);
511
91.0M
            }
512
51.4M
        }
513
4.25M
        else {
514
4.25M
            PyDictKeyEntry *entries = DK_ENTRIES(dk);
515
4.25M
            Py_ssize_t i, n;
516
83.3M
            for (i = 0, n = dk->dk_nentries; i < n; i++) {
517
79.0M
                Py_XDECREF(entries[i].me_key);
518
79.0M
                Py_XDECREF(entries[i].me_value);
519
79.0M
            }
520
4.25M
        }
521
55.6M
        free_keys_object(dk, use_qsbr);
522
55.6M
    }
523
56.4M
}
524
525
/* lookup indices.  returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
526
static inline Py_ssize_t
527
dictkeys_get_index(const PyDictKeysObject *keys, Py_ssize_t i)
528
3.90G
{
529
3.90G
    int log2size = DK_LOG_SIZE(keys);
530
3.90G
    Py_ssize_t ix;
531
532
3.90G
    if (log2size < 8) {
533
3.73G
        ix = LOAD_INDEX(keys, 8, i);
534
3.73G
    }
535
172M
    else if (log2size < 16) {
536
147M
        ix = LOAD_INDEX(keys, 16, i);
537
147M
    }
538
24.4M
#if SIZEOF_VOID_P > 4
539
24.4M
    else if (log2size >= 32) {
540
0
        ix = LOAD_INDEX(keys, 64, i);
541
0
    }
542
24.4M
#endif
543
24.4M
    else {
544
24.4M
        ix = LOAD_INDEX(keys, 32, i);
545
24.4M
    }
546
3.90G
    assert(ix >= DKIX_DUMMY);
547
3.90G
    return ix;
548
3.90G
}
549
550
/* write to indices. */
551
static inline void
552
dictkeys_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
553
274M
{
554
274M
    int log2size = DK_LOG_SIZE(keys);
555
556
274M
    assert(ix >= DKIX_DUMMY);
557
274M
    assert(keys->dk_version == 0);
558
559
274M
    if (log2size < 8) {
560
249M
        assert(ix <= 0x7f);
561
249M
        STORE_INDEX(keys, 8, i, ix);
562
249M
    }
563
24.3M
    else if (log2size < 16) {
564
20.4M
        assert(ix <= 0x7fff);
565
20.4M
        STORE_INDEX(keys, 16, i, ix);
566
20.4M
    }
567
3.92M
#if SIZEOF_VOID_P > 4
568
3.92M
    else if (log2size >= 32) {
569
0
        STORE_INDEX(keys, 64, i, ix);
570
0
    }
571
3.92M
#endif
572
3.92M
    else {
573
3.92M
        assert(ix <= 0x7fffffff);
574
3.92M
        STORE_INDEX(keys, 32, i, ix);
575
3.92M
    }
576
274M
}
577
578
579
/* USABLE_FRACTION is the maximum dictionary load.
580
 * Increasing this ratio makes dictionaries more dense resulting in more
581
 * collisions.  Decreasing it improves sparseness at the expense of spreading
582
 * indices over more cache lines and at the cost of total memory consumed.
583
 *
584
 * USABLE_FRACTION must obey the following:
585
 *     (0 < USABLE_FRACTION(n) < n) for all n >= 2
586
 *
587
 * USABLE_FRACTION should be quick to calculate.
588
 * Fractions around 1/2 to 2/3 seem to work well in practice.
589
 */
590
161M
#define USABLE_FRACTION(n) (((n) << 1)/3)
591
592
/* Find the smallest dk_size >= minsize. */
593
static inline uint8_t
594
calculate_log2_keysize(Py_ssize_t minsize)
595
7.39M
{
596
7.39M
#if SIZEOF_LONG == SIZEOF_SIZE_T
597
7.39M
    minsize = Py_MAX(minsize, PyDict_MINSIZE);
598
7.39M
    return _Py_bit_length(minsize - 1);
599
#elif defined(_MSC_VER)
600
    // On 64bit Windows, sizeof(long) == 4. We cannot use _Py_bit_length.
601
    minsize = Py_MAX(minsize, PyDict_MINSIZE);
602
    unsigned long msb;
603
    _BitScanReverse64(&msb, (uint64_t)minsize - 1);
604
    return (uint8_t)(msb + 1);
605
#else
606
    uint8_t log2_size;
607
    for (log2_size = PyDict_LOG_MINSIZE;
608
            (((Py_ssize_t)1) << log2_size) < minsize;
609
            log2_size++)
610
        ;
611
    return log2_size;
612
#endif
613
7.39M
}
614
615
/* estimate_keysize is reverse function of USABLE_FRACTION.
616
 *
617
 * This can be used to reserve enough size to insert n entries without
618
 * resizing.
619
 */
620
static inline uint8_t
621
estimate_log2_keysize(Py_ssize_t n)
622
542k
{
623
542k
    return calculate_log2_keysize((n*3 + 1) / 2);
624
542k
}
625
626
627
/* GROWTH_RATE. Growth rate upon hitting maximum load.
628
 * Currently set to used*3.
629
 * This means that dicts double in size when growing without deletions,
630
 * but have more head room when the number of deletions is on a par with the
631
 * number of insertions.  See also bpo-17563 and bpo-33205.
632
 *
633
 * GROWTH_RATE was set to used*4 up to version 3.2.
634
 * GROWTH_RATE was set to used*2 in version 3.3.0
635
 * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
636
 */
637
6.85M
#define GROWTH_RATE(d) ((d)->ma_used*3)
638
639
/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
640
 * (which cannot fail and thus can do no allocation).
641
 *
642
 * See https://github.com/python/cpython/pull/127568#discussion_r1868070614
643
 * for the rationale of using dk_log2_index_bytes=3 instead of 0.
644
 */
645
static PyDictKeysObject empty_keys_struct = {
646
        _Py_DICT_IMMORTAL_INITIAL_REFCNT, /* dk_refcnt */
647
        0, /* dk_log2_size */
648
        3, /* dk_log2_index_bytes */
649
        DICT_KEYS_UNICODE, /* dk_kind */
650
#ifdef Py_GIL_DISABLED
651
        {0}, /* dk_mutex */
652
#endif
653
        1, /* dk_version */
654
        0, /* dk_usable (immutable) */
655
        0, /* dk_nentries */
656
        {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
657
         DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
658
};
659
660
411M
#define Py_EMPTY_KEYS &empty_keys_struct
661
662
/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
663
// #define DEBUG_PYDICT
664
665
#ifdef DEBUG_PYDICT
666
#  define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 1))
667
#else
668
423M
#  define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 0))
669
#endif
670
671
static inline int
672
get_index_from_order(PyDictObject *mp, Py_ssize_t i)
673
1.54M
{
674
1.54M
    assert(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
675
1.54M
    assert(i < mp->ma_values->size);
676
1.54M
    uint8_t *array = get_insertion_order_array(mp->ma_values);
677
1.54M
    return array[i];
678
1.54M
}
679
680
#ifdef DEBUG_PYDICT
681
static void
682
dump_entries(PyDictKeysObject *dk)
683
{
684
    for (Py_ssize_t i = 0; i < dk->dk_nentries; i++) {
685
        if (DK_IS_UNICODE(dk)) {
686
            PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(dk)[i];
687
            printf("key=%p value=%p\n", ep->me_key, ep->me_value);
688
        }
689
        else {
690
            PyDictKeyEntry *ep = &DK_ENTRIES(dk)[i];
691
            printf("key=%p hash=%lx value=%p\n", ep->me_key, ep->me_hash, ep->me_value);
692
        }
693
    }
694
}
695
#endif
696
697
int
698
_PyDict_CheckConsistency(PyObject *op, int check_content)
699
0
{
700
0
    ASSERT_WORLD_STOPPED_OR_DICT_LOCKED(op);
701
702
0
#define CHECK(expr) \
703
0
    do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
704
705
0
    assert(op != NULL);
706
0
    CHECK(PyAnyDict_Check(op));
707
0
    PyDictObject *mp = (PyDictObject *)op;
708
709
0
    PyDictKeysObject *keys = mp->ma_keys;
710
0
    int splitted = _PyDict_HasSplitTable(mp);
711
0
    Py_ssize_t usable = USABLE_FRACTION(DK_SIZE(keys));
712
713
    // In the free-threaded build, shared keys may be concurrently modified,
714
    // so use atomic loads.
715
0
    Py_ssize_t dk_usable = FT_ATOMIC_LOAD_SSIZE_ACQUIRE(keys->dk_usable);
716
0
    Py_ssize_t dk_nentries = FT_ATOMIC_LOAD_SSIZE_ACQUIRE(keys->dk_nentries);
717
718
0
    CHECK(0 <= mp->ma_used && mp->ma_used <= usable);
719
0
    CHECK(0 <= dk_usable && dk_usable <= usable);
720
0
    CHECK(0 <= dk_nentries && dk_nentries <= usable);
721
0
    CHECK(dk_usable + dk_nentries <= usable);
722
723
0
    if (!splitted) {
724
        /* combined table */
725
0
        CHECK(keys->dk_kind != DICT_KEYS_SPLIT);
726
0
        CHECK(keys->dk_refcnt == 1 || keys == Py_EMPTY_KEYS);
727
0
    }
728
0
    else {
729
0
        CHECK(keys->dk_kind == DICT_KEYS_SPLIT);
730
0
        CHECK(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
731
0
        if (mp->ma_values->embedded) {
732
0
            CHECK(mp->ma_values->embedded == 1);
733
0
            CHECK(mp->ma_values->valid == 1);
734
0
        }
735
0
    }
736
737
0
    if (check_content) {
738
0
        LOCK_KEYS_IF_SPLIT(keys, keys->dk_kind);
739
0
        for (Py_ssize_t i=0; i < DK_SIZE(keys); i++) {
740
0
            Py_ssize_t ix = dictkeys_get_index(keys, i);
741
0
            CHECK(DKIX_DUMMY <= ix && ix <= usable);
742
0
        }
743
744
0
        if (keys->dk_kind == DICT_KEYS_GENERAL) {
745
0
            PyDictKeyEntry *entries = DK_ENTRIES(keys);
746
0
            for (Py_ssize_t i=0; i < usable; i++) {
747
0
                PyDictKeyEntry *entry = &entries[i];
748
0
                PyObject *key = entry->me_key;
749
750
0
                if (key != NULL) {
751
                    /* test_dict fails if PyObject_Hash() is called again */
752
0
                    CHECK(entry->me_hash != -1);
753
0
                    CHECK(entry->me_value != NULL);
754
755
0
                    if (PyUnicode_CheckExact(key)) {
756
0
                        Py_hash_t hash = unicode_get_hash(key);
757
0
                        CHECK(entry->me_hash == hash);
758
0
                    }
759
0
                }
760
0
            }
761
0
        }
762
0
        else {
763
0
            PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(keys);
764
0
            for (Py_ssize_t i=0; i < usable; i++) {
765
0
                PyDictUnicodeEntry *entry = &entries[i];
766
0
                PyObject *key = entry->me_key;
767
768
0
                if (key != NULL) {
769
0
                    CHECK(PyUnicode_CheckExact(key));
770
0
                    Py_hash_t hash = unicode_get_hash(key);
771
0
                    CHECK(hash != -1);
772
0
                    if (!splitted) {
773
0
                        CHECK(entry->me_value != NULL);
774
0
                    }
775
0
                }
776
777
0
                if (splitted) {
778
0
                    CHECK(entry->me_value == NULL);
779
0
                }
780
0
            }
781
0
        }
782
783
0
        if (splitted) {
784
0
            CHECK(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
785
            /* splitted table */
786
0
            int duplicate_check = 0;
787
0
            for (Py_ssize_t i=0; i < mp->ma_used; i++) {
788
0
                int index = get_index_from_order(mp, i);
789
0
                CHECK((duplicate_check & (1<<index)) == 0);
790
0
                duplicate_check |= (1<<index);
791
0
                CHECK(mp->ma_values->values[index] != NULL);
792
0
            }
793
0
        }
794
0
        UNLOCK_KEYS_IF_SPLIT(keys, keys->dk_kind);
795
0
    }
796
0
    return 1;
797
798
0
#undef CHECK
799
0
}
800
801
802
static inline int
803
get_log2_bytes(uint8_t log2_size)
804
58.4M
{
805
58.4M
    int log2_bytes;
806
58.4M
    assert(log2_size >= PyDict_LOG_MINSIZE);
807
808
58.4M
    if (log2_size < 8) {
809
58.3M
        log2_bytes = log2_size;
810
58.3M
    }
811
112k
    else if (log2_size < 16) {
812
112k
        log2_bytes = log2_size + 1;
813
112k
    }
814
75
#if SIZEOF_VOID_P > 4
815
75
    else if (log2_size >= 32) {
816
0
        log2_bytes = log2_size + 3;
817
0
    }
818
75
#endif
819
75
    else {
820
75
        log2_bytes = log2_size + 2;
821
75
    }
822
823
58.4M
    return log2_bytes;
824
58.4M
}
825
826
static inline void
827
init_keys_object(PyDictKeysObject* dk, uint8_t log2_size, int log2_bytes, int kind,
828
                 Py_ssize_t usable, Py_ssize_t entry_size)
829
58.4M
{
830
#ifdef Py_REF_DEBUG
831
    _Py_IncRefTotal(_PyThreadState_GET());
832
#endif
833
58.4M
    dk->dk_refcnt = 1;
834
58.4M
    dk->dk_log2_size = log2_size;
835
58.4M
    dk->dk_log2_index_bytes = log2_bytes;
836
58.4M
    dk->dk_kind = kind;
837
#ifdef Py_GIL_DISABLED
838
    dk->dk_mutex = (PyMutex){0};
839
#endif
840
58.4M
    dk->dk_nentries = 0;
841
58.4M
    dk->dk_usable = usable;
842
58.4M
    dk->dk_version = 0;
843
58.4M
    memset(&dk->dk_indices[0], 0xff, ((size_t)1 << log2_bytes));
844
58.4M
    memset(&dk->dk_indices[(size_t)1 << log2_bytes], 0, entry_size * usable);
845
58.4M
}
846
847
static PyDictKeysObject*
848
new_keys_object(uint8_t log2_size, bool unicode)
849
58.1M
{
850
58.1M
    Py_ssize_t usable = USABLE_FRACTION((size_t)1<<log2_size);
851
58.1M
    size_t entry_size = unicode ? sizeof(PyDictUnicodeEntry) : sizeof(PyDictKeyEntry);
852
853
58.1M
    int log2_bytes = get_log2_bytes(log2_size);
854
855
58.1M
    PyDictKeysObject *dk = NULL;
856
58.1M
    if (log2_size == PyDict_LOG_MINSIZE && unicode) {
857
47.6M
        dk = _Py_FREELIST_POP_MEM(dictkeys);
858
47.6M
    }
859
58.1M
    if (dk == NULL) {
860
38.4M
        dk = PyMem_Malloc(sizeof(PyDictKeysObject)
861
38.4M
                          + ((size_t)1 << log2_bytes)
862
38.4M
                          + entry_size * usable);
863
38.4M
        if (dk == NULL) {
864
0
            PyErr_NoMemory();
865
0
            return NULL;
866
0
        }
867
38.4M
    }
868
58.1M
    init_keys_object(dk, log2_size, log2_bytes,
869
58.1M
                     unicode ? DICT_KEYS_UNICODE : DICT_KEYS_GENERAL,
870
58.1M
                     usable, entry_size);
871
58.1M
    return dk;
872
58.1M
}
873
874
static void
875
free_keys_object(PyDictKeysObject *keys, bool use_qsbr)
876
61.8M
{
877
61.8M
    void *ptr = keys;
878
#ifdef Py_GIL_DISABLED
879
    size_t size = _PyDict_KeysSize(keys);
880
#endif
881
61.8M
    if (keys->dk_kind == DICT_KEYS_SPLIT) {
882
267k
        ptr = _PyDictKeys_AsSharedKeys(keys);
883
#ifdef Py_GIL_DISABLED
884
        size += offsetof(struct _instancekeysobject, dsk_keys);
885
#endif
886
267k
    }
887
#ifdef Py_GIL_DISABLED
888
    if (use_qsbr) {
889
        _PyMem_FreeDelayed(ptr, size);
890
        return;
891
    }
892
#endif
893
61.8M
    if (DK_LOG_SIZE(keys) == PyDict_LOG_MINSIZE && keys->dk_kind == DICT_KEYS_UNICODE) {
894
51.1M
        _Py_FREELIST_FREE(dictkeys, keys, PyMem_Free);
895
51.1M
    }
896
10.7M
    else {
897
10.7M
        PyMem_Free(ptr);
898
10.7M
    }
899
61.8M
}
900
901
static size_t
902
values_size_from_count(size_t count)
903
91.5k
{
904
91.5k
    assert(count >= 1);
905
91.5k
    size_t suffix_size = _Py_SIZE_ROUND_UP(count, sizeof(PyObject *));
906
91.5k
    assert(suffix_size < 128);
907
91.5k
    assert(suffix_size % sizeof(PyObject *) == 0);
908
91.5k
    return (count + 1) * sizeof(PyObject *) + suffix_size;
909
91.5k
}
910
911
143M
#define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
912
913
static inline PyDictValues*
914
new_values(size_t size)
915
91.5k
{
916
91.5k
    size_t n = values_size_from_count(size);
917
91.5k
    PyDictValues *res = (PyDictValues *)PyMem_Malloc(n);
918
91.5k
    if (res == NULL) {
919
0
        return NULL;
920
0
    }
921
91.5k
    res->embedded = 0;
922
91.5k
    res->size = 0;
923
91.5k
    assert(size < 256);
924
91.5k
    res->capacity = (uint8_t)size;
925
91.5k
    return res;
926
91.5k
}
927
928
static inline void
929
free_values(PyDictValues *values, bool use_qsbr)
930
84.1k
{
931
84.1k
    assert(values->embedded == 0);
932
#ifdef Py_GIL_DISABLED
933
    if (use_qsbr) {
934
        _PyMem_FreeDelayed(values, values_size_from_count(values->capacity));
935
        return;
936
    }
937
#endif
938
84.1k
    PyMem_Free(values);
939
84.1k
}
940
941
static inline PyObject *
942
new_dict_impl(PyDictObject *mp, PyDictKeysObject *keys,
943
              PyDictValues *values, Py_ssize_t used,
944
              int free_values_on_failure, int frozendict, int gc_track)
945
152M
{
946
152M
    assert(keys != NULL);
947
152M
    if (mp == NULL) {
948
0
        dictkeys_decref(keys, false);
949
0
        if (free_values_on_failure) {
950
0
            free_values(values, false);
951
0
        }
952
0
        return NULL;
953
0
    }
954
955
152M
    mp->ma_keys = keys;
956
152M
    mp->ma_values = values;
957
152M
    mp->ma_used = used;
958
152M
    mp->_ma_watcher_tag = 0;
959
152M
    if (frozendict) {
960
0
        ((PyFrozenDictObject *)mp)->ma_hash = -1;
961
0
    }
962
152M
    ASSERT_CONSISTENT(mp);
963
152M
    if (gc_track) {
964
152M
        _PyObject_GC_TRACK(mp);
965
152M
    }
966
152M
    return (PyObject *)mp;
967
152M
}
968
969
/* Consumes a reference to the keys object */
970
static PyObject*
971
new_dict(PyDictKeysObject *keys, PyDictValues *values,
972
         Py_ssize_t used, int free_values_on_failure)
973
152M
{
974
152M
    PyDictObject *mp = _Py_FREELIST_POP(PyDictObject, dicts);
975
152M
    if (mp == NULL) {
976
29.4M
        mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
977
29.4M
    }
978
152M
    assert(mp == NULL || Py_IS_TYPE(mp, &PyDict_Type));
979
980
152M
    return new_dict_impl(mp, keys, values, used, free_values_on_failure, 0, 1);
981
152M
}
982
983
/* Consumes a reference to the keys object */
984
static PyObject*
985
new_dict_untracked(PyDictKeysObject *keys, PyDictValues *values,
986
                   Py_ssize_t used, int free_values_on_failure)
987
380k
{
988
380k
    PyDictObject *mp = _Py_FREELIST_POP(PyDictObject, dicts);
989
380k
    if (mp == NULL) {
990
13.4k
        mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
991
13.4k
    }
992
380k
    assert(mp == NULL || Py_IS_TYPE(mp, &PyDict_Type));
993
994
380k
    return new_dict_impl(mp, keys, values, used, free_values_on_failure, 0, 0);
995
380k
}
996
997
/* Consumes a reference to the keys object */
998
static PyObject*
999
new_frozendict_untracked(PyDictKeysObject *keys, PyDictValues *values,
1000
                         Py_ssize_t used, int free_values_on_failure)
1001
0
{
1002
0
    PyDictObject *mp = PyObject_GC_New(PyDictObject, &PyFrozenDict_Type);
1003
0
    return new_dict_impl(mp, keys, values, used, free_values_on_failure, 1, 0);
1004
0
}
1005
1006
static PyObject *
1007
new_dict_with_shared_keys(PyDictKeysObject *keys)
1008
7.62k
{
1009
7.62k
    size_t size = shared_keys_usable_size(keys);
1010
7.62k
    PyDictValues *values = new_values(size);
1011
7.62k
    if (values == NULL) {
1012
0
        return PyErr_NoMemory();
1013
0
    }
1014
7.62k
    dictkeys_incref(keys);
1015
236k
    for (size_t i = 0; i < size; i++) {
1016
228k
        values->values[i] = NULL;
1017
228k
    }
1018
7.62k
    return new_dict(keys, values, 0, 1);
1019
7.62k
}
1020
1021
1022
static PyDictKeysObject *
1023
clone_combined_dict_keys(PyDictObject *orig)
1024
3.54M
{
1025
3.54M
    assert(PyAnyDict_Check(orig));
1026
3.54M
    assert(Py_TYPE(orig)->tp_iter == dict_iter);
1027
3.54M
    assert(orig->ma_values == NULL);
1028
3.54M
    assert(orig->ma_keys != Py_EMPTY_KEYS);
1029
3.54M
    assert(orig->ma_keys->dk_refcnt == 1);
1030
1031
3.54M
    if (!PyFrozenDict_Check(orig)) {
1032
3.54M
        ASSERT_DICT_LOCKED(orig);
1033
3.54M
    }
1034
1035
3.54M
    size_t keys_size = _PyDict_KeysSize(orig->ma_keys);
1036
3.54M
    PyDictKeysObject *keys = PyMem_Malloc(keys_size);
1037
3.54M
    if (keys == NULL) {
1038
0
        PyErr_NoMemory();
1039
0
        return NULL;
1040
0
    }
1041
1042
3.54M
    memcpy(keys, orig->ma_keys, keys_size);
1043
1044
    /* The keys version must be unique per keys object: the specializer
1045
       and the JIT optimizer rely on it to identify a dict's keys. */
1046
3.54M
    keys->dk_version = 0;
1047
1048
    /* After copying key/value pairs, we need to incref all
1049
       keys and values and they are about to be co-owned by a
1050
       new dict object. */
1051
3.54M
    PyObject **pkey, **pvalue;
1052
3.54M
    size_t offs;
1053
3.54M
    if (DK_IS_UNICODE(orig->ma_keys)) {
1054
3.53M
        PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(keys);
1055
3.53M
        pkey = &ep0->me_key;
1056
3.53M
        pvalue = &ep0->me_value;
1057
3.53M
        offs = sizeof(PyDictUnicodeEntry) / sizeof(PyObject*);
1058
3.53M
    }
1059
3.31k
    else {
1060
3.31k
        PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
1061
3.31k
        pkey = &ep0->me_key;
1062
3.31k
        pvalue = &ep0->me_value;
1063
3.31k
        offs = sizeof(PyDictKeyEntry) / sizeof(PyObject*);
1064
3.31k
    }
1065
1066
3.54M
    Py_ssize_t n = keys->dk_nentries;
1067
8.89M
    for (Py_ssize_t i = 0; i < n; i++) {
1068
5.35M
        PyObject *value = *pvalue;
1069
5.35M
        if (value != NULL) {
1070
5.33M
            Py_INCREF(value);
1071
5.33M
            Py_INCREF(*pkey);
1072
5.33M
        }
1073
5.35M
        pvalue += offs;
1074
5.35M
        pkey += offs;
1075
5.35M
    }
1076
1077
    /* Since we copied the keys table we now have an extra reference
1078
       in the system.  Manually call increment _Py_RefTotal to signal that
1079
       we have it now; calling dictkeys_incref would be an error as
1080
       keys->dk_refcnt is already set to 1 (after memcpy). */
1081
#ifdef Py_REF_DEBUG
1082
    _Py_IncRefTotal(_PyThreadState_GET());
1083
#endif
1084
3.54M
    return keys;
1085
3.54M
}
1086
1087
PyObject *
1088
PyDict_New(void)
1089
151M
{
1090
    /* We don't incref Py_EMPTY_KEYS here because it is immortal. */
1091
151M
    return new_dict(Py_EMPTY_KEYS, NULL, 0, 0);
1092
151M
}
1093
1094
/* Search index of hash table from offset of entry table */
1095
static Py_ssize_t
1096
lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
1097
2.72M
{
1098
2.72M
    size_t mask = DK_MASK(k);
1099
2.72M
    size_t perturb = (size_t)hash;
1100
2.72M
    size_t i = (size_t)hash & mask;
1101
1102
4.76M
    for (;;) {
1103
4.76M
        Py_ssize_t ix = dictkeys_get_index(k, i);
1104
4.76M
        if (ix == index) {
1105
2.72M
            return i;
1106
2.72M
        }
1107
2.04M
        if (ix == DKIX_EMPTY) {
1108
0
            return DKIX_EMPTY;
1109
0
        }
1110
2.04M
        perturb >>= PERTURB_SHIFT;
1111
2.04M
        i = mask & (i*5 + perturb + 1);
1112
2.04M
    }
1113
2.72M
    Py_UNREACHABLE();
1114
2.72M
}
1115
1116
static inline Py_ALWAYS_INLINE Py_ssize_t
1117
do_lookup(PyDictObject *mp, PyDictKeysObject *dk, PyObject *key, Py_hash_t hash,
1118
          int (*check_lookup)(PyDictObject *, PyDictKeysObject *, void *, Py_ssize_t ix, PyObject *key, Py_hash_t))
1119
3.18G
{
1120
3.18G
    void *ep0 = _DK_ENTRIES(dk);
1121
3.18G
    size_t mask = DK_MASK(dk);
1122
3.18G
    size_t perturb = hash;
1123
3.18G
    size_t i = (size_t)hash & mask;
1124
3.18G
    Py_ssize_t ix;
1125
3.32G
    for (;;) {
1126
3.32G
        ix = dictkeys_get_index(dk, i);
1127
3.32G
        if (ix >= 0) {
1128
2.88G
            int cmp = check_lookup(mp, dk, ep0, ix, key, hash);
1129
2.88G
            if (cmp < 0) {
1130
0
                return cmp;
1131
2.88G
            } else if (cmp) {
1132
2.63G
                return ix;
1133
2.63G
            }
1134
2.88G
        }
1135
434M
        else if (ix == DKIX_EMPTY) {
1136
376M
            return DKIX_EMPTY;
1137
376M
        }
1138
316M
        perturb >>= PERTURB_SHIFT;
1139
316M
        i = mask & (i*5 + perturb + 1);
1140
1141
        // Manual loop unrolling
1142
316M
        ix = dictkeys_get_index(dk, i);
1143
316M
        if (ix >= 0) {
1144
184M
            int cmp = check_lookup(mp, dk, ep0, ix, key, hash);
1145
184M
            if (cmp < 0) {
1146
0
                return cmp;
1147
184M
            } else if (cmp) {
1148
65.7M
                return ix;
1149
65.7M
            }
1150
184M
        }
1151
132M
        else if (ix == DKIX_EMPTY) {
1152
115M
            return DKIX_EMPTY;
1153
115M
        }
1154
135M
        perturb >>= PERTURB_SHIFT;
1155
135M
        i = mask & (i*5 + perturb + 1);
1156
135M
    }
1157
3.18G
    Py_UNREACHABLE();
1158
3.18G
}
1159
1160
static inline int
1161
compare_unicode_generic(PyDictObject *mp, PyDictKeysObject *dk,
1162
                        void *ep0, Py_ssize_t ix, PyObject *key, Py_hash_t hash)
1163
1.19k
{
1164
1.19k
    PyDictUnicodeEntry *ep = &((PyDictUnicodeEntry *)ep0)[ix];
1165
1.19k
    assert(ep->me_key != NULL);
1166
1.19k
    assert(PyUnicode_CheckExact(ep->me_key));
1167
1.19k
    assert(!PyUnicode_CheckExact(key));
1168
1169
1.19k
    if (unicode_get_hash(ep->me_key) == hash) {
1170
0
        PyObject *startkey = ep->me_key;
1171
0
        Py_INCREF(startkey);
1172
0
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
1173
0
        Py_DECREF(startkey);
1174
0
        if (cmp < 0) {
1175
0
            return DKIX_ERROR;
1176
0
        }
1177
0
        if (dk == mp->ma_keys && ep->me_key == startkey) {
1178
0
            return cmp;
1179
0
        }
1180
0
        else {
1181
            /* The dict was mutated, restart */
1182
0
            return DKIX_KEY_CHANGED;
1183
0
        }
1184
0
    }
1185
1.19k
    return 0;
1186
1.19k
}
1187
1188
// Search non-Unicode key from Unicode table
1189
static Py_ssize_t
1190
unicodekeys_lookup_generic(PyDictObject *mp, PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1191
46.3M
{
1192
46.3M
    return do_lookup(mp, dk, key, hash, compare_unicode_generic);
1193
46.3M
}
1194
1195
static inline int
1196
compare_unicode_unicode(PyDictObject *mp, PyDictKeysObject *dk,
1197
                        void *ep0, Py_ssize_t ix, PyObject *key, Py_hash_t hash)
1198
2.77G
{
1199
2.77G
    PyDictUnicodeEntry *ep = &((PyDictUnicodeEntry *)ep0)[ix];
1200
2.77G
    PyObject *ep_key = FT_ATOMIC_LOAD_PTR_CONSUME(ep->me_key);
1201
2.77G
    assert(ep_key != NULL);
1202
2.77G
    assert(PyUnicode_CheckExact(ep_key));
1203
2.77G
    if (ep_key == key ||
1204
2.56G
            (unicode_get_hash(ep_key) == hash && unicode_eq(ep_key, key))) {
1205
2.56G
        return 1;
1206
2.56G
    }
1207
208M
    return 0;
1208
2.77G
}
1209
1210
static Py_ssize_t _Py_HOT_FUNCTION
1211
unicodekeys_lookup_unicode(PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1212
2.82G
{
1213
2.82G
    return do_lookup(NULL, dk, key, hash, compare_unicode_unicode);
1214
2.82G
}
1215
1216
static inline int
1217
compare_generic(PyDictObject *mp, PyDictKeysObject *dk,
1218
                void *ep0, Py_ssize_t ix, PyObject *key, Py_hash_t hash)
1219
301M
{
1220
301M
    PyDictKeyEntry *ep = &((PyDictKeyEntry *)ep0)[ix];
1221
301M
    assert(ep->me_key != NULL);
1222
301M
    if (ep->me_key == key) {
1223
46.9M
        return 1;
1224
46.9M
    }
1225
254M
    if (ep->me_hash == hash) {
1226
86.1M
        PyObject *startkey = ep->me_key;
1227
86.1M
        Py_INCREF(startkey);
1228
86.1M
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
1229
86.1M
        Py_DECREF(startkey);
1230
86.1M
        if (cmp < 0) {
1231
0
            return DKIX_ERROR;
1232
0
        }
1233
86.1M
        if (dk == mp->ma_keys && ep->me_key == startkey) {
1234
86.1M
            return cmp;
1235
86.1M
        }
1236
0
        else {
1237
            /* The dict was mutated, restart */
1238
0
            return DKIX_KEY_CHANGED;
1239
0
        }
1240
86.1M
    }
1241
168M
    return 0;
1242
254M
}
1243
1244
static Py_ssize_t
1245
dictkeys_generic_lookup(PyDictObject *mp, PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1246
315M
{
1247
315M
    return do_lookup(mp, dk, key, hash, compare_generic);
1248
315M
}
1249
1250
static bool
1251
check_keys_unicode(PyDictKeysObject *dk, PyObject *key)
1252
4.41M
{
1253
4.41M
    return PyUnicode_CheckExact(key) && (dk->dk_kind != DICT_KEYS_GENERAL);
1254
4.41M
}
1255
1256
static Py_ssize_t
1257
hash_unicode_key(PyObject *key)
1258
49.9M
{
1259
49.9M
    assert(PyUnicode_CheckExact(key));
1260
49.9M
    Py_hash_t hash = unicode_get_hash(key);
1261
49.9M
    if (hash == -1) {
1262
0
        hash = PyUnicode_Type.tp_hash(key);
1263
0
        assert(hash != -1);
1264
0
    }
1265
49.9M
    return hash;
1266
49.9M
}
1267
1268
#ifdef Py_GIL_DISABLED
1269
static Py_ssize_t
1270
unicodekeys_lookup_unicode_threadsafe(PyDictKeysObject* dk, PyObject *key,
1271
                                      Py_hash_t hash);
1272
#endif
1273
1274
static Py_ssize_t
1275
unicodekeys_lookup_split(PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1276
76.3M
{
1277
76.3M
    Py_ssize_t ix;
1278
76.3M
    assert(dk->dk_kind == DICT_KEYS_SPLIT);
1279
76.3M
    assert(PyUnicode_CheckExact(key));
1280
1281
#ifdef Py_GIL_DISABLED
1282
    // A split dictionaries keys can be mutated by other dictionaries
1283
    // but if we have a unicode key we can avoid locking the shared
1284
    // keys.
1285
    ix = unicodekeys_lookup_unicode_threadsafe(dk, key, hash);
1286
    if (ix == DKIX_KEY_CHANGED) {
1287
        LOCK_KEYS(dk);
1288
        ix = unicodekeys_lookup_unicode(dk, key, hash);
1289
        UNLOCK_KEYS(dk);
1290
    }
1291
#else
1292
76.3M
    ix = unicodekeys_lookup_unicode(dk, key, hash);
1293
76.3M
#endif
1294
76.3M
    return ix;
1295
76.3M
}
1296
1297
/* Lookup a string in a (all unicode) dict keys.
1298
 * Returns DKIX_ERROR if key is not a string,
1299
 * or if the dict keys is not all strings.
1300
 * If the keys is present then return the index of key.
1301
 * If the key is not present then return DKIX_EMPTY.
1302
 */
1303
Py_ssize_t
1304
_PyDictKeys_StringLookup(PyDictKeysObject* dk, PyObject *key)
1305
0
{
1306
0
    if (!check_keys_unicode(dk, key)) {
1307
0
        return DKIX_ERROR;
1308
0
    }
1309
0
    Py_hash_t hash = hash_unicode_key(key);
1310
0
    return unicodekeys_lookup_unicode(dk, key, hash);
1311
0
}
1312
1313
Py_ssize_t
1314
_PyDictKeys_StringLookupAndVersion(PyDictKeysObject *dk, PyObject *key, uint32_t *version)
1315
4.41M
{
1316
4.41M
    if (!check_keys_unicode(dk, key)) {
1317
0
        return DKIX_ERROR;
1318
0
    }
1319
4.41M
    Py_ssize_t ix;
1320
4.41M
    Py_hash_t hash = hash_unicode_key(key);
1321
4.41M
    LOCK_KEYS(dk);
1322
4.41M
    ix = unicodekeys_lookup_unicode(dk, key, hash);
1323
4.41M
    *version = _PyDictKeys_GetVersionForCurrentState(_PyInterpreterState_GET(), dk);
1324
4.41M
    UNLOCK_KEYS(dk);
1325
4.41M
    return ix;
1326
4.41M
}
1327
1328
/* Like _PyDictKeys_StringLookup() but only works on split keys.  Note
1329
 * that in free-threaded builds this locks the keys object as required.
1330
 */
1331
Py_ssize_t
1332
_PyDictKeys_StringLookupSplit(PyDictKeysObject* dk, PyObject *key)
1333
76.3M
{
1334
76.3M
    assert(dk->dk_kind == DICT_KEYS_SPLIT);
1335
76.3M
    assert(PyUnicode_CheckExact(key));
1336
76.3M
    Py_hash_t hash = unicode_get_hash(key);
1337
76.3M
    if (hash == -1) {
1338
0
        hash = PyUnicode_Type.tp_hash(key);
1339
0
        if (hash == -1) {
1340
0
            PyErr_Clear();
1341
0
            return DKIX_ERROR;
1342
0
        }
1343
0
    }
1344
76.3M
    return unicodekeys_lookup_split(dk, key, hash);
1345
76.3M
}
1346
1347
/*
1348
The basic lookup function used by all operations.
1349
This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
1350
Open addressing is preferred over chaining since the link overhead for
1351
chaining would be substantial (100% with typical malloc overhead).
1352
1353
The initial probe index is computed as hash mod the table size. Subsequent
1354
probe indices are computed as explained earlier.
1355
1356
All arithmetic on hash should ignore overflow.
1357
1358
_Py_dict_lookup() is general-purpose, and may return DKIX_ERROR if (and only if) a
1359
comparison raises an exception.
1360
When the key isn't found a DKIX_EMPTY is returned.
1361
*/
1362
Py_ssize_t
1363
_Py_dict_lookup(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject **value_addr)
1364
3.08G
{
1365
3.08G
    PyDictKeysObject *dk;
1366
3.08G
    DictKeysKind kind;
1367
3.08G
    Py_ssize_t ix;
1368
1369
3.08G
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(mp);
1370
3.08G
start:
1371
3.08G
    dk = mp->ma_keys;
1372
3.08G
    kind = dk->dk_kind;
1373
1374
3.08G
    if (kind != DICT_KEYS_GENERAL) {
1375
2.77G
        if (PyUnicode_CheckExact(key)) {
1376
#ifdef Py_GIL_DISABLED
1377
            if (kind == DICT_KEYS_SPLIT) {
1378
                ix = unicodekeys_lookup_split(dk, key, hash);
1379
            }
1380
            else {
1381
                ix = unicodekeys_lookup_unicode(dk, key, hash);
1382
            }
1383
#else
1384
2.72G
            ix = unicodekeys_lookup_unicode(dk, key, hash);
1385
2.72G
#endif
1386
2.72G
        }
1387
46.3M
        else {
1388
46.3M
            INCREF_KEYS_FT(dk);
1389
46.3M
            LOCK_KEYS_IF_SPLIT(dk, kind);
1390
1391
46.3M
            ix = unicodekeys_lookup_generic(mp, dk, key, hash);
1392
1393
46.3M
            UNLOCK_KEYS_IF_SPLIT(dk, kind);
1394
46.3M
            DECREF_KEYS_FT(dk, IS_DICT_SHARED(mp));
1395
46.3M
            if (ix == DKIX_KEY_CHANGED) {
1396
0
                goto start;
1397
0
            }
1398
46.3M
        }
1399
1400
2.77G
        if (ix >= 0) {
1401
2.50G
            if (kind == DICT_KEYS_SPLIT) {
1402
6.76M
                *value_addr = mp->ma_values->values[ix];
1403
6.76M
            }
1404
2.49G
            else {
1405
2.49G
                *value_addr = DK_UNICODE_ENTRIES(dk)[ix].me_value;
1406
2.49G
            }
1407
2.50G
        }
1408
271M
        else {
1409
271M
            *value_addr = NULL;
1410
271M
        }
1411
2.77G
    }
1412
315M
    else {
1413
315M
        ix = dictkeys_generic_lookup(mp, dk, key, hash);
1414
315M
        if (ix == DKIX_KEY_CHANGED) {
1415
0
            goto start;
1416
0
        }
1417
315M
        if (ix >= 0) {
1418
133M
            *value_addr = DK_ENTRIES(dk)[ix].me_value;
1419
133M
        }
1420
181M
        else {
1421
181M
            *value_addr = NULL;
1422
181M
        }
1423
315M
    }
1424
1425
3.08G
    return ix;
1426
3.08G
}
1427
1428
#ifdef Py_GIL_DISABLED
1429
static inline void
1430
ensure_shared_on_read(PyDictObject *mp)
1431
{
1432
    if (!_Py_IsOwnedByCurrentThread((PyObject *)mp) && !IS_DICT_SHARED(mp)) {
1433
        // The first time we access a dict from a non-owning thread we mark it
1434
        // as shared. This ensures that a concurrent resize operation will
1435
        // delay freeing the old keys or values using QSBR, which is necessary
1436
        // to safely allow concurrent reads without locking...
1437
        Py_BEGIN_CRITICAL_SECTION(mp);
1438
        if (!IS_DICT_SHARED(mp)) {
1439
            SET_DICT_SHARED(mp);
1440
        }
1441
        Py_END_CRITICAL_SECTION();
1442
    }
1443
}
1444
1445
void
1446
_PyDict_EnsureSharedOnRead(PyDictObject *mp)
1447
{
1448
    ensure_shared_on_read(mp);
1449
}
1450
#endif
1451
1452
static inline void
1453
ensure_shared_on_resize(PyDictObject *mp)
1454
10.8M
{
1455
#ifdef Py_GIL_DISABLED
1456
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(mp);
1457
1458
    if (!_Py_IsOwnedByCurrentThread((PyObject *)mp) && !IS_DICT_SHARED(mp)) {
1459
        // We are writing to the dict from another thread that owns
1460
        // it and we haven't marked it as shared which will ensure
1461
        // that when we re-size ma_keys or ma_values that we will
1462
        // free using QSBR.  We need to lock the dictionary to
1463
        // contend with writes from the owning thread, mark it as
1464
        // shared, and then we can continue with lock-free reads.
1465
        // Technically this is a little heavy handed, we could just
1466
        // free the individual old keys / old-values using qsbr
1467
        SET_DICT_SHARED(mp);
1468
    }
1469
#endif
1470
10.8M
}
1471
1472
static inline void
1473
ensure_shared_on_keys_version_assignment(PyDictObject *mp)
1474
61.6k
{
1475
61.6k
    ASSERT_DICT_LOCKED((PyObject *) mp);
1476
    #ifdef Py_GIL_DISABLED
1477
    if (!IS_DICT_SHARED(mp)) {
1478
        // This ensures that a concurrent resize operation will delay
1479
        // freeing the old keys or values using QSBR, which is necessary to
1480
        // safely allow concurrent reads without locking.
1481
        SET_DICT_SHARED(mp);
1482
    }
1483
    #endif
1484
61.6k
}
1485
1486
#ifdef Py_GIL_DISABLED
1487
1488
static inline Py_ALWAYS_INLINE int
1489
compare_unicode_generic_threadsafe(PyDictObject *mp, PyDictKeysObject *dk,
1490
                                   void *ep0, Py_ssize_t ix, PyObject *key, Py_hash_t hash)
1491
{
1492
    PyDictUnicodeEntry *ep = &((PyDictUnicodeEntry *)ep0)[ix];
1493
    PyObject *startkey = _Py_atomic_load_ptr_consume(&ep->me_key);
1494
    assert(startkey == NULL || PyUnicode_CheckExact(ep->me_key));
1495
    assert(!PyUnicode_CheckExact(key));
1496
1497
    if (startkey != NULL) {
1498
        if (!_Py_TryIncrefCompare(&ep->me_key, startkey)) {
1499
            return DKIX_KEY_CHANGED;
1500
        }
1501
1502
        if (unicode_get_hash(startkey) == hash) {
1503
            int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
1504
            Py_DECREF(startkey);
1505
            if (cmp < 0) {
1506
                return DKIX_ERROR;
1507
            }
1508
            if (dk == _Py_atomic_load_ptr_relaxed(&mp->ma_keys) &&
1509
                startkey == _Py_atomic_load_ptr_relaxed(&ep->me_key)) {
1510
                return cmp;
1511
            }
1512
            else {
1513
                /* The dict was mutated, restart */
1514
                return DKIX_KEY_CHANGED;
1515
            }
1516
        }
1517
        else {
1518
            Py_DECREF(startkey);
1519
        }
1520
    }
1521
    return 0;
1522
}
1523
1524
// Search non-Unicode key from Unicode table
1525
static Py_ssize_t
1526
unicodekeys_lookup_generic_threadsafe(PyDictObject *mp, PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1527
{
1528
    return do_lookup(mp, dk, key, hash, compare_unicode_generic_threadsafe);
1529
}
1530
1531
static inline Py_ALWAYS_INLINE int
1532
compare_unicode_unicode_threadsafe(PyDictObject *mp, PyDictKeysObject *dk,
1533
                                   void *ep0, Py_ssize_t ix, PyObject *key, Py_hash_t hash)
1534
{
1535
    PyDictUnicodeEntry *ep = &((PyDictUnicodeEntry *)ep0)[ix];
1536
    PyObject *startkey = _Py_atomic_load_ptr_consume(&ep->me_key);
1537
    if (startkey == key) {
1538
        assert(PyUnicode_CheckExact(startkey));
1539
        return 1;
1540
    }
1541
    if (startkey != NULL) {
1542
        if (_Py_IsImmortal(startkey)) {
1543
            assert(PyUnicode_CheckExact(startkey));
1544
            return unicode_get_hash(startkey) == hash && unicode_eq(startkey, key);
1545
        }
1546
        else {
1547
            if (!_Py_TryIncrefCompare(&ep->me_key, startkey)) {
1548
                return DKIX_KEY_CHANGED;
1549
            }
1550
            assert(PyUnicode_CheckExact(startkey));
1551
            if (unicode_get_hash(startkey) == hash && unicode_eq(startkey, key)) {
1552
                Py_DECREF(startkey);
1553
                return 1;
1554
            }
1555
            Py_DECREF(startkey);
1556
        }
1557
    }
1558
    return 0;
1559
}
1560
1561
static Py_ssize_t _Py_HOT_FUNCTION
1562
unicodekeys_lookup_unicode_threadsafe(PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1563
{
1564
    return do_lookup(NULL, dk, key, hash, compare_unicode_unicode_threadsafe);
1565
}
1566
1567
static inline Py_ALWAYS_INLINE int
1568
compare_generic_threadsafe(PyDictObject *mp, PyDictKeysObject *dk,
1569
                           void *ep0, Py_ssize_t ix, PyObject *key, Py_hash_t hash)
1570
{
1571
    PyDictKeyEntry *ep = &((PyDictKeyEntry *)ep0)[ix];
1572
    PyObject *startkey = _Py_atomic_load_ptr_consume(&ep->me_key);
1573
    if (startkey == key) {
1574
        return 1;
1575
    }
1576
    Py_ssize_t ep_hash = _Py_atomic_load_ssize_relaxed(&ep->me_hash);
1577
    if (ep_hash == hash) {
1578
        if (startkey == NULL || !_Py_TryIncrefCompare(&ep->me_key, startkey)) {
1579
            return DKIX_KEY_CHANGED;
1580
        }
1581
        int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
1582
        Py_DECREF(startkey);
1583
        if (cmp < 0) {
1584
            return DKIX_ERROR;
1585
        }
1586
        if (dk == _Py_atomic_load_ptr_relaxed(&mp->ma_keys) &&
1587
            startkey == _Py_atomic_load_ptr_relaxed(&ep->me_key)) {
1588
            return cmp;
1589
        }
1590
        else {
1591
            /* The dict was mutated, restart */
1592
            return DKIX_KEY_CHANGED;
1593
        }
1594
    }
1595
    return 0;
1596
}
1597
1598
static Py_ssize_t
1599
dictkeys_generic_lookup_threadsafe(PyDictObject *mp, PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
1600
{
1601
    return do_lookup(mp, dk, key, hash, compare_generic_threadsafe);
1602
}
1603
1604
Py_ssize_t
1605
_Py_dict_lookup_threadsafe(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject **value_addr)
1606
{
1607
    PyDictKeysObject *dk;
1608
    DictKeysKind kind;
1609
    Py_ssize_t ix;
1610
    PyObject *value;
1611
1612
    ensure_shared_on_read(mp);
1613
1614
    dk = _Py_atomic_load_ptr(&mp->ma_keys);
1615
    kind = dk->dk_kind;
1616
1617
    if (kind != DICT_KEYS_GENERAL) {
1618
        if (PyUnicode_CheckExact(key)) {
1619
            ix = unicodekeys_lookup_unicode_threadsafe(dk, key, hash);
1620
        }
1621
        else {
1622
            ix = unicodekeys_lookup_generic_threadsafe(mp, dk, key, hash);
1623
        }
1624
        if (ix == DKIX_KEY_CHANGED) {
1625
            goto read_failed;
1626
        }
1627
1628
        if (ix >= 0) {
1629
            if (kind == DICT_KEYS_SPLIT) {
1630
                PyDictValues *values = _Py_atomic_load_ptr(&mp->ma_values);
1631
                if (values == NULL)
1632
                    goto read_failed;
1633
1634
                uint8_t capacity = _Py_atomic_load_uint8_relaxed(&values->capacity);
1635
                if (ix >= (Py_ssize_t)capacity)
1636
                    goto read_failed;
1637
1638
                value = _Py_TryXGetRef(&values->values[ix]);
1639
                if (value == NULL)
1640
                    goto read_failed;
1641
1642
                if (values != _Py_atomic_load_ptr(&mp->ma_values)) {
1643
                    Py_DECREF(value);
1644
                    goto read_failed;
1645
                }
1646
            }
1647
            else {
1648
                value = _Py_TryXGetRef(&DK_UNICODE_ENTRIES(dk)[ix].me_value);
1649
                if (value == NULL) {
1650
                    goto read_failed;
1651
                }
1652
1653
                if (dk != _Py_atomic_load_ptr(&mp->ma_keys)) {
1654
                    Py_DECREF(value);
1655
                    goto read_failed;
1656
                }
1657
            }
1658
        }
1659
        else {
1660
            value = NULL;
1661
        }
1662
    }
1663
    else {
1664
        ix = dictkeys_generic_lookup_threadsafe(mp, dk, key, hash);
1665
        if (ix == DKIX_KEY_CHANGED) {
1666
            goto read_failed;
1667
        }
1668
        if (ix >= 0) {
1669
            value = _Py_TryXGetRef(&DK_ENTRIES(dk)[ix].me_value);
1670
            if (value == NULL)
1671
                goto read_failed;
1672
1673
            if (dk != _Py_atomic_load_ptr(&mp->ma_keys)) {
1674
                Py_DECREF(value);
1675
                goto read_failed;
1676
            }
1677
        }
1678
        else {
1679
            value = NULL;
1680
        }
1681
    }
1682
1683
    *value_addr = value;
1684
    return ix;
1685
1686
read_failed:
1687
    // In addition to the normal races of the dict being modified the _Py_TryXGetRef
1688
    // can all fail if they don't yet have a shared ref count.  That can happen here
1689
    // or in the *_lookup_* helper.  In that case we need to take the lock to avoid
1690
    // mutation and do a normal incref which will make them shared.
1691
    Py_BEGIN_CRITICAL_SECTION(mp);
1692
    ix = _Py_dict_lookup(mp, key, hash, &value);
1693
    *value_addr = value;
1694
    if (value != NULL) {
1695
        assert(ix >= 0);
1696
        _Py_NewRefWithLock(value);
1697
    }
1698
    Py_END_CRITICAL_SECTION();
1699
    return ix;
1700
}
1701
1702
static Py_ssize_t
1703
lookup_threadsafe_unicode(PyDictKeysObject *dk, PyObject *key, Py_hash_t hash, _PyStackRef *value_addr)
1704
{
1705
    assert(dk->dk_kind == DICT_KEYS_UNICODE);
1706
    assert(PyUnicode_CheckExact(key));
1707
1708
    Py_ssize_t ix = unicodekeys_lookup_unicode_threadsafe(dk, key, hash);
1709
    if (ix == DKIX_EMPTY) {
1710
        *value_addr = PyStackRef_NULL;
1711
        return ix;
1712
    }
1713
    else if (ix >= 0) {
1714
        PyObject **addr_of_value = &DK_UNICODE_ENTRIES(dk)[ix].me_value;
1715
        PyObject *value = _Py_atomic_load_ptr(addr_of_value);
1716
        if (value == NULL) {
1717
            *value_addr = PyStackRef_NULL;
1718
            return DKIX_EMPTY;
1719
        }
1720
        if (_PyObject_HasDeferredRefcount(value)) {
1721
            *value_addr =  (_PyStackRef){ .bits = (uintptr_t)value | Py_TAG_REFCNT };
1722
            return ix;
1723
        }
1724
        if (_Py_TryIncrefCompare(addr_of_value, value)) {
1725
            *value_addr = PyStackRef_FromPyObjectSteal(value);
1726
            return ix;
1727
        }
1728
        return DKIX_KEY_CHANGED;
1729
    }
1730
    assert(ix == DKIX_KEY_CHANGED);
1731
    return ix;
1732
}
1733
1734
Py_ssize_t
1735
_Py_dict_lookup_threadsafe_stackref(PyDictObject *mp, PyObject *key, Py_hash_t hash, _PyStackRef *value_addr)
1736
{
1737
    ensure_shared_on_read(mp);
1738
1739
    PyDictKeysObject *dk = _Py_atomic_load_ptr_acquire(&mp->ma_keys);
1740
    if (dk->dk_kind == DICT_KEYS_UNICODE && PyUnicode_CheckExact(key)) {
1741
        Py_ssize_t ix = lookup_threadsafe_unicode(dk, key, hash, value_addr);
1742
        if (ix != DKIX_KEY_CHANGED) {
1743
            return ix;
1744
        }
1745
    }
1746
1747
    PyObject *obj;
1748
    Py_ssize_t ix = _Py_dict_lookup_threadsafe(mp, key, hash, &obj);
1749
    if (ix >= 0 && obj != NULL) {
1750
        *value_addr = PyStackRef_FromPyObjectSteal(obj);
1751
    }
1752
    else {
1753
        *value_addr = PyStackRef_NULL;
1754
    }
1755
    return ix;
1756
}
1757
1758
#else   // Py_GIL_DISABLED
1759
1760
Py_ssize_t
1761
_Py_dict_lookup_threadsafe(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject **value_addr)
1762
1.59G
{
1763
1.59G
    Py_ssize_t ix = _Py_dict_lookup(mp, key, hash, value_addr);
1764
1.59G
    Py_XNewRef(*value_addr);
1765
1.59G
    return ix;
1766
1.59G
}
1767
1768
Py_ssize_t
1769
_Py_dict_lookup_threadsafe_stackref(PyDictObject *mp, PyObject *key, Py_hash_t hash, _PyStackRef *value_addr)
1770
54.3M
{
1771
54.3M
    PyObject *val;
1772
54.3M
    Py_ssize_t ix = _Py_dict_lookup(mp, key, hash, &val);
1773
54.3M
    if (val == NULL) {
1774
29.8M
        *value_addr = PyStackRef_NULL;
1775
29.8M
    }
1776
24.4M
    else {
1777
24.4M
        *value_addr = PyStackRef_FromPyObjectNew(val);
1778
24.4M
    }
1779
54.3M
    return ix;
1780
54.3M
}
1781
1782
#endif
1783
1784
// Looks up the unicode key `key` in the dictionary. Note that `*method` may
1785
// already contain a valid value! See _PyObject_GetMethodStackRef().
1786
int
1787
_PyDict_GetMethodStackRef(PyDictObject *mp, PyObject *key, _PyStackRef *method)
1788
45.5M
{
1789
45.5M
    assert(PyUnicode_CheckExact(key));
1790
45.5M
    Py_hash_t hash = hash_unicode_key(key);
1791
1792
#ifdef Py_GIL_DISABLED
1793
    // NOTE: We can only do the fast-path lookup if we are on the owning
1794
    // thread or if the dict is already marked as shared so that the load
1795
    // of ma_keys is safe without a lock. We cannot call ensure_shared_on_read()
1796
    // in this code path without incref'ing the dict because the dict is a
1797
    // borrowed reference protected by QSBR, and acquiring the lock could lead
1798
    // to a quiescent state (allowing the dict to be freed).
1799
    if (_Py_IsOwnedByCurrentThread((PyObject *)mp) || IS_DICT_SHARED(mp)) {
1800
        PyDictKeysObject *dk = _Py_atomic_load_ptr_acquire(&mp->ma_keys);
1801
        if (dk->dk_kind == DICT_KEYS_UNICODE) {
1802
            _PyStackRef ref;
1803
            Py_ssize_t ix = lookup_threadsafe_unicode(dk, key, hash, &ref);
1804
            if (ix >= 0) {
1805
                assert(!PyStackRef_IsNull(ref));
1806
                PyStackRef_XSETREF(*method, ref);
1807
                return 1;
1808
            }
1809
            else if (ix == DKIX_EMPTY) {
1810
                return 0;
1811
            }
1812
            assert(ix == DKIX_KEY_CHANGED);
1813
        }
1814
    }
1815
#endif
1816
1817
45.5M
    PyObject *obj;
1818
45.5M
    Py_INCREF(mp);
1819
45.5M
    Py_ssize_t ix = _Py_dict_lookup_threadsafe(mp, key, hash, &obj);
1820
45.5M
    Py_DECREF(mp);
1821
45.5M
    if (ix == DKIX_ERROR) {
1822
0
        PyStackRef_CLEAR(*method);
1823
0
        return -1;
1824
0
    }
1825
45.5M
    else if (ix >= 0 && obj != NULL) {
1826
14
        PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectSteal(obj));
1827
14
        return 1;
1828
14
    }
1829
45.5M
    return 0;  // not found
1830
45.5M
}
1831
1832
int
1833
_PyDict_HasOnlyStringKeys(PyObject *dict)
1834
282k
{
1835
282k
    Py_ssize_t pos = 0;
1836
282k
    PyObject *key, *value;
1837
282k
    assert(PyDict_Check(dict));
1838
    /* Shortcut */
1839
282k
    if (((PyDictObject *)dict)->ma_keys->dk_kind != DICT_KEYS_GENERAL)
1840
282k
        return 1;
1841
0
    while (PyDict_Next(dict, &pos, &key, &value))
1842
0
        if (!PyUnicode_Check(key))
1843
0
            return 0;
1844
0
    return 1;
1845
0
}
1846
1847
void
1848
_PyDict_EnablePerThreadRefcounting(PyObject *op)
1849
3.86k
{
1850
3.86k
    assert(PyDict_Check(op));
1851
#ifdef Py_GIL_DISABLED
1852
    Py_ssize_t id = _PyObject_AssignUniqueId(op);
1853
    if (id == _Py_INVALID_UNIQUE_ID) {
1854
        return;
1855
    }
1856
    if ((uint64_t)id >= (uint64_t)DICT_UNIQUE_ID_MAX) {
1857
        _PyObject_ReleaseUniqueId(id);
1858
        return;
1859
    }
1860
1861
    PyDictObject *mp = (PyDictObject *)op;
1862
    assert((mp->_ma_watcher_tag >> DICT_UNIQUE_ID_SHIFT) == 0);
1863
    mp->_ma_watcher_tag += (uint64_t)id << DICT_UNIQUE_ID_SHIFT;
1864
#endif
1865
3.86k
}
1866
1867
static inline int
1868
is_unusable_slot(Py_ssize_t ix)
1869
146M
{
1870
#ifdef Py_GIL_DISABLED
1871
    return ix >= 0 || ix == DKIX_DUMMY;
1872
#else
1873
146M
    return ix >= 0;
1874
146M
#endif
1875
146M
}
1876
1877
/* Internal function to find slot for an item from its hash
1878
   when it is known that the key is not present in the dict.
1879
 */
1880
static Py_ssize_t
1881
find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
1882
114M
{
1883
114M
    assert(keys != NULL);
1884
1885
114M
    const size_t mask = DK_MASK(keys);
1886
114M
    size_t i = hash & mask;
1887
114M
    Py_ssize_t ix = dictkeys_get_index(keys, i);
1888
146M
    for (size_t perturb = hash; is_unusable_slot(ix);) {
1889
32.3M
        perturb >>= PERTURB_SHIFT;
1890
32.3M
        i = (i*5 + perturb + 1) & mask;
1891
32.3M
        ix = dictkeys_get_index(keys, i);
1892
32.3M
    }
1893
114M
    return i;
1894
114M
}
1895
1896
static int
1897
insertion_resize(PyDictObject *mp, int unicode)
1898
6.85M
{
1899
6.85M
    return dictresize(mp, calculate_log2_keysize(GROWTH_RATE(mp)), unicode);
1900
6.85M
}
1901
1902
static inline int
1903
insert_combined_dict(PyDictObject *mp,
1904
                     Py_hash_t hash, PyObject *key, PyObject *value)
1905
112M
{
1906
    // gh-140551: If dict was cleared in _Py_dict_lookup,
1907
    // we have to resize one more time to force general key kind.
1908
112M
    if (DK_IS_UNICODE(mp->ma_keys) && !PyUnicode_CheckExact(key)) {
1909
2.18k
        if (insertion_resize(mp, 0) < 0)
1910
0
            return -1;
1911
2.18k
        assert(mp->ma_keys->dk_kind == DICT_KEYS_GENERAL);
1912
2.18k
    }
1913
1914
112M
    if (mp->ma_keys->dk_usable <= 0) {
1915
        /* Need to resize. */
1916
6.85M
        if (insertion_resize(mp, 1) < 0) {
1917
0
            return -1;
1918
0
        }
1919
6.85M
    }
1920
1921
112M
    _PyDict_NotifyEvent(PyDict_EVENT_ADDED, mp, key, value);
1922
112M
    FT_ATOMIC_STORE_UINT32_RELAXED(mp->ma_keys->dk_version, 0);
1923
1924
112M
    Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
1925
112M
    dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
1926
1927
112M
    if (DK_IS_UNICODE(mp->ma_keys)) {
1928
36.0M
        PyDictUnicodeEntry *ep;
1929
36.0M
        ep = &DK_UNICODE_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
1930
36.0M
        STORE_KEY(ep, key);
1931
36.0M
        STORE_VALUE(ep, value);
1932
36.0M
    }
1933
76.3M
    else {
1934
76.3M
        PyDictKeyEntry *ep;
1935
76.3M
        ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
1936
76.3M
        STORE_KEY(ep, key);
1937
76.3M
        STORE_VALUE(ep, value);
1938
76.3M
        STORE_HASH(ep, hash);
1939
76.3M
    }
1940
112M
    STORE_KEYS_USABLE(mp->ma_keys, mp->ma_keys->dk_usable - 1);
1941
112M
    STORE_KEYS_NENTRIES(mp->ma_keys, mp->ma_keys->dk_nentries + 1);
1942
112M
    assert(mp->ma_keys->dk_usable >= 0);
1943
112M
    return 0;
1944
112M
}
1945
1946
static Py_ssize_t
1947
insert_split_key(PyDictKeysObject *keys, PyObject *key, Py_hash_t hash)
1948
18.7M
{
1949
18.7M
    assert(PyUnicode_CheckExact(key));
1950
18.7M
    Py_ssize_t ix;
1951
1952
1953
#ifdef Py_GIL_DISABLED
1954
    ix = unicodekeys_lookup_unicode_threadsafe(keys, key, hash);
1955
    if (ix >= 0) {
1956
        return ix;
1957
    }
1958
1959
    // We need to acquire the type lock before the keys mutex. Another lock
1960
    // is never acquired below the keys mutex but a keys mutex can be acquired
1961
    // elsewhere while we hold the types lock. To avoid deadlocks we must always
1962
    // acquire the type lock first.
1963
    Py_BEGIN_CRITICAL_SECTION_MUTEX(&_PyInterpreterState_GET()->types.mutex);
1964
#endif
1965
1966
18.7M
    LOCK_KEYS(keys);
1967
18.7M
    ix = unicodekeys_lookup_unicode(keys, key, hash);
1968
18.7M
    if (ix == DKIX_EMPTY && keys->dk_usable > 0) {
1969
        // Insert into new slot
1970
1.61M
        FT_ATOMIC_STORE_UINT32_RELAXED(keys->dk_version, 0);
1971
1.61M
        struct _instancekeysobject *shared_keys = _PyDictKeys_AsSharedKeys(keys);
1972
1.61M
        PyTypeObject *type = FT_ATOMIC_LOAD_PTR_ACQUIRE(shared_keys->dsk_owning_type);
1973
1.61M
        if (type) {
1974
            // we acquired the type lock above
1975
1.61M
            _PyType_Modified_Unlocked(type);
1976
1.61M
        }
1977
1.61M
        Py_ssize_t hashpos = find_empty_slot(keys, hash);
1978
1.61M
        ix = keys->dk_nentries;
1979
1.61M
        dictkeys_set_index(keys, hashpos, ix);
1980
1.61M
        PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(keys)[ix];
1981
1.61M
        STORE_SHARED_KEY(ep->me_key, Py_NewRef(key));
1982
1.61M
        split_keys_entry_added(keys);
1983
1.61M
    }
1984
18.7M
    assert (ix < SHARED_KEYS_MAX_SIZE);
1985
18.7M
    UNLOCK_KEYS(keys);
1986
1987
#ifdef Py_GIL_DISABLED
1988
    Py_END_CRITICAL_SECTION();
1989
#endif
1990
18.7M
    return ix;
1991
18.7M
}
1992
1993
void
1994
_PyDict_InsertSplitValue(PyDictObject *mp, PyObject *key, PyObject *value, Py_ssize_t ix)
1995
228k
{
1996
228k
    assert(can_modify_dict(mp));
1997
228k
    assert(PyUnicode_CheckExact(key));
1998
1999
228k
    PyObject *old_value = mp->ma_values->values[ix];
2000
228k
    if (old_value == NULL) {
2001
195k
        _PyDict_NotifyEvent(PyDict_EVENT_ADDED, mp, key, value);
2002
195k
        STORE_SPLIT_VALUE(mp, ix, Py_NewRef(value));
2003
195k
        _PyDictValues_AddToInsertionOrder(mp->ma_values, ix);
2004
195k
        STORE_USED(mp, mp->ma_used + 1);
2005
195k
    }
2006
33.1k
    else {
2007
33.1k
        _PyDict_NotifyEvent(PyDict_EVENT_MODIFIED, mp, key, value);
2008
33.1k
        STORE_SPLIT_VALUE(mp, ix, Py_NewRef(value));
2009
        // old_value should be DECREFed after GC track checking is done, if not, it could raise a segmentation fault,
2010
        // when dict only holds the strong reference to value in ep->me_value.
2011
33.1k
        Py_DECREF(old_value);
2012
33.1k
    }
2013
228k
    ASSERT_CONSISTENT(mp);
2014
228k
}
2015
2016
// Replace a value at an existing entry. Steals the new value reference.
2017
static void
2018
replace_value(PyDictObject *mp, PyObject *key, Py_ssize_t ix,
2019
              PyObject *old_value, PyObject *value)
2020
74.0M
{
2021
74.0M
    assert(can_modify_dict(mp));
2022
74.0M
    assert(old_value != NULL);
2023
2024
74.0M
    if (old_value != value) {
2025
35.7M
        _PyDict_NotifyEvent(PyDict_EVENT_MODIFIED, mp, key, value);
2026
35.7M
        if (DK_IS_UNICODE(mp->ma_keys)) {
2027
35.5M
            if (_PyDict_HasSplitTable(mp)) {
2028
0
                STORE_SPLIT_VALUE(mp, ix, value);
2029
0
            }
2030
35.5M
            else {
2031
35.5M
                PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(mp->ma_keys)[ix];
2032
35.5M
                STORE_VALUE(ep, value);
2033
35.5M
            }
2034
35.5M
        }
2035
217k
        else {
2036
217k
            PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[ix];
2037
217k
            STORE_VALUE(ep, value);
2038
217k
        }
2039
35.7M
    }
2040
74.0M
    Py_DECREF(old_value); /* which **CAN** re-enter (see gh-66843) */
2041
2042
74.0M
    ASSERT_CONSISTENT(mp);
2043
74.0M
}
2044
2045
/*
2046
Internal routine to insert a new item into the table.
2047
Used both by the internal resize routine and by the public insert routine.
2048
Returns -1 if an error occurred, or 0 on success.
2049
Consumes key and value references.
2050
*/
2051
static int
2052
insertdict(PyDictObject *mp,
2053
           PyObject *key, Py_hash_t hash, PyObject *value)
2054
185M
{
2055
185M
    assert(can_modify_dict(mp));
2056
2057
185M
    PyObject *old_value = NULL;
2058
185M
    Py_ssize_t ix;
2059
2060
185M
    if (_PyDict_HasSplitTable(mp) && PyUnicode_CheckExact(key)) {
2061
884k
        ix = insert_split_key(mp->ma_keys, key, hash);
2062
884k
        if (ix != DKIX_EMPTY) {
2063
228k
            _PyDict_InsertSplitValue(mp, key, value, ix);
2064
228k
            Py_DECREF(key);
2065
228k
            Py_DECREF(value);
2066
228k
            return 0;
2067
228k
        }
2068
        // No space in shared keys. Go to insert_combined_dict() below.
2069
884k
    }
2070
184M
    else {
2071
184M
        ix = _Py_dict_lookup(mp, key, hash, &old_value);
2072
184M
        if (ix == DKIX_ERROR)
2073
0
            goto Fail;
2074
184M
    }
2075
2076
185M
    if (old_value == NULL) {
2077
        // insert_combined_dict() will convert from non DICT_KEYS_GENERAL table
2078
        // into DICT_KEYS_GENERAL table if key is not Unicode.
2079
        // We don't convert it before _Py_dict_lookup because non-Unicode key
2080
        // may change generic table into Unicode table.
2081
        //
2082
        // NOTE: ix may not be DKIX_EMPTY because split table may have key
2083
        // without value.
2084
111M
        if (insert_combined_dict(mp, hash, key, value) < 0) {
2085
0
            goto Fail;
2086
0
        }
2087
111M
        STORE_USED(mp, mp->ma_used + 1);
2088
111M
        ASSERT_CONSISTENT(mp);
2089
111M
        return 0;
2090
111M
    }
2091
2092
74.0M
    replace_value(mp, key, ix, old_value, value);
2093
74.0M
    Py_DECREF(key);
2094
74.0M
    return 0;
2095
2096
0
Fail:
2097
0
    Py_DECREF(value);
2098
0
    Py_DECREF(key);
2099
0
    return -1;
2100
185M
}
2101
2102
// Same as insertdict but specialized for ma_keys == Py_EMPTY_KEYS.
2103
// Consumes key and value references.
2104
static int
2105
insert_to_emptydict(PyDictObject *mp,
2106
                    PyObject *key, Py_hash_t hash, PyObject *value)
2107
50.7M
{
2108
50.7M
    assert(can_modify_dict(mp));
2109
50.7M
    assert(mp->ma_keys == Py_EMPTY_KEYS);
2110
2111
50.7M
    int unicode = PyUnicode_CheckExact(key);
2112
50.7M
    PyDictKeysObject *newkeys = new_keys_object(PyDict_LOG_MINSIZE, unicode);
2113
50.7M
    if (newkeys == NULL) {
2114
0
        Py_DECREF(key);
2115
0
        Py_DECREF(value);
2116
0
        return -1;
2117
0
    }
2118
50.7M
    _PyDict_NotifyEvent(PyDict_EVENT_ADDED, mp, key, value);
2119
2120
    /* We don't decref Py_EMPTY_KEYS here because it is immortal. */
2121
50.7M
    assert(mp->ma_values == NULL);
2122
2123
50.7M
    size_t hashpos = (size_t)hash & (PyDict_MINSIZE-1);
2124
50.7M
    dictkeys_set_index(newkeys, hashpos, 0);
2125
50.7M
    if (unicode) {
2126
46.4M
        PyDictUnicodeEntry *ep = DK_UNICODE_ENTRIES(newkeys);
2127
46.4M
        ep->me_key = key;
2128
46.4M
        STORE_VALUE(ep, value);
2129
46.4M
    }
2130
4.25M
    else {
2131
4.25M
        PyDictKeyEntry *ep = DK_ENTRIES(newkeys);
2132
4.25M
        ep->me_key = key;
2133
4.25M
        ep->me_hash = hash;
2134
4.25M
        STORE_VALUE(ep, value);
2135
4.25M
    }
2136
50.7M
    STORE_USED(mp, mp->ma_used + 1);
2137
50.7M
    newkeys->dk_usable--;
2138
50.7M
    newkeys->dk_nentries++;
2139
    // We store the keys last so no one can see them in a partially inconsistent
2140
    // state so that we don't need to switch the keys to being shared yet for
2141
    // the case where we're inserting from the non-owner thread.  We don't use
2142
    // set_keys here because the transition from empty to non-empty is safe
2143
    // as the empty keys will never be freed.
2144
50.7M
    FT_ATOMIC_STORE_PTR_RELEASE(mp->ma_keys, newkeys);
2145
50.7M
    return 0;
2146
50.7M
}
2147
2148
/*
2149
Internal routine used by dictresize() to build a hashtable of entries.
2150
*/
2151
static void
2152
build_indices_generic(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
2153
5.83M
{
2154
5.83M
    size_t mask = DK_MASK(keys);
2155
102M
    for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
2156
96.8M
        Py_hash_t hash = ep->me_hash;
2157
96.8M
        size_t i = hash & mask;
2158
102M
        for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
2159
5.48M
            perturb >>= PERTURB_SHIFT;
2160
5.48M
            i = mask & (i*5 + perturb + 1);
2161
5.48M
        }
2162
96.8M
        dictkeys_set_index(keys, i, ix);
2163
96.8M
    }
2164
5.83M
}
2165
2166
static void
2167
build_indices_unicode(PyDictKeysObject *keys, PyDictUnicodeEntry *ep, Py_ssize_t n)
2168
1.55M
{
2169
1.55M
    size_t mask = DK_MASK(keys);
2170
11.4M
    for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
2171
9.88M
        Py_hash_t hash = unicode_get_hash(ep->me_key);
2172
9.88M
        assert(hash != -1);
2173
9.88M
        size_t i = hash & mask;
2174
11.4M
        for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
2175
1.56M
            perturb >>= PERTURB_SHIFT;
2176
1.56M
            i = mask & (i*5 + perturb + 1);
2177
1.56M
        }
2178
9.88M
        dictkeys_set_index(keys, i, ix);
2179
9.88M
    }
2180
1.55M
}
2181
2182
static void
2183
invalidate_and_clear_inline_values(PyDictValues *values)
2184
726k
{
2185
726k
    assert(values->embedded);
2186
726k
    FT_ATOMIC_STORE_UINT8(values->valid, 0);
2187
3.66M
    for (int i = 0; i < values->capacity; i++) {
2188
2.93M
        FT_ATOMIC_STORE_PTR_RELEASE(values->values[i], NULL);
2189
2.93M
    }
2190
726k
}
2191
2192
/*
2193
Restructure the table by allocating a new table and reinserting all
2194
items again.  When entries have been deleted, the new table may
2195
actually be smaller than the old one.
2196
If a table is split (its keys and hashes are shared, its values are not),
2197
then the values are temporarily copied into the table, it is resized as
2198
a combined table, then the me_value slots in the old table are NULLed out.
2199
After resizing, a table is always combined.
2200
2201
This function supports:
2202
 - Unicode split -> Unicode combined or Generic
2203
 - Unicode combined -> Unicode combined or Generic
2204
 - Generic -> Generic
2205
*/
2206
static int
2207
dictresize(PyDictObject *mp,
2208
           uint8_t log2_newsize, int unicode)
2209
6.85M
{
2210
6.85M
    assert(can_modify_dict(mp));
2211
2212
6.85M
    PyDictKeysObject *oldkeys, *newkeys;
2213
6.85M
    PyDictValues *oldvalues;
2214
2215
6.85M
    if (log2_newsize >= SIZEOF_SIZE_T*8) {
2216
0
        PyErr_NoMemory();
2217
0
        return -1;
2218
0
    }
2219
6.85M
    assert(log2_newsize >= PyDict_LOG_MINSIZE);
2220
2221
6.85M
    oldkeys = mp->ma_keys;
2222
6.85M
    oldvalues = mp->ma_values;
2223
2224
6.85M
    if (!DK_IS_UNICODE(oldkeys)) {
2225
5.83M
        unicode = 0;
2226
5.83M
    }
2227
2228
6.85M
    ensure_shared_on_resize(mp);
2229
    /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
2230
     * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
2231
     * TODO: Try reusing oldkeys when reimplement odict.
2232
     */
2233
2234
    /* Allocate a new table. */
2235
6.85M
    newkeys = new_keys_object(log2_newsize, unicode);
2236
6.85M
    if (newkeys == NULL) {
2237
0
        return -1;
2238
0
    }
2239
    // New table must be large enough.
2240
6.85M
    assert(newkeys->dk_usable >= mp->ma_used);
2241
2242
6.85M
    Py_ssize_t numentries = mp->ma_used;
2243
2244
6.85M
    if (oldvalues != NULL) {
2245
655k
        LOCK_KEYS(oldkeys);
2246
655k
        PyDictUnicodeEntry *oldentries = DK_UNICODE_ENTRIES(oldkeys);
2247
        /* Convert split table into new combined table.
2248
         * We must incref keys; we can transfer values.
2249
         */
2250
655k
        if (newkeys->dk_kind == DICT_KEYS_GENERAL) {
2251
            // split -> generic
2252
0
            PyDictKeyEntry *newentries = DK_ENTRIES(newkeys);
2253
2254
0
            for (Py_ssize_t i = 0; i < numentries; i++) {
2255
0
                int index = get_index_from_order(mp, i);
2256
0
                PyDictUnicodeEntry *ep = &oldentries[index];
2257
0
                assert(oldvalues->values[index] != NULL);
2258
0
                newentries[i].me_key = Py_NewRef(ep->me_key);
2259
0
                newentries[i].me_hash = unicode_get_hash(ep->me_key);
2260
0
                newentries[i].me_value = oldvalues->values[index];
2261
0
            }
2262
0
            build_indices_generic(newkeys, newentries, numentries);
2263
0
        }
2264
655k
        else { // split -> combined unicode
2265
655k
            PyDictUnicodeEntry *newentries = DK_UNICODE_ENTRIES(newkeys);
2266
2267
2.19M
            for (Py_ssize_t i = 0; i < numentries; i++) {
2268
1.54M
                int index = get_index_from_order(mp, i);
2269
1.54M
                PyDictUnicodeEntry *ep = &oldentries[index];
2270
1.54M
                assert(oldvalues->values[index] != NULL);
2271
1.54M
                newentries[i].me_key = Py_NewRef(ep->me_key);
2272
1.54M
                newentries[i].me_value = oldvalues->values[index];
2273
1.54M
            }
2274
655k
            build_indices_unicode(newkeys, newentries, numentries);
2275
655k
        }
2276
655k
        UNLOCK_KEYS(oldkeys);
2277
655k
        set_keys(mp, newkeys);
2278
655k
        dictkeys_decref(oldkeys, IS_DICT_SHARED(mp));
2279
655k
        if (oldvalues->embedded) {
2280
649k
            assert(oldvalues->embedded == 1);
2281
649k
            assert(oldvalues->valid == 1);
2282
649k
            invalidate_and_clear_inline_values(oldvalues);
2283
649k
        }
2284
6.62k
        else {
2285
6.62k
            free_values(oldvalues, IS_DICT_SHARED(mp));
2286
6.62k
        }
2287
655k
        set_values(mp, NULL);
2288
655k
    }
2289
6.19M
    else {  // oldkeys is combined.
2290
6.19M
        if (oldkeys->dk_kind == DICT_KEYS_GENERAL) {
2291
            // generic -> generic
2292
5.83M
            assert(newkeys->dk_kind == DICT_KEYS_GENERAL);
2293
5.83M
            PyDictKeyEntry *oldentries = DK_ENTRIES(oldkeys);
2294
5.83M
            PyDictKeyEntry *newentries = DK_ENTRIES(newkeys);
2295
5.83M
            if (oldkeys->dk_nentries == numentries) {
2296
5.80M
                memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
2297
5.80M
            }
2298
30.8k
            else {
2299
30.8k
                PyDictKeyEntry *ep = oldentries;
2300
420k
                for (Py_ssize_t i = 0; i < numentries; i++) {
2301
1.04M
                    while (ep->me_value == NULL)
2302
658k
                        ep++;
2303
389k
                    newentries[i] = *ep++;
2304
389k
                }
2305
30.8k
            }
2306
5.83M
            build_indices_generic(newkeys, newentries, numentries);
2307
5.83M
        }
2308
368k
        else {  // oldkeys is combined unicode
2309
368k
            PyDictUnicodeEntry *oldentries = DK_UNICODE_ENTRIES(oldkeys);
2310
368k
            if (unicode) { // combined unicode -> combined unicode
2311
366k
                PyDictUnicodeEntry *newentries = DK_UNICODE_ENTRIES(newkeys);
2312
366k
                if (oldkeys->dk_nentries == numentries && mp->ma_keys->dk_kind == DICT_KEYS_UNICODE) {
2313
317k
                    memcpy(newentries, oldentries, numentries * sizeof(PyDictUnicodeEntry));
2314
317k
                }
2315
48.0k
                else {
2316
48.0k
                    PyDictUnicodeEntry *ep = oldentries;
2317
408k
                    for (Py_ssize_t i = 0; i < numentries; i++) {
2318
446k
                        while (ep->me_value == NULL)
2319
86.5k
                            ep++;
2320
360k
                        newentries[i] = *ep++;
2321
360k
                    }
2322
48.0k
                }
2323
366k
                build_indices_unicode(newkeys, newentries, numentries);
2324
366k
            }
2325
2.18k
            else { // combined unicode -> generic
2326
2.18k
                PyDictKeyEntry *newentries = DK_ENTRIES(newkeys);
2327
2.18k
                PyDictUnicodeEntry *ep = oldentries;
2328
7.19k
                for (Py_ssize_t i = 0; i < numentries; i++) {
2329
5.01k
                    while (ep->me_value == NULL)
2330
0
                        ep++;
2331
5.01k
                    newentries[i].me_key = ep->me_key;
2332
5.01k
                    newentries[i].me_hash = unicode_get_hash(ep->me_key);
2333
5.01k
                    newentries[i].me_value = ep->me_value;
2334
5.01k
                    ep++;
2335
5.01k
                }
2336
2.18k
                build_indices_generic(newkeys, newentries, numentries);
2337
2.18k
            }
2338
368k
        }
2339
2340
6.19M
        set_keys(mp, newkeys);
2341
2342
6.19M
        if (oldkeys != Py_EMPTY_KEYS) {
2343
#ifdef Py_REF_DEBUG
2344
            _Py_DecRefTotal(_PyThreadState_GET());
2345
#endif
2346
6.19M
            assert(oldkeys->dk_kind != DICT_KEYS_SPLIT);
2347
6.19M
            assert(oldkeys->dk_refcnt == 1);
2348
6.19M
            free_keys_object(oldkeys, IS_DICT_SHARED(mp));
2349
6.19M
        }
2350
6.19M
    }
2351
2352
6.85M
    STORE_KEYS_USABLE(mp->ma_keys, mp->ma_keys->dk_usable - numentries);
2353
6.85M
    STORE_KEYS_NENTRIES(mp->ma_keys, numentries);
2354
6.85M
    ASSERT_CONSISTENT(mp);
2355
6.85M
    return 0;
2356
6.85M
}
2357
2358
static PyObject *
2359
dict_new_presized(Py_ssize_t minused, bool unicode)
2360
99.2M
{
2361
99.2M
    const uint8_t log2_max_presize = 17;
2362
99.2M
    const Py_ssize_t max_presize = ((Py_ssize_t)1) << log2_max_presize;
2363
99.2M
    uint8_t log2_newsize;
2364
99.2M
    PyDictKeysObject *new_keys;
2365
2366
99.2M
    if (minused <= USABLE_FRACTION(PyDict_MINSIZE)) {
2367
99.2M
        return PyDict_New();
2368
99.2M
    }
2369
    /* There are no strict guarantee that returned dict can contain minused
2370
     * items without resize.  So we create medium size dict instead of very
2371
     * large dict or MemoryError.
2372
     */
2373
10.3k
    if (minused > USABLE_FRACTION(max_presize)) {
2374
0
        log2_newsize = log2_max_presize;
2375
0
    }
2376
10.3k
    else {
2377
10.3k
        log2_newsize = estimate_log2_keysize(minused);
2378
10.3k
    }
2379
2380
10.3k
    new_keys = new_keys_object(log2_newsize, unicode);
2381
10.3k
    if (new_keys == NULL)
2382
0
        return NULL;
2383
10.3k
    return new_dict(new_keys, NULL, 0, 0);
2384
10.3k
}
2385
2386
PyObject *
2387
_PyDict_NewPresized(Py_ssize_t minused)
2388
0
{
2389
0
    return dict_new_presized(minused, false);
2390
0
}
2391
2392
PyObject *
2393
_PyDict_FromItems(PyObject *const *keys, Py_ssize_t keys_offset,
2394
                  PyObject *const *values, Py_ssize_t values_offset,
2395
                  Py_ssize_t length)
2396
99.2M
{
2397
99.2M
    bool unicode = true;
2398
99.2M
    PyObject *const *ks = keys;
2399
2400
128M
    for (Py_ssize_t i = 0; i < length; i++) {
2401
29.2M
        if (!PyUnicode_CheckExact(*ks)) {
2402
45.5k
            unicode = false;
2403
45.5k
            break;
2404
45.5k
        }
2405
29.2M
        ks += keys_offset;
2406
29.2M
    }
2407
2408
99.2M
    PyObject *dict = dict_new_presized(length, unicode);
2409
99.2M
    if (dict == NULL) {
2410
0
        return NULL;
2411
0
    }
2412
2413
99.2M
    ks = keys;
2414
99.2M
    PyObject *const *vs = values;
2415
2416
128M
    for (Py_ssize_t i = 0; i < length; i++) {
2417
29.4M
        PyObject *key = *ks;
2418
29.4M
        PyObject *value = *vs;
2419
29.4M
        if (setitem_lock_held((PyDictObject *)dict, key, value) < 0) {
2420
0
            Py_DECREF(dict);
2421
0
            return NULL;
2422
0
        }
2423
29.4M
        ks += keys_offset;
2424
29.4M
        vs += values_offset;
2425
29.4M
    }
2426
2427
99.2M
    return dict;
2428
99.2M
}
2429
2430
/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
2431
 * that may occur (originally dicts supported only string keys, and exceptions
2432
 * weren't possible).  So, while the original intent was that a NULL return
2433
 * meant the key wasn't present, in reality it can mean that, or that an error
2434
 * (suppressed) occurred while computing the key's hash, or that some error
2435
 * (suppressed) occurred when comparing keys in the dict's internal probe
2436
 * sequence.  A nasty example of the latter is when a Python-coded comparison
2437
 * function hits a stack-depth error, which can cause this to return NULL
2438
 * even if the key is present.
2439
 */
2440
static PyObject *
2441
dict_getitem(PyObject *op, PyObject *key, const char *warnmsg)
2442
278k
{
2443
278k
    if (!PyAnyDict_Check(op)) {
2444
0
        return NULL;
2445
0
    }
2446
278k
    PyDictObject *mp = (PyDictObject *)op;
2447
2448
278k
    Py_hash_t hash = _PyObject_HashDictKey(key);
2449
278k
    if (hash == -1) {
2450
0
        PyErr_FormatUnraisable(warnmsg);
2451
0
        return NULL;
2452
0
    }
2453
2454
278k
    PyThreadState *tstate = _PyThreadState_GET();
2455
#ifdef Py_DEBUG
2456
    // bpo-40839: Before Python 3.10, it was possible to call PyDict_GetItem()
2457
    // with the GIL released.
2458
    _Py_EnsureTstateNotNULL(tstate);
2459
#endif
2460
2461
    /* Preserve the existing exception */
2462
278k
    PyObject *value;
2463
278k
    Py_ssize_t ix; (void)ix;
2464
2465
278k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
2466
#ifdef Py_GIL_DISABLED
2467
    ix = _Py_dict_lookup_threadsafe(mp, key, hash, &value);
2468
    Py_XDECREF(value);
2469
#else
2470
278k
    ix = _Py_dict_lookup(mp, key, hash, &value);
2471
278k
#endif
2472
2473
    /* Ignore any exception raised by the lookup */
2474
278k
    PyObject *exc2 = _PyErr_Occurred(tstate);
2475
278k
    if (exc2 && !PyErr_GivenExceptionMatches(exc2, PyExc_KeyError)) {
2476
0
        PyErr_FormatUnraisable(warnmsg);
2477
0
    }
2478
278k
    _PyErr_SetRaisedException(tstate, exc);
2479
2480
278k
    assert(ix >= 0 || value == NULL);
2481
278k
    return value;  // borrowed reference
2482
278k
}
2483
2484
PyObject *
2485
PyDict_GetItem(PyObject *op, PyObject *key)
2486
278k
{
2487
278k
    return dict_getitem(op, key,
2488
278k
            "Exception ignored in PyDict_GetItem(); consider using "
2489
278k
            "PyDict_GetItemRef() or PyDict_GetItemWithError()");
2490
278k
}
2491
2492
static void
2493
dict_unhashable_type(PyObject *op, PyObject *key)
2494
2
{
2495
2
    PyObject *exc = PyErr_GetRaisedException();
2496
2
    assert(exc != NULL);
2497
2
    if (!Py_IS_TYPE(exc, (PyTypeObject*)PyExc_TypeError)) {
2498
0
        PyErr_SetRaisedException(exc);
2499
0
        return;
2500
0
    }
2501
2502
2
    const char *errmsg;
2503
2
    if (PyFrozenDict_Check(op)) {
2504
0
        errmsg = "cannot use '%T' as a frozendict key (%S)";
2505
0
    }
2506
2
    else {
2507
2
        errmsg = "cannot use '%T' as a dict key (%S)";
2508
2
    }
2509
2
    PyErr_Format(PyExc_TypeError, errmsg, key, exc);
2510
2
    Py_DECREF(exc);
2511
2
}
2512
2513
Py_ssize_t
2514
_PyDict_LookupIndexAndValue(PyDictObject *mp, PyObject *key, PyObject **value)
2515
81.3k
{
2516
    // TODO: Thread safety
2517
81.3k
    assert(PyDict_CheckExact((PyObject*)mp));
2518
81.3k
    assert(PyUnicode_CheckExact(key));
2519
2520
81.3k
    Py_hash_t hash = _PyObject_HashDictKey(key);
2521
81.3k
    if (hash == -1) {
2522
0
        dict_unhashable_type((PyObject*)mp, key);
2523
0
        return -1;
2524
0
    }
2525
2526
81.3k
    return _Py_dict_lookup(mp, key, hash, value);
2527
81.3k
}
2528
2529
Py_ssize_t
2530
_PyDict_LookupIndex(PyDictObject *mp, PyObject *key)
2531
19.3k
{
2532
19.3k
    PyObject *value; // discarded
2533
19.3k
    return _PyDict_LookupIndexAndValue(mp, key, &value);
2534
19.3k
}
2535
2536
/* Same as PyDict_GetItemWithError() but with hash supplied by caller.
2537
   This returns NULL *with* an exception set if an exception occurred.
2538
   It returns NULL *without* an exception set if the key wasn't present.
2539
*/
2540
PyObject *
2541
_PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
2542
0
{
2543
0
    Py_ssize_t ix; (void)ix;
2544
0
    PyDictObject *mp = (PyDictObject *)op;
2545
0
    PyObject *value;
2546
2547
0
    if (!PyAnyDict_Check(op)) {
2548
0
        PyErr_BadInternalCall();
2549
0
        return NULL;
2550
0
    }
2551
2552
#ifdef Py_GIL_DISABLED
2553
    ix = _Py_dict_lookup_threadsafe(mp, key, hash, &value);
2554
    Py_XDECREF(value);
2555
#else
2556
0
    ix = _Py_dict_lookup(mp, key, hash, &value);
2557
0
#endif
2558
0
    assert(ix >= 0 || value == NULL);
2559
0
    return value;  // borrowed reference
2560
0
}
2561
2562
/* Gets an item and provides a new reference if the value is present.
2563
 * Returns 1 if the key is present, 0 if the key is missing, and -1 if an
2564
 * exception occurred.
2565
*/
2566
int
2567
_PyDict_GetItemRef_KnownHash_LockHeld(PyDictObject *op, PyObject *key,
2568
                                      Py_hash_t hash, PyObject **result)
2569
40.3k
{
2570
40.3k
    PyObject *value;
2571
40.3k
    Py_ssize_t ix = _Py_dict_lookup(op, key, hash, &value);
2572
40.3k
    assert(ix >= 0 || value == NULL);
2573
40.3k
    if (ix == DKIX_ERROR) {
2574
0
        *result = NULL;
2575
0
        return -1;
2576
0
    }
2577
40.3k
    if (value == NULL) {
2578
2.29k
        *result = NULL;
2579
2.29k
        return 0;  // missing key
2580
2.29k
    }
2581
38.0k
    *result = Py_NewRef(value);
2582
38.0k
    return 1;  // key is present
2583
40.3k
}
2584
2585
/* Gets an item and provides a new reference if the value is present.
2586
 * Returns 1 if the key is present, 0 if the key is missing, and -1 if an
2587
 * exception occurred.
2588
*/
2589
int
2590
_PyDict_GetItemRef_KnownHash(PyDictObject *op, PyObject *key, Py_hash_t hash, PyObject **result)
2591
417M
{
2592
417M
    PyObject *value;
2593
#ifdef Py_GIL_DISABLED
2594
    Py_ssize_t ix = _Py_dict_lookup_threadsafe(op, key, hash, &value);
2595
#else
2596
417M
    Py_ssize_t ix = _Py_dict_lookup(op, key, hash, &value);
2597
417M
#endif
2598
417M
    assert(ix >= 0 || value == NULL);
2599
417M
    if (ix == DKIX_ERROR) {
2600
0
        *result = NULL;
2601
0
        return -1;
2602
0
    }
2603
417M
    if (value == NULL) {
2604
51.2M
        *result = NULL;
2605
51.2M
        return 0;  // missing key
2606
51.2M
    }
2607
#ifdef Py_GIL_DISABLED
2608
    *result = value;
2609
#else
2610
365M
    *result = Py_NewRef(value);
2611
365M
#endif
2612
365M
    return 1;  // key is present
2613
417M
}
2614
2615
int
2616
PyDict_GetItemRef(PyObject *op, PyObject *key, PyObject **result)
2617
417M
{
2618
417M
    if (!PyAnyDict_Check(op)) {
2619
0
        PyErr_BadInternalCall();
2620
0
        *result = NULL;
2621
0
        return -1;
2622
0
    }
2623
2624
417M
    Py_hash_t hash = _PyObject_HashDictKey(key);
2625
417M
    if (hash == -1) {
2626
0
        dict_unhashable_type(op, key);
2627
0
        *result = NULL;
2628
0
        return -1;
2629
0
    }
2630
2631
417M
    return _PyDict_GetItemRef_KnownHash((PyDictObject *)op, key, hash, result);
2632
417M
}
2633
2634
static inline int
2635
compare_generic_exact_unicode(PyDictObject *mp, PyDictKeysObject *dk,
2636
                              void *ep0, Py_ssize_t ix, PyObject *key,
2637
                              Py_hash_t hash)
2638
0
{
2639
0
    PyDictKeyEntry *ep = &((PyDictKeyEntry *)ep0)[ix];
2640
0
    assert(ep->me_key != NULL);
2641
0
    if (ep->me_key == key) {
2642
0
        return 1;
2643
0
    }
2644
0
    return (ep->me_hash == hash && PyUnicode_CheckExact(ep->me_key) &&
2645
0
            unicode_eq(ep->me_key, key));
2646
0
}
2647
2648
// Look up an exact str key, without comparing it to keys that are not exact
2649
// str: those are skipped, so no user code can run.  Returns a borrowed
2650
// reference, or NULL (without an exception) if the key is not found.  The
2651
// caller must hold the dict lock or have the world stopped.
2652
PyObject *
2653
_PyDict_GetItem_ExactUnicode(PyDictObject *mp, PyObject *key)
2654
0
{
2655
0
    assert(PyUnicode_CheckExact(key));
2656
0
    Py_hash_t hash = hash_unicode_key(key);
2657
0
    PyDictKeysObject *dk = mp->ma_keys;
2658
0
    Py_ssize_t ix;
2659
0
    if (dk->dk_kind == DICT_KEYS_GENERAL) {
2660
0
        ix = do_lookup(mp, dk, key, hash, compare_generic_exact_unicode);
2661
0
    }
2662
0
    else {
2663
0
        ix = unicodekeys_lookup_unicode(dk, key, hash);
2664
0
    }
2665
0
    if (ix < 0) {
2666
0
        return NULL;
2667
0
    }
2668
0
    if (dk->dk_kind == DICT_KEYS_SPLIT) {
2669
0
        return mp->ma_values->values[ix];
2670
0
    }
2671
0
    if (dk->dk_kind == DICT_KEYS_GENERAL) {
2672
0
        return DK_ENTRIES(dk)[ix].me_value;
2673
0
    }
2674
0
    return DK_UNICODE_ENTRIES(dk)[ix].me_value;
2675
0
}
2676
2677
// Like _PyDict_GetItem_ExactUnicode() but safe to call without holding the
2678
// dict lock.  Stores a new reference (or NULL) in *value_addr.  Returns 1 if
2679
// the key was found and 0 if not.
2680
int
2681
_PyDict_GetItemStackRef_ExactUnicode(PyDictObject *mp, PyObject *key,
2682
                                     _PyStackRef *value_addr)
2683
0
{
2684
0
    assert(PyUnicode_CheckExact(key));
2685
0
    PyObject *value;
2686
#ifdef Py_GIL_DISABLED
2687
    ensure_shared_on_read(mp);
2688
    PyDictKeysObject *dk = _Py_atomic_load_ptr_acquire(&mp->ma_keys);
2689
    if (dk->dk_kind == DICT_KEYS_UNICODE) {
2690
        // All keys are exact str, so the lock-free lookup cannot run user
2691
        // code.
2692
        Py_hash_t hash = hash_unicode_key(key);
2693
        Py_ssize_t ix = lookup_threadsafe_unicode(dk, key, hash, value_addr);
2694
        if (ix != DKIX_KEY_CHANGED) {
2695
            return !PyStackRef_IsNull(*value_addr);
2696
        }
2697
    }
2698
    Py_BEGIN_CRITICAL_SECTION(mp);
2699
    value = _PyDict_GetItem_ExactUnicode(mp, key);
2700
    *value_addr = value ? PyStackRef_FromPyObjectNew(value) : PyStackRef_NULL;
2701
    Py_END_CRITICAL_SECTION();
2702
#else
2703
0
    value = _PyDict_GetItem_ExactUnicode(mp, key);
2704
0
    *value_addr = value ? PyStackRef_FromPyObjectNew(value) : PyStackRef_NULL;
2705
0
#endif
2706
0
    return value != NULL;
2707
0
}
2708
2709
int
2710
_PyDict_GetItemRef_Unicode_LockHeld(PyDictObject *op, PyObject *key, PyObject **result)
2711
33.7k
{
2712
33.7k
    ASSERT_DICT_LOCKED(op);
2713
33.7k
    assert(PyUnicode_CheckExact(key));
2714
2715
33.7k
    Py_hash_t hash = _PyObject_HashDictKey(key);
2716
33.7k
    if (hash == -1) {
2717
0
        dict_unhashable_type((PyObject*)op, key);
2718
0
        *result = NULL;
2719
0
        return -1;
2720
0
    }
2721
2722
33.7k
    PyObject *value;
2723
33.7k
    Py_ssize_t ix = _Py_dict_lookup(op, key, hash, &value);
2724
33.7k
    assert(ix >= 0 || value == NULL);
2725
33.7k
    if (ix == DKIX_ERROR) {
2726
0
        *result = NULL;
2727
0
        return -1;
2728
0
    }
2729
33.7k
    if (value == NULL) {
2730
10.4k
        *result = NULL;
2731
10.4k
        return 0;  // missing key
2732
10.4k
    }
2733
23.3k
    *result = Py_NewRef(value);
2734
23.3k
    return 1;  // key is present
2735
33.7k
}
2736
2737
/* Variant of PyDict_GetItem() that doesn't suppress exceptions.
2738
   This returns NULL *with* an exception set if an exception occurred.
2739
   It returns NULL *without* an exception set if the key wasn't present.
2740
*/
2741
PyObject *
2742
PyDict_GetItemWithError(PyObject *op, PyObject *key)
2743
35.5M
{
2744
35.5M
    Py_ssize_t ix; (void)ix;
2745
35.5M
    Py_hash_t hash;
2746
35.5M
    PyDictObject*mp = (PyDictObject *)op;
2747
35.5M
    PyObject *value;
2748
2749
35.5M
    if (!PyAnyDict_Check(op)) {
2750
0
        PyErr_BadInternalCall();
2751
0
        return NULL;
2752
0
    }
2753
35.5M
    hash = _PyObject_HashDictKey(key);
2754
35.5M
    if (hash == -1) {
2755
0
        dict_unhashable_type(op, key);
2756
0
        return NULL;
2757
0
    }
2758
2759
#ifdef Py_GIL_DISABLED
2760
    ix = _Py_dict_lookup_threadsafe(mp, key, hash, &value);
2761
    Py_XDECREF(value);
2762
#else
2763
35.5M
    ix = _Py_dict_lookup(mp, key, hash, &value);
2764
35.5M
#endif
2765
35.5M
    assert(ix >= 0 || value == NULL);
2766
35.5M
    return value;  // borrowed reference
2767
35.5M
}
2768
2769
PyObject *
2770
_PyDict_GetItemWithError(PyObject *dp, PyObject *kv)
2771
0
{
2772
0
    assert(PyUnicode_CheckExact(kv));
2773
0
    Py_hash_t hash = Py_TYPE(kv)->tp_hash(kv);
2774
0
    if (hash == -1) {
2775
0
        return NULL;
2776
0
    }
2777
0
    return _PyDict_GetItem_KnownHash(dp, kv, hash);  // borrowed reference
2778
0
}
2779
2780
PyObject *
2781
_PyDict_GetItemStringWithError(PyObject *v, const char *key)
2782
0
{
2783
0
    PyObject *kv, *rv;
2784
0
    kv = PyUnicode_FromString(key);
2785
0
    if (kv == NULL) {
2786
0
        return NULL;
2787
0
    }
2788
0
    rv = PyDict_GetItemWithError(v, kv);
2789
0
    Py_DECREF(kv);
2790
0
    return rv;
2791
0
}
2792
2793
PyObject *
2794
_PyDict_LoadGlobalStackRef(PyDictObject *globals, PyDictObject *builtins, PyObject *key, _PyStackRef *res)
2795
267k
{
2796
267k
    Py_ssize_t ix;
2797
267k
    Py_hash_t hash;
2798
2799
267k
    hash = _PyObject_HashDictKey(key);
2800
267k
    if (hash == -1) {
2801
0
        *res = PyStackRef_NULL;
2802
0
        return NULL;
2803
0
    }
2804
2805
    /* namespace 1: globals */
2806
267k
    ix = _Py_dict_lookup_threadsafe_stackref(globals, key, hash, res);
2807
267k
    if (ix == DKIX_ERROR) {
2808
0
        return NULL;
2809
0
    }
2810
267k
    if (ix != DKIX_EMPTY && !PyStackRef_IsNull(*res)) {
2811
118k
        return (PyObject *)globals;
2812
118k
    }
2813
2814
    /* namespace 2: builtins */
2815
149k
    ix = _Py_dict_lookup_threadsafe_stackref(builtins, key, hash, res);
2816
149k
    assert(ix >= 0 || PyStackRef_IsNull(*res));
2817
149k
    return PyStackRef_IsNull(*res) ? NULL : (PyObject *)builtins;
2818
267k
}
2819
2820
PyObject *
2821
_PyDict_LoadBuiltinsFromGlobals(PyObject *globals)
2822
15.4M
{
2823
15.4M
    if (!PyAnyDict_Check(globals)) {
2824
0
        PyErr_BadInternalCall();
2825
0
        return NULL;
2826
0
    }
2827
2828
15.4M
    PyDictObject *mp = (PyDictObject *)globals;
2829
15.4M
    PyObject *key = &_Py_ID(__builtins__);
2830
15.4M
    Py_hash_t hash = unicode_get_hash(key);
2831
2832
    // Use the stackref variant to avoid reference count contention on the
2833
    // builtins module in the free threading build. It's important not to
2834
    // make any escaping calls between the lookup and the `PyStackRef_CLOSE()`
2835
    // because the `ref` is not visible to the GC.
2836
15.4M
    _PyStackRef ref;
2837
15.4M
    Py_ssize_t ix = _Py_dict_lookup_threadsafe_stackref(mp, key, hash, &ref);
2838
15.4M
    if (ix == DKIX_ERROR) {
2839
0
        return NULL;
2840
0
    }
2841
15.4M
    if (PyStackRef_IsNull(ref)) {
2842
1.13k
        return Py_NewRef(PyEval_GetBuiltins());
2843
1.13k
    }
2844
15.4M
    PyObject *builtins = PyStackRef_AsPyObjectBorrow(ref);
2845
15.4M
    if (PyModule_Check(builtins)) {
2846
74
        builtins = _PyModule_GetDict(builtins);
2847
74
        assert(builtins != NULL);
2848
74
    }
2849
15.4M
    _Py_INCREF_BUILTINS(builtins);
2850
15.4M
    PyStackRef_CLOSE(ref);
2851
15.4M
    return builtins;
2852
15.4M
}
2853
2854
#define frozendict_does_not_support(WHAT) \
2855
0
    PyErr_SetString(PyExc_TypeError, "frozendict object does " \
2856
0
                    "not support item " WHAT)
2857
2858
/* Consumes references to key and value */
2859
static int
2860
setitem_take2_lock_held_known_hash(PyDictObject *mp, PyObject *key, PyObject *value, Py_hash_t hash)
2861
235M
{
2862
235M
    assert(PyAnyDict_Check(mp));
2863
235M
    assert(can_modify_dict(mp));
2864
235M
    assert(key);
2865
235M
    assert(value);
2866
2867
235M
    if (mp->ma_keys == Py_EMPTY_KEYS) {
2868
50.3M
        return insert_to_emptydict(mp, key, hash, value);
2869
50.3M
    }
2870
    /* insertdict() handles any resizing that might be necessary */
2871
185M
    return insertdict(mp, key, hash, value);
2872
235M
}
2873
2874
static int
2875
setitem_take2_lock_held(PyDictObject *mp, PyObject *key, PyObject *value)
2876
235M
{
2877
235M
    Py_hash_t hash = _PyObject_HashDictKey(key);
2878
235M
    if (hash == -1) {
2879
2
        dict_unhashable_type((PyObject*)mp, key);
2880
2
        Py_DECREF(key);
2881
2
        Py_DECREF(value);
2882
2
        return -1;
2883
2
    }
2884
2885
235M
    return setitem_take2_lock_held_known_hash(mp, key, value, hash);
2886
235M
}
2887
2888
int
2889
_PyDict_SetItem_Take2(PyDictObject *mp, PyObject *key, PyObject *value)
2890
113M
{
2891
113M
    int res;
2892
113M
    Py_BEGIN_CRITICAL_SECTION(mp);
2893
113M
    res = setitem_take2_lock_held(mp, key, value);
2894
113M
    Py_END_CRITICAL_SECTION();
2895
113M
    return res;
2896
113M
}
2897
2898
int
2899
_PyDict_SetItem_Take2_KnownHash(PyDictObject *mp, PyObject *key, PyObject *value, Py_hash_t hash)
2900
0
{
2901
0
    int res;
2902
0
    Py_BEGIN_CRITICAL_SECTION(mp);
2903
0
    res = setitem_take2_lock_held_known_hash(mp, key, value, hash);
2904
0
    Py_END_CRITICAL_SECTION();
2905
0
    return res;
2906
0
}
2907
2908
/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
2909
 * dictionary if it's merely replacing the value for an existing key.
2910
 * This means that it's safe to loop over a dictionary with PyDict_Next()
2911
 * and occasionally replace a value -- but you can't insert new keys or
2912
 * remove them.
2913
 */
2914
int
2915
PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
2916
9.63M
{
2917
9.63M
    assert(key);
2918
9.63M
    assert(value);
2919
2920
9.63M
    if (!PyDict_Check(op)) {
2921
0
        if (PyFrozenDict_Check(op)) {
2922
0
            frozendict_does_not_support("assignment");
2923
0
        }
2924
0
        else {
2925
0
            PyErr_BadInternalCall();
2926
0
        }
2927
0
        return -1;
2928
0
    }
2929
2930
9.63M
    return _PyDict_SetItem_Take2((PyDictObject *)op,
2931
9.63M
                                 Py_NewRef(key), Py_NewRef(value));
2932
9.63M
}
2933
2934
static int
2935
_PyAnyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
2936
1.90k
{
2937
1.90k
    assert(PyAnyDict_Check(op));
2938
1.90k
    assert(key);
2939
1.90k
    assert(value);
2940
1.90k
    return _PyDict_SetItem_Take2((PyDictObject *)op,
2941
1.90k
                                 Py_NewRef(key), Py_NewRef(value));
2942
1.90k
}
2943
2944
static int
2945
setitem_lock_held(PyDictObject *mp, PyObject *key, PyObject *value)
2946
121M
{
2947
121M
    assert(key);
2948
121M
    assert(value);
2949
121M
    return setitem_take2_lock_held(mp,
2950
121M
                                   Py_NewRef(key), Py_NewRef(value));
2951
121M
}
2952
2953
2954
int
2955
_PyDict_SetItem_KnownHash_LockHeld(PyDictObject *mp, PyObject *key, PyObject *value,
2956
                                   Py_hash_t hash)
2957
4.16k
{
2958
4.16k
    if (mp->ma_keys == Py_EMPTY_KEYS) {
2959
955
        return insert_to_emptydict(mp, Py_NewRef(key), hash, Py_NewRef(value));
2960
955
    }
2961
    /* insertdict() handles any resizing that might be necessary */
2962
3.20k
    return insertdict(mp, Py_NewRef(key), hash, Py_NewRef(value));
2963
4.16k
}
2964
2965
int
2966
_PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
2967
                          Py_hash_t hash)
2968
909
{
2969
909
    assert(key);
2970
909
    assert(value);
2971
909
    assert(hash != -1);
2972
2973
909
    if (!PyDict_Check(op)) {
2974
0
        if (PyFrozenDict_Check(op)) {
2975
0
            frozendict_does_not_support("assignment");
2976
0
        }
2977
0
        else {
2978
0
            PyErr_BadInternalCall();
2979
0
        }
2980
0
        return -1;
2981
0
    }
2982
2983
909
    int res;
2984
909
    Py_BEGIN_CRITICAL_SECTION(op);
2985
909
    res = _PyDict_SetItem_KnownHash_LockHeld((PyDictObject *)op, key, value, hash);
2986
909
    Py_END_CRITICAL_SECTION();
2987
909
    return res;
2988
909
}
2989
2990
static void
2991
delete_index_from_values(PyDictValues *values, Py_ssize_t ix)
2992
432k
{
2993
432k
    uint8_t *array = get_insertion_order_array(values);
2994
432k
    int size = values->size;
2995
432k
    assert(size <= values->capacity);
2996
432k
    int i;
2997
1.15M
    for (i = 0; array[i] != ix; i++) {
2998
720k
        assert(i < size);
2999
720k
    }
3000
432k
    assert(i < size);
3001
432k
    size--;
3002
1.00M
    for (; i < size; i++) {
3003
576k
        FT_ATOMIC_STORE_UINT8_RELAXED(array[i], array[i+1]);
3004
576k
    }
3005
432k
    FT_ATOMIC_STORE_UINT8_RELEASE(values->size, size);
3006
432k
}
3007
3008
static void
3009
delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
3010
               PyObject *old_value)
3011
2.70M
{
3012
2.70M
    assert(can_modify_dict(mp));
3013
3014
2.70M
    PyObject *old_key;
3015
3016
2.70M
    STORE_USED(mp, mp->ma_used - 1);
3017
2.70M
    if (_PyDict_HasSplitTable(mp)) {
3018
0
        assert(old_value == mp->ma_values->values[ix]);
3019
0
        STORE_SPLIT_VALUE(mp, ix, NULL);
3020
0
        assert(ix < SHARED_KEYS_MAX_SIZE);
3021
        /* Update order */
3022
0
        delete_index_from_values(mp->ma_values, ix);
3023
0
        ASSERT_CONSISTENT(mp);
3024
0
    }
3025
2.70M
    else {
3026
2.70M
        Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
3027
2.70M
        assert(hashpos >= 0);
3028
3029
2.70M
        FT_ATOMIC_STORE_UINT32_RELAXED(mp->ma_keys->dk_version, 0);
3030
2.70M
        dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
3031
2.70M
        if (DK_IS_UNICODE(mp->ma_keys)) {
3032
1.03M
            PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(mp->ma_keys)[ix];
3033
1.03M
            old_key = ep->me_key;
3034
1.03M
            STORE_KEY(ep, NULL);
3035
1.03M
            STORE_VALUE(ep, NULL);
3036
1.03M
        }
3037
1.66M
        else {
3038
1.66M
            PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[ix];
3039
1.66M
            old_key = ep->me_key;
3040
1.66M
            STORE_KEY(ep, NULL);
3041
1.66M
            STORE_VALUE(ep, NULL);
3042
1.66M
            STORE_HASH(ep, 0);
3043
1.66M
        }
3044
2.70M
        Py_DECREF(old_key);
3045
2.70M
    }
3046
2.70M
    Py_DECREF(old_value);
3047
3048
2.70M
    ASSERT_CONSISTENT(mp);
3049
2.70M
}
3050
3051
int
3052
PyDict_DelItem(PyObject *op, PyObject *key)
3053
1.97M
{
3054
1.97M
    assert(key);
3055
1.97M
    Py_hash_t hash = _PyObject_HashDictKey(key);
3056
1.97M
    if (hash == -1) {
3057
0
        dict_unhashable_type(op, key);
3058
0
        return -1;
3059
0
    }
3060
3061
1.97M
    return _PyDict_DelItem_KnownHash(op, key, hash);
3062
1.97M
}
3063
3064
int
3065
_PyDict_DelItem_KnownHash_LockHeld(PyObject *op, PyObject *key, Py_hash_t hash)
3066
1.99M
{
3067
1.99M
    if (!PyDict_Check(op)) {
3068
0
        if (PyFrozenDict_Check(op)) {
3069
0
            frozendict_does_not_support("deletion");
3070
0
        }
3071
0
        else {
3072
0
            PyErr_BadInternalCall();
3073
0
        }
3074
0
        return -1;
3075
0
    }
3076
3077
1.99M
    Py_ssize_t ix;
3078
1.99M
    PyObject *old_value;
3079
1.99M
    PyDictObject *mp = (PyDictObject *)op;
3080
1.99M
    assert(can_modify_dict(mp));
3081
3082
1.99M
    assert(key);
3083
1.99M
    assert(hash != -1);
3084
1.99M
    ix = _Py_dict_lookup(mp, key, hash, &old_value);
3085
1.99M
    if (ix == DKIX_ERROR)
3086
0
        return -1;
3087
1.99M
    if (ix == DKIX_EMPTY || old_value == NULL) {
3088
0
        _PyErr_SetKeyError(key);
3089
0
        return -1;
3090
0
    }
3091
3092
1.99M
    _PyDict_NotifyEvent(PyDict_EVENT_DELETED, mp, key, NULL);
3093
1.99M
    delitem_common(mp, hash, ix, old_value);
3094
1.99M
    return 0;
3095
1.99M
}
3096
3097
int
3098
_PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
3099
1.97M
{
3100
1.97M
    int res;
3101
1.97M
    Py_BEGIN_CRITICAL_SECTION(op);
3102
1.97M
    res = _PyDict_DelItem_KnownHash_LockHeld(op, key, hash);
3103
1.97M
    Py_END_CRITICAL_SECTION();
3104
1.97M
    return res;
3105
1.97M
}
3106
3107
static int
3108
delitemif_lock_held(PyObject *op, PyObject *key,
3109
                    int (*predicate)(PyObject *value, void *arg),
3110
                    void *arg)
3111
7.07k
{
3112
7.07k
    PyDictObject *mp = _PyAnyDict_CAST(op);
3113
7.07k
    assert(can_modify_dict(mp));
3114
3115
7.07k
    Py_ssize_t ix;
3116
7.07k
    Py_hash_t hash;
3117
7.07k
    PyObject *old_value;
3118
7.07k
    int res;
3119
3120
7.07k
    assert(key);
3121
7.07k
    hash = PyObject_Hash(key);
3122
7.07k
    if (hash == -1)
3123
0
        return -1;
3124
7.07k
    ix = _Py_dict_lookup(mp, key, hash, &old_value);
3125
7.07k
    if (ix == DKIX_ERROR) {
3126
0
        return -1;
3127
0
    }
3128
7.07k
    if (ix == DKIX_EMPTY || old_value == NULL) {
3129
0
        return 0;
3130
0
    }
3131
3132
7.07k
    res = predicate(old_value, arg);
3133
7.07k
    if (res == -1)
3134
0
        return -1;
3135
3136
7.07k
    if (res > 0) {
3137
7.07k
        _PyDict_NotifyEvent(PyDict_EVENT_DELETED, mp, key, NULL);
3138
7.07k
        delitem_common(mp, hash, ix, old_value);
3139
7.07k
        return 1;
3140
7.07k
    } else {
3141
0
        return 0;
3142
0
    }
3143
7.07k
}
3144
/* This function promises that the predicate -> deletion sequence is atomic
3145
 * (i.e. protected by the GIL or the per-dict mutex in free threaded builds),
3146
 * assuming the predicate itself doesn't release the GIL (or cause re-entrancy
3147
 * which would release the per-dict mutex)
3148
 */
3149
int
3150
_PyDict_DelItemIf(PyObject *op, PyObject *key,
3151
                  int (*predicate)(PyObject *value, void *arg),
3152
                  void *arg)
3153
7.07k
{
3154
7.07k
    assert(PyDict_Check(op));
3155
7.07k
    int res;
3156
7.07k
    Py_BEGIN_CRITICAL_SECTION(op);
3157
7.07k
    res = delitemif_lock_held(op, key, predicate, arg);
3158
7.07k
    Py_END_CRITICAL_SECTION();
3159
7.07k
    return res;
3160
7.07k
}
3161
3162
int
3163
_PyDict_ReplaceItemIf(PyObject *op, PyObject *key,
3164
                      PyObject *expected, PyObject *replacement)
3165
19
{
3166
19
    assert(PyDict_Check(op));
3167
19
    assert(expected != NULL);
3168
19
    assert(replacement != NULL);
3169
3170
19
    Py_hash_t hash = PyObject_Hash(key);
3171
19
    if (hash == -1) {
3172
0
        return -1;
3173
0
    }
3174
19
    int result = 0;
3175
19
    Py_BEGIN_CRITICAL_SECTION(op);
3176
19
    PyDictObject *mp = (PyDictObject *)op;
3177
19
    PyObject *current;
3178
19
    Py_ssize_t ix = _Py_dict_lookup(mp, key, hash, &current);
3179
19
    if (ix == DKIX_ERROR) {
3180
0
        result = -1;
3181
0
    }
3182
19
    else if (current == expected) {
3183
        // Do not look up the key again: equality can execute Python code.
3184
19
        replace_value(mp, key, ix, current, Py_NewRef(replacement));
3185
19
        result = 1;
3186
19
    }
3187
19
    Py_END_CRITICAL_SECTION();
3188
19
    return result;
3189
19
}
3190
3191
static void
3192
clear_embedded_values(PyDictValues *values, Py_ssize_t nentries)
3193
0
{
3194
0
    PyObject *refs[SHARED_KEYS_MAX_SIZE];
3195
0
    assert(nentries <= SHARED_KEYS_MAX_SIZE);
3196
0
    for (Py_ssize_t i = 0; i < nentries; i++) {
3197
0
        refs[i] = values->values[i];
3198
0
        FT_ATOMIC_STORE_PTR_RELEASE(values->values[i], NULL);
3199
0
    }
3200
0
    FT_ATOMIC_STORE_UINT8_RELEASE(values->size, 0);
3201
0
    for (Py_ssize_t i = 0; i < nentries; i++) {
3202
0
        Py_XDECREF(refs[i]);
3203
0
    }
3204
0
}
3205
3206
// This function is used in both `PyDict_Clear`
3207
// and `PyDict_AsFrozenDictAndClear`, place all the common parts here.
3208
static void
3209
clear_common(PyDictObject *mp)
3210
277k
{
3211
277k
    _PyDict_NotifyEvent(PyDict_EVENT_CLEARED, mp, NULL, NULL);
3212
    // We don't inc ref empty keys because they're immortal
3213
277k
    ensure_shared_on_resize(mp);
3214
277k
    STORE_USED(mp, 0);
3215
277k
}
3216
3217
static void
3218
clear_lock_held(PyObject *op)
3219
557k
{
3220
557k
    if (!PyDict_Check(op)) {
3221
0
        return;
3222
0
    }
3223
557k
    PyDictObject *mp = (PyDictObject *)op;
3224
557k
    assert(can_modify_dict(mp));
3225
3226
557k
    PyDictKeysObject *oldkeys;
3227
557k
    PyDictValues *oldvalues;
3228
557k
    Py_ssize_t i, n;
3229
3230
557k
    oldkeys = mp->ma_keys;
3231
557k
    oldvalues = mp->ma_values;
3232
557k
    if (oldkeys == Py_EMPTY_KEYS) {
3233
279k
        return;
3234
279k
    }
3235
    /* Empty the dict... */
3236
277k
    clear_common(mp);
3237
277k
    if (oldvalues == NULL) {
3238
277k
        set_keys(mp, Py_EMPTY_KEYS);
3239
277k
        assert(oldkeys->dk_refcnt == 1);
3240
277k
        dictkeys_decref(oldkeys, IS_DICT_SHARED(mp));
3241
277k
    }
3242
0
    else if (oldvalues->embedded) {
3243
0
        clear_embedded_values(oldvalues, oldkeys->dk_nentries);
3244
0
    }
3245
0
    else {
3246
0
        set_values(mp, NULL);
3247
0
        set_keys(mp, Py_EMPTY_KEYS);
3248
0
        n = oldkeys->dk_nentries;
3249
0
        for (i = 0; i < n; i++) {
3250
0
            PyObject *tmp = oldvalues->values[i];
3251
0
            FT_ATOMIC_STORE_PTR_RELEASE(oldvalues->values[i], NULL);
3252
0
            Py_XDECREF(tmp);
3253
0
        }
3254
0
        free_values(oldvalues, IS_DICT_SHARED(mp));
3255
0
        dictkeys_decref(oldkeys, IS_DICT_SHARED(mp));
3256
0
    }
3257
277k
    ASSERT_CONSISTENT(mp);
3258
277k
}
3259
3260
void
3261
6.09k
_PyDict_Clear_LockHeld(PyObject *op) {
3262
6.09k
    clear_lock_held(op);
3263
6.09k
}
3264
3265
void
3266
PyDict_Clear(PyObject *op)
3267
551k
{
3268
551k
    Py_BEGIN_CRITICAL_SECTION(op);
3269
551k
    clear_lock_held(op);
3270
551k
    Py_END_CRITICAL_SECTION();
3271
551k
}
3272
3273
/* Internal version of PyDict_Next that returns a hash value in addition
3274
 * to the key and value.
3275
 * Return 1 on success, return 0 when the reached the end of the dictionary
3276
 * (or if op is not a dictionary)
3277
 */
3278
int
3279
_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
3280
             PyObject **pvalue, Py_hash_t *phash)
3281
71.3M
{
3282
71.3M
    Py_ssize_t i;
3283
71.3M
    PyDictObject *mp;
3284
71.3M
    PyObject *key, *value;
3285
71.3M
    Py_hash_t hash;
3286
3287
71.3M
    if (!PyAnyDict_Check(op))
3288
0
        return 0;
3289
3290
71.3M
    mp = (PyDictObject *)op;
3291
71.3M
    i = *ppos;
3292
71.3M
    if (_PyDict_HasSplitTable(mp)) {
3293
0
        assert(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
3294
0
        if (i < 0 || i >= mp->ma_used)
3295
0
            return 0;
3296
0
        int index = get_index_from_order(mp, i);
3297
0
        value = mp->ma_values->values[index];
3298
0
        key = LOAD_SHARED_KEY(DK_UNICODE_ENTRIES(mp->ma_keys)[index].me_key);
3299
0
        hash = unicode_get_hash(key);
3300
0
        assert(value != NULL);
3301
0
    }
3302
71.3M
    else {
3303
71.3M
        Py_ssize_t n = mp->ma_keys->dk_nentries;
3304
71.3M
        if (i < 0 || i >= n)
3305
15.8M
            return 0;
3306
55.4M
        if (DK_IS_UNICODE(mp->ma_keys)) {
3307
52.2M
            PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(mp->ma_keys)[i];
3308
54.1M
            while (i < n && entry_ptr->me_value == NULL) {
3309
1.93M
                entry_ptr++;
3310
1.93M
                i++;
3311
1.93M
            }
3312
52.2M
            if (i >= n)
3313
3.22k
                return 0;
3314
52.2M
            key = entry_ptr->me_key;
3315
52.2M
            hash = unicode_get_hash(entry_ptr->me_key);
3316
52.2M
            value = entry_ptr->me_value;
3317
52.2M
        }
3318
3.25M
        else {
3319
3.25M
            PyDictKeyEntry *entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
3320
3.25M
            while (i < n && entry_ptr->me_value == NULL) {
3321
0
                entry_ptr++;
3322
0
                i++;
3323
0
            }
3324
3.25M
            if (i >= n)
3325
0
                return 0;
3326
3.25M
            key = entry_ptr->me_key;
3327
3.25M
            hash = entry_ptr->me_hash;
3328
3.25M
            value = entry_ptr->me_value;
3329
3.25M
        }
3330
55.4M
    }
3331
55.4M
    *ppos = i+1;
3332
55.4M
    if (pkey)
3333
55.4M
        *pkey = key;
3334
55.4M
    if (pvalue)
3335
54.7M
        *pvalue = value;
3336
55.4M
    if (phash)
3337
35.1M
        *phash = hash;
3338
55.4M
    return 1;
3339
71.3M
}
3340
3341
/*
3342
 * Iterate over a dict.  Use like so:
3343
 *
3344
 *     Py_ssize_t i;
3345
 *     PyObject *key, *value;
3346
 *     i = 0;   # important!  i should not otherwise be changed by you
3347
 *     while (PyDict_Next(yourdict, &i, &key, &value)) {
3348
 *         Refer to borrowed references in key and value.
3349
 *     }
3350
 *
3351
 * Return 1 on success, return 0 when the reached the end of the dictionary
3352
 * (or if op is not a dictionary)
3353
 *
3354
 * CAUTION:  In general, it isn't safe to use PyDict_Next in a loop that
3355
 * mutates the dict.  One exception:  it is safe if the loop merely changes
3356
 * the values associated with the keys (but doesn't insert new keys or
3357
 * delete keys), via PyDict_SetItem().
3358
 */
3359
int
3360
PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
3361
29.3M
{
3362
29.3M
    return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
3363
29.3M
}
3364
3365
3366
/* Internal version of dict.pop(). */
3367
int
3368
_PyDict_Pop_KnownHash(PyDictObject *mp, PyObject *key, Py_hash_t hash,
3369
                      PyObject **result)
3370
718k
{
3371
718k
    assert(PyDict_Check(mp));
3372
718k
    assert(can_modify_dict(mp));
3373
3374
718k
    if (mp->ma_used == 0) {
3375
0
        if (result) {
3376
0
            *result = NULL;
3377
0
        }
3378
0
        return 0;
3379
0
    }
3380
3381
718k
    PyObject *old_value;
3382
718k
    Py_ssize_t ix = _Py_dict_lookup(mp, key, hash, &old_value);
3383
718k
    if (ix == DKIX_ERROR) {
3384
0
        if (result) {
3385
0
            *result = NULL;
3386
0
        }
3387
0
        return -1;
3388
0
    }
3389
3390
718k
    if (ix == DKIX_EMPTY || old_value == NULL) {
3391
12.5k
        if (result) {
3392
8.71k
            *result = NULL;
3393
8.71k
        }
3394
12.5k
        return 0;
3395
12.5k
    }
3396
3397
718k
    assert(old_value != NULL);
3398
706k
    _PyDict_NotifyEvent(PyDict_EVENT_DELETED, mp, key, NULL);
3399
706k
    delitem_common(mp, hash, ix, Py_NewRef(old_value));
3400
3401
706k
    ASSERT_CONSISTENT(mp);
3402
706k
    if (result) {
3403
706k
        *result = old_value;
3404
706k
    }
3405
3
    else {
3406
3
        Py_DECREF(old_value);
3407
3
    }
3408
706k
    return 1;
3409
718k
}
3410
3411
static int
3412
pop_lock_held(PyObject *op, PyObject *key, PyObject **result)
3413
928k
{
3414
928k
    if (!PyDict_Check(op)) {
3415
0
        if (result) {
3416
0
            *result = NULL;
3417
0
        }
3418
0
        if (PyFrozenDict_Check(op)) {
3419
0
            frozendict_does_not_support("deletion");
3420
0
        }
3421
0
        else {
3422
0
            PyErr_BadInternalCall();
3423
0
        }
3424
0
        return -1;
3425
0
    }
3426
928k
    PyDictObject *dict = (PyDictObject *)op;
3427
928k
    assert(can_modify_dict(dict));
3428
3429
928k
    if (dict->ma_used == 0) {
3430
210k
        if (result) {
3431
210k
            *result = NULL;
3432
210k
        }
3433
210k
        return 0;
3434
210k
    }
3435
3436
718k
    Py_hash_t hash = _PyObject_HashDictKey(key);
3437
718k
    if (hash == -1) {
3438
0
        dict_unhashable_type(op, key);
3439
0
        if (result) {
3440
0
            *result = NULL;
3441
0
        }
3442
0
        return -1;
3443
0
    }
3444
718k
    return _PyDict_Pop_KnownHash(dict, key, hash, result);
3445
718k
}
3446
3447
int
3448
PyDict_Pop(PyObject *op, PyObject *key, PyObject **result)
3449
928k
{
3450
928k
    int err;
3451
928k
    Py_BEGIN_CRITICAL_SECTION(op);
3452
928k
    err = pop_lock_held(op, key, result);
3453
928k
    Py_END_CRITICAL_SECTION();
3454
3455
928k
    return err;
3456
928k
}
3457
3458
3459
int
3460
PyDict_PopString(PyObject *op, const char *key, PyObject **result)
3461
0
{
3462
0
    PyObject *key_obj = PyUnicode_FromString(key);
3463
0
    if (key_obj == NULL) {
3464
0
        if (result != NULL) {
3465
0
            *result = NULL;
3466
0
        }
3467
0
        return -1;
3468
0
    }
3469
3470
0
    int res = PyDict_Pop(op, key_obj, result);
3471
0
    Py_DECREF(key_obj);
3472
0
    return res;
3473
0
}
3474
3475
3476
static PyObject *
3477
dict_pop_default(PyObject *dict, PyObject *key, PyObject *default_value)
3478
766k
{
3479
766k
    PyObject *result;
3480
766k
    if (PyDict_Pop(dict, key, &result) == 0) {
3481
216k
        if (default_value != NULL) {
3482
216k
            return Py_NewRef(default_value);
3483
216k
        }
3484
0
        _PyErr_SetKeyError(key);
3485
0
        return NULL;
3486
216k
    }
3487
550k
    return result;
3488
766k
}
3489
3490
PyObject *
3491
_PyDict_Pop(PyObject *dict, PyObject *key, PyObject *default_value)
3492
0
{
3493
0
    return dict_pop_default(dict, key, default_value);
3494
0
}
3495
3496
static PyDictObject *
3497
dict_dict_fromkeys(PyDictObject *mp, PyObject *iterable, PyObject *value)
3498
0
{
3499
0
    assert(can_modify_dict(mp));
3500
3501
0
    PyObject *oldvalue;
3502
0
    Py_ssize_t pos = 0;
3503
0
    PyObject *key;
3504
0
    Py_hash_t hash;
3505
0
    int unicode = DK_IS_UNICODE(((PyDictObject*)iterable)->ma_keys);
3506
0
    uint8_t log2_keysize = estimate_log2_keysize(PyDict_GET_SIZE(iterable));
3507
0
    uint8_t new_size = Py_MAX(log2_keysize, DK_LOG_SIZE(mp->ma_keys));
3508
0
    if (dictresize(mp, new_size, unicode)) {
3509
0
        Py_DECREF(mp);
3510
0
        return NULL;
3511
0
    }
3512
3513
0
    while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
3514
0
        if (insertdict(mp, Py_NewRef(key), hash, Py_NewRef(value))) {
3515
0
            Py_DECREF(mp);
3516
0
            return NULL;
3517
0
        }
3518
0
    }
3519
0
    return mp;
3520
0
}
3521
3522
static PyDictObject *
3523
dict_set_fromkeys(PyDictObject *mp, PyObject *iterable, PyObject *value)
3524
0
{
3525
0
    assert(can_modify_dict(mp));
3526
3527
0
    Py_ssize_t pos = 0;
3528
0
    PyObject *key;
3529
0
    Py_hash_t hash;
3530
0
    uint8_t log2_keysize = estimate_log2_keysize(PySet_GET_SIZE(iterable));
3531
0
    uint8_t new_size = Py_MAX(log2_keysize, DK_LOG_SIZE(mp->ma_keys));
3532
0
    if (dictresize(mp, new_size, 0)) {
3533
0
        Py_DECREF(mp);
3534
0
        return NULL;
3535
0
    }
3536
3537
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(iterable);
3538
0
    while (_PySet_NextEntryRef(iterable, &pos, &key, &hash)) {
3539
0
        if (insertdict(mp, key, hash, Py_NewRef(value))) {
3540
0
            Py_DECREF(mp);
3541
0
            return NULL;
3542
0
        }
3543
0
    }
3544
0
    return mp;
3545
0
}
3546
3547
/* Internal version of dict.from_keys().  It is subclass-friendly. */
3548
PyObject *
3549
_PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
3550
1.11M
{
3551
1.11M
    PyObject *it = NULL;       /* iter(iterable) */
3552
1.11M
    PyObject *d;
3553
1.11M
    int need_copy = 0;
3554
3555
1.11M
    if (cls == (PyObject*)&PyFrozenDict_Type) {
3556
        // gh-151722: Create a frozendict which is not tracked by the GC.
3557
0
        d = frozendict_new_untracked(&PyFrozenDict_Type);
3558
0
    }
3559
1.11M
    else {
3560
        // Dict subclass, or frozendict subclass which overrides
3561
        // the constructor.
3562
1.11M
        d = _PyObject_CallNoArgs(cls);
3563
1.11M
    }
3564
1.11M
    if (d == NULL) {
3565
0
        return NULL;
3566
0
    }
3567
3568
    // gh-151722: If cls constructor returns a frozendict which is tracked by
3569
    // the GC, create a frozendict copy which is not tracked by the GC.
3570
    //
3571
    // At the function exit, return cls(fd) where fd is a frozendict.
3572
    //
3573
    // Untracking the frozendict requires tracking again the frozendict on
3574
    // error which is more complicated. It's easier to work on a copy.
3575
1.11M
    if (PyFrozenDict_Check(d) && _PyObject_GC_IS_TRACKED(d)) {
3576
0
        need_copy = 1;
3577
3578
0
        PyObject *copy = frozendict_new_untracked(&PyFrozenDict_Type);
3579
0
        if (copy == NULL) {
3580
0
            goto Fail;
3581
0
        }
3582
0
        if (dict_merge(copy, d, 1, NULL) < 0) {
3583
0
            Py_DECREF(copy);
3584
0
            goto Fail;
3585
0
        }
3586
0
        Py_SETREF(d, copy);
3587
0
    }
3588
1.11M
    if (PyFrozenDict_Check(d)) {
3589
0
        assert(can_modify_dict((PyDictObject*)d));
3590
0
    }
3591
3592
1.11M
    if (PyDict_CheckExact(d)) {
3593
1.11M
        if (PyDict_CheckExact(iterable)) {
3594
0
            PyDictObject *mp = (PyDictObject *)d;
3595
3596
0
            Py_BEGIN_CRITICAL_SECTION2(d, iterable);
3597
0
            d = (PyObject *)dict_dict_fromkeys(mp, iterable, value);
3598
0
            Py_END_CRITICAL_SECTION2();
3599
0
            goto Done;
3600
0
        }
3601
1.11M
        else if (PyFrozenDict_CheckExact(iterable)) {
3602
0
            PyDictObject *mp = (PyDictObject *)d;
3603
3604
0
            Py_BEGIN_CRITICAL_SECTION(d);
3605
0
            d = (PyObject *)dict_dict_fromkeys(mp, iterable, value);
3606
0
            Py_END_CRITICAL_SECTION();
3607
0
            goto Done;
3608
0
        }
3609
1.11M
        else if (PyAnySet_CheckExact(iterable)) {
3610
0
            PyDictObject *mp = (PyDictObject *)d;
3611
3612
0
            Py_BEGIN_CRITICAL_SECTION2(d, iterable);
3613
0
            d = (PyObject *)dict_set_fromkeys(mp, iterable, value);
3614
0
            Py_END_CRITICAL_SECTION2();
3615
0
            goto Done;
3616
0
        }
3617
1.11M
    }
3618
0
    else if (PyFrozenDict_CheckExact(d)) {
3619
0
        if (PyDict_CheckExact(iterable)) {
3620
0
            PyDictObject *mp = (PyDictObject *)d;
3621
3622
0
            Py_BEGIN_CRITICAL_SECTION(iterable);
3623
0
            d = (PyObject *)dict_dict_fromkeys(mp, iterable, value);
3624
0
            Py_END_CRITICAL_SECTION();
3625
0
            goto Done;
3626
0
        }
3627
0
        else if (PyFrozenDict_CheckExact(iterable)) {
3628
0
            PyDictObject *mp = (PyDictObject *)d;
3629
0
            d = (PyObject *)dict_dict_fromkeys(mp, iterable, value);
3630
0
            goto Done;
3631
0
        }
3632
0
        else if (PyAnySet_CheckExact(iterable)) {
3633
0
            PyDictObject *mp = (PyDictObject *)d;
3634
3635
0
            Py_BEGIN_CRITICAL_SECTION(iterable);
3636
0
            d = (PyObject *)dict_set_fromkeys(mp, iterable, value);
3637
0
            Py_END_CRITICAL_SECTION();
3638
0
            goto Done;
3639
0
        }
3640
0
    }
3641
3642
1.11M
    it = PyObject_GetIter(iterable);
3643
1.11M
    if (it == NULL){
3644
0
        goto Fail;
3645
0
    }
3646
3647
1.11M
    if (PyDict_CheckExact(d)) {
3648
1.11M
        int status = 0;
3649
3650
1.11M
        Py_BEGIN_CRITICAL_SECTION(d);
3651
9.91M
        while (1) {
3652
9.91M
            PyObject *key;
3653
9.91M
            status = PyIter_NextItem(it, &key);
3654
9.91M
            if (status <= 0) {
3655
1.11M
                break;
3656
1.11M
            }
3657
3658
8.79M
            status = setitem_lock_held((PyDictObject *)d, key, value);
3659
8.79M
            Py_DECREF(key);
3660
8.79M
            if (status < 0) {
3661
0
                break;
3662
0
            }
3663
8.79M
        }
3664
1.11M
        Py_END_CRITICAL_SECTION();
3665
3666
1.11M
        if (status < 0) {
3667
0
            goto Fail;
3668
0
        }
3669
1.11M
    }
3670
0
    else if (PyFrozenDict_Check(d)) {
3671
0
        while (1) {
3672
0
            PyObject *key;
3673
0
            int status = PyIter_NextItem(it, &key);
3674
0
            if (status < 0) {
3675
0
                goto Fail;
3676
0
            }
3677
0
            if (status == 0) {
3678
0
                break;
3679
0
            }
3680
3681
            // setitem_take2_lock_held consumes a reference to key
3682
0
            status = setitem_take2_lock_held((PyDictObject *)d,
3683
0
                                             key, Py_NewRef(value));
3684
0
            if (status < 0) {
3685
0
                goto Fail;
3686
0
            }
3687
0
        }
3688
0
    }
3689
0
    else {
3690
0
        while (1) {
3691
0
            PyObject *key;
3692
0
            int status = PyIter_NextItem(it, &key);
3693
0
            if (status < 0) {
3694
0
                goto Fail;
3695
0
            }
3696
0
            if (status == 0) {
3697
0
                break;
3698
0
            }
3699
3700
0
            status = PyObject_SetItem(d, key, value);
3701
0
            Py_DECREF(key);
3702
0
            if (status < 0) {
3703
0
                goto Fail;
3704
0
            }
3705
0
        }
3706
3707
0
    }
3708
3709
1.11M
    assert(!PyErr_Occurred());
3710
1.11M
    Py_DECREF(it);
3711
1.11M
    goto Done;
3712
3713
0
Fail:
3714
0
    assert(PyErr_Occurred());
3715
0
    Py_XDECREF(it);
3716
0
    Py_DECREF(d);
3717
0
    return NULL;
3718
3719
1.11M
Done:
3720
1.11M
    if (d == NULL) {
3721
0
        return NULL;
3722
0
    }
3723
3724
1.11M
    if (need_copy) {
3725
0
        PyObject *copy = _PyObject_CallOneArg(cls, d);
3726
0
        Py_SETREF(d, copy);
3727
0
    }
3728
1.11M
    else if (!_PyObject_GC_IS_TRACKED(d)) {
3729
0
        _PyObject_GC_TRACK(d);
3730
0
    }
3731
1.11M
    return d;
3732
1.11M
}
3733
3734
/* Methods */
3735
3736
static void
3737
dict_dealloc(PyObject *self)
3738
153M
{
3739
153M
    PyDictObject *mp = (PyDictObject *)self;
3740
153M
    _PyObject_ResurrectStart(self);
3741
153M
    _PyDict_NotifyEvent(PyDict_EVENT_DEALLOCATED, mp, NULL, NULL);
3742
153M
    if (_PyObject_ResurrectEnd(self)) {
3743
0
        return;
3744
0
    }
3745
153M
    PyDictValues *values = mp->ma_values;
3746
153M
    PyDictKeysObject *keys = mp->ma_keys;
3747
153M
    Py_ssize_t i, n;
3748
3749
    /* bpo-31095: UnTrack is needed before calling any callbacks */
3750
153M
    PyObject_GC_UnTrack(mp);
3751
153M
    if (values != NULL) {
3752
77.5k
        if (values->embedded == 0) {
3753
1.05M
            for (i = 0, n = values->capacity; i < n; i++) {
3754
974k
                Py_XDECREF(values->values[i]);
3755
974k
            }
3756
77.5k
            free_values(values, false);
3757
77.5k
        }
3758
77.5k
        dictkeys_decref(keys, false);
3759
77.5k
    }
3760
153M
    else if (keys != NULL) {
3761
153M
        assert(keys->dk_refcnt == 1 || keys == Py_EMPTY_KEYS);
3762
153M
        dictkeys_decref(keys, false);
3763
153M
    }
3764
153M
    if (Py_IS_TYPE(mp, &PyDict_Type)) {
3765
153M
        _Py_FREELIST_FREE(dicts, mp, Py_TYPE(mp)->tp_free);
3766
153M
    }
3767
165k
    else {
3768
165k
        Py_TYPE(mp)->tp_free((PyObject *)mp);
3769
165k
    }
3770
153M
}
3771
3772
3773
static PyObject *
3774
anydict_repr_impl(PyObject *self)
3775
0
{
3776
0
    PyDictObject *mp = (PyDictObject *)self;
3777
0
    PyObject *key = NULL, *value = NULL;
3778
3779
0
    int res = Py_ReprEnter(self);
3780
0
    if (res != 0) {
3781
0
        return (res > 0 ? PyUnicode_FromString("{...}") : NULL);
3782
0
    }
3783
3784
0
    if (mp->ma_used == 0) {
3785
0
        Py_ReprLeave(self);
3786
0
        return PyUnicode_FromString("{}");
3787
0
    }
3788
3789
    // "{" + "1: 2" + ", 3: 4" * (len - 1) + "}"
3790
0
    Py_ssize_t prealloc = 1 + 4 + 6 * (mp->ma_used - 1) + 1;
3791
0
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(prealloc);
3792
0
    if (writer == NULL) {
3793
0
        goto error;
3794
0
    }
3795
3796
0
    if (PyUnicodeWriter_WriteChar(writer, '{') < 0) {
3797
0
        goto error;
3798
0
    }
3799
3800
    /* Do repr() on each key+value pair, and insert ": " between them.
3801
       Note that repr may mutate the dict. */
3802
0
    Py_ssize_t i = 0;
3803
0
    int first = 1;
3804
0
    while (_PyDict_Next(self, &i, &key, &value, NULL)) {
3805
        // Prevent repr from deleting key or value during key format.
3806
0
        Py_INCREF(key);
3807
0
        Py_INCREF(value);
3808
3809
0
        if (!first) {
3810
            // Write ", "
3811
0
            if (PyUnicodeWriter_WriteChar(writer, ',') < 0) {
3812
0
                goto error;
3813
0
            }
3814
0
            if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) {
3815
0
                goto error;
3816
0
            }
3817
0
        }
3818
0
        first = 0;
3819
3820
        // Write repr(key)
3821
0
        if (PyUnicodeWriter_WriteRepr(writer, key) < 0) {
3822
0
            goto error;
3823
0
        }
3824
3825
        // Write ": "
3826
0
        if (PyUnicodeWriter_WriteChar(writer, ':') < 0) {
3827
0
            goto error;
3828
0
        }
3829
0
        if (PyUnicodeWriter_WriteChar(writer, ' ') < 0) {
3830
0
            goto error;
3831
0
        }
3832
3833
        // Write repr(value)
3834
0
        if (PyUnicodeWriter_WriteRepr(writer, value) < 0) {
3835
0
            goto error;
3836
0
        }
3837
3838
0
        Py_CLEAR(key);
3839
0
        Py_CLEAR(value);
3840
0
    }
3841
3842
0
    if (PyUnicodeWriter_WriteChar(writer, '}') < 0) {
3843
0
        goto error;
3844
0
    }
3845
3846
0
    Py_ReprLeave(self);
3847
3848
0
    return PyUnicodeWriter_Finish(writer);
3849
3850
0
error:
3851
0
    Py_ReprLeave(self);
3852
0
    PyUnicodeWriter_Discard(writer);
3853
0
    Py_XDECREF(key);
3854
0
    Py_XDECREF(value);
3855
0
    return NULL;
3856
0
}
3857
3858
/*[clinic input]
3859
@critical_section
3860
dict.__repr__
3861
3862
    self: self(type="PyObject *")
3863
[clinic start generated code]*/
3864
3865
static PyObject *
3866
dict_repr_impl(PyObject *self)
3867
/*[clinic end generated code: output=059263af818a321d input=f9c423cbdf534674]*/
3868
0
{
3869
0
    ASSERT_DICT_LOCKED((PyDictObject *)self);
3870
0
    return anydict_repr_impl(self);
3871
0
}
3872
3873
static Py_ssize_t
3874
dict_length(PyObject *self)
3875
6.27M
{
3876
6.27M
    return GET_USED(_PyAnyDict_CAST(self));
3877
6.27M
}
3878
3879
static Py_ssize_t
3880
frozendict_length(PyObject *self)
3881
0
{
3882
0
    return _PyAnyDict_CAST(self)->ma_used;
3883
0
}
3884
3885
PyObject *
3886
_PyDict_SubscriptKnownHash(PyObject *self, PyObject *key, Py_hash_t hash)
3887
1.40G
{
3888
1.40G
    PyDictObject *mp = (PyDictObject *)self;
3889
1.40G
    Py_ssize_t ix;
3890
1.40G
    PyObject *value;
3891
3892
1.40G
    ix = _Py_dict_lookup_threadsafe(mp, key, hash, &value);
3893
1.40G
    if (ix == DKIX_ERROR)
3894
0
        return NULL;
3895
1.40G
    if (ix == DKIX_EMPTY || value == NULL) {
3896
4.33M
        if (!PyAnyDict_CheckExact(mp)) {
3897
            /* Look up __missing__ method if we're a subclass. */
3898
1.68k
            PyObject *missing, *res;
3899
1.68k
            missing = _PyObject_LookupSpecial(
3900
1.68k
                    (PyObject *)mp, &_Py_ID(__missing__));
3901
1.68k
            if (missing != NULL) {
3902
759
                res = PyObject_CallOneArg(missing, key);
3903
759
                Py_DECREF(missing);
3904
759
                return res;
3905
759
            }
3906
927
            else if (PyErr_Occurred())
3907
0
                return NULL;
3908
1.68k
        }
3909
4.33M
        _PyErr_SetKeyError(key);
3910
4.33M
        return NULL;
3911
4.33M
    }
3912
1.40G
    return value;
3913
1.40G
}
3914
3915
PyObject *
3916
_PyDict_Subscript(PyObject *self, PyObject *key)
3917
1.40G
{
3918
1.40G
    Py_hash_t hash = _PyObject_HashDictKey(key);
3919
1.40G
    if (hash == -1) {
3920
0
        dict_unhashable_type(self, key);
3921
0
        return NULL;
3922
0
    }
3923
1.40G
    return _PyDict_SubscriptKnownHash(self, key, hash);
3924
1.40G
}
3925
3926
int
3927
_PyDict_StoreSubscript(PyObject *mp, PyObject *v, PyObject *w)
3928
327k
{
3929
327k
    if (w == NULL)
3930
319k
        return PyDict_DelItem(mp, v);
3931
7.90k
    else
3932
7.90k
        return PyDict_SetItem(mp, v, w);
3933
327k
}
3934
3935
static PyMappingMethods dict_as_mapping = {
3936
    dict_length, /*mp_length*/
3937
    _PyDict_Subscript, /*mp_subscript*/
3938
    _PyDict_StoreSubscript, /*mp_ass_subscript*/
3939
};
3940
3941
static PyObject *
3942
keys_lock_held(PyObject *dict)
3943
10.8k
{
3944
10.8k
    ASSERT_DICT_LOCKED(dict);
3945
3946
10.8k
    if (dict == NULL || !PyAnyDict_Check(dict)) {
3947
0
        PyErr_BadInternalCall();
3948
0
        return NULL;
3949
0
    }
3950
10.8k
    PyDictObject *mp = (PyDictObject *)dict;
3951
10.8k
    PyObject *v;
3952
10.8k
    Py_ssize_t n;
3953
3954
10.8k
  again:
3955
10.8k
    n = mp->ma_used;
3956
10.8k
    v = PyList_New(n);
3957
10.8k
    if (v == NULL)
3958
0
        return NULL;
3959
10.8k
    if (n != mp->ma_used) {
3960
        /* Durnit.  The allocations caused the dict to resize.
3961
         * Just start over, this shouldn't normally happen.
3962
         */
3963
0
        Py_DECREF(v);
3964
0
        goto again;
3965
0
    }
3966
3967
    /* Nothing we do below makes any function calls. */
3968
10.8k
    Py_ssize_t j = 0, pos = 0;
3969
10.8k
    PyObject *key;
3970
727k
    while (_PyDict_Next((PyObject*)mp, &pos, &key, NULL, NULL)) {
3971
716k
        assert(j < n);
3972
716k
        PyList_SET_ITEM(v, j, Py_NewRef(key));
3973
716k
        j++;
3974
716k
    }
3975
10.8k
    assert(j == n);
3976
10.8k
    return v;
3977
10.8k
}
3978
3979
PyObject *
3980
PyDict_Keys(PyObject *dict)
3981
10.8k
{
3982
10.8k
    PyObject *res;
3983
10.8k
    Py_BEGIN_CRITICAL_SECTION(dict);
3984
10.8k
    res = keys_lock_held(dict);
3985
10.8k
    Py_END_CRITICAL_SECTION();
3986
3987
10.8k
    return res;
3988
10.8k
}
3989
3990
static PyObject *
3991
values_lock_held(PyObject *dict)
3992
0
{
3993
0
    ASSERT_DICT_LOCKED(dict);
3994
3995
0
    if (dict == NULL || !PyAnyDict_Check(dict)) {
3996
0
        PyErr_BadInternalCall();
3997
0
        return NULL;
3998
0
    }
3999
0
    PyDictObject *mp = (PyDictObject *)dict;
4000
0
    PyObject *v;
4001
0
    Py_ssize_t n;
4002
4003
0
  again:
4004
0
    n = mp->ma_used;
4005
0
    v = PyList_New(n);
4006
0
    if (v == NULL)
4007
0
        return NULL;
4008
0
    if (n != mp->ma_used) {
4009
        /* Durnit.  The allocations caused the dict to resize.
4010
         * Just start over, this shouldn't normally happen.
4011
         */
4012
0
        Py_DECREF(v);
4013
0
        goto again;
4014
0
    }
4015
4016
    /* Nothing we do below makes any function calls. */
4017
0
    Py_ssize_t j = 0, pos = 0;
4018
0
    PyObject *value;
4019
0
    while (_PyDict_Next((PyObject*)mp, &pos, NULL, &value, NULL)) {
4020
0
        assert(j < n);
4021
0
        PyList_SET_ITEM(v, j, Py_NewRef(value));
4022
0
        j++;
4023
0
    }
4024
0
    assert(j == n);
4025
0
    return v;
4026
0
}
4027
4028
PyObject *
4029
PyDict_Values(PyObject *dict)
4030
0
{
4031
0
    PyObject *res;
4032
0
    Py_BEGIN_CRITICAL_SECTION(dict);
4033
0
    res = values_lock_held(dict);
4034
0
    Py_END_CRITICAL_SECTION();
4035
0
    return res;
4036
0
}
4037
4038
static PyObject *
4039
items_lock_held(PyObject *dict)
4040
0
{
4041
0
    ASSERT_DICT_LOCKED(dict);
4042
4043
0
    if (dict == NULL || !PyAnyDict_Check(dict)) {
4044
0
        PyErr_BadInternalCall();
4045
0
        return NULL;
4046
0
    }
4047
0
    PyDictObject *mp = (PyDictObject *)dict;
4048
0
    PyObject *v;
4049
0
    Py_ssize_t i, n;
4050
0
    PyObject *item;
4051
4052
    /* Preallocate the list of tuples, to avoid allocations during
4053
     * the loop over the items, which could trigger GC, which
4054
     * could resize the dict. :-(
4055
     */
4056
0
  again:
4057
0
    n = mp->ma_used;
4058
0
    v = PyList_New(n);
4059
0
    if (v == NULL)
4060
0
        return NULL;
4061
0
    for (i = 0; i < n; i++) {
4062
0
        item = PyTuple_New(2);
4063
0
        if (item == NULL) {
4064
0
            Py_DECREF(v);
4065
0
            return NULL;
4066
0
        }
4067
0
        PyList_SET_ITEM(v, i, item);
4068
0
    }
4069
0
    if (n != mp->ma_used) {
4070
        /* Durnit.  The allocations caused the dict to resize.
4071
         * Just start over, this shouldn't normally happen.
4072
         */
4073
0
        Py_DECREF(v);
4074
0
        goto again;
4075
0
    }
4076
4077
    /* Nothing we do below makes any function calls. */
4078
0
    Py_ssize_t j = 0, pos = 0;
4079
0
    PyObject *key, *value;
4080
0
    while (_PyDict_Next((PyObject*)mp, &pos, &key, &value, NULL)) {
4081
0
        assert(j < n);
4082
0
        PyObject *item = PyList_GET_ITEM(v, j);
4083
0
        PyTuple_SET_ITEM(item, 0, Py_NewRef(key));
4084
0
        PyTuple_SET_ITEM(item, 1, Py_NewRef(value));
4085
0
        j++;
4086
0
    }
4087
0
    assert(j == n);
4088
0
    return v;
4089
0
}
4090
4091
PyObject *
4092
PyDict_Items(PyObject *dict)
4093
0
{
4094
0
    PyObject *res;
4095
0
    Py_BEGIN_CRITICAL_SECTION(dict);
4096
0
    res = items_lock_held(dict);
4097
0
    Py_END_CRITICAL_SECTION();
4098
4099
0
    return res;
4100
0
}
4101
4102
/*[clinic input]
4103
@permit_long_summary
4104
@classmethod
4105
dict.fromkeys
4106
    iterable: object
4107
    value: object=None
4108
    /
4109
4110
Create a new dictionary with keys from iterable and values set to value.
4111
[clinic start generated code]*/
4112
4113
static PyObject *
4114
dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
4115
/*[clinic end generated code: output=8fb98e4b10384999 input=3903715eb48b287e]*/
4116
1.11M
{
4117
1.11M
    return _PyDict_FromKeys((PyObject *)type, iterable, value);
4118
1.11M
}
4119
4120
/* Single-arg dict update; used by dict_update_common and operators. */
4121
static int
4122
dict_update_arg(PyObject *self, PyObject *arg)
4123
6.45k
{
4124
6.45k
    if (PyAnyDict_CheckExact(arg)) {
4125
5.65k
        return dict_merge(self, arg, 1, NULL);
4126
5.65k
    }
4127
791
    int has_keys = PyObject_HasAttrWithError(arg, &_Py_ID(keys));
4128
791
    if (has_keys < 0) {
4129
0
        return -1;
4130
0
    }
4131
791
    if (has_keys) {
4132
419
        return dict_merge(self, arg, 1, NULL);
4133
419
    }
4134
372
    return dict_merge_from_seq2(self, arg, 1);
4135
791
}
4136
4137
static int
4138
dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
4139
                   const char *methname)
4140
167k
{
4141
167k
    PyObject *arg = NULL;
4142
167k
    int result = 0;
4143
4144
167k
    if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
4145
0
        result = -1;
4146
0
    }
4147
167k
    else if (arg != NULL) {
4148
2.01k
        result = dict_update_arg(self, arg);
4149
2.01k
    }
4150
4151
167k
    if (result == 0 && kwds != NULL) {
4152
32
        if (PyArg_ValidateKeywordArguments(kwds))
4153
32
            result = dict_merge(self, kwds, 1, NULL);
4154
0
        else
4155
0
            result = -1;
4156
32
    }
4157
167k
    return result;
4158
167k
}
4159
4160
/* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
4161
   Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
4162
   slower, see the issue #29312. */
4163
static PyObject *
4164
dict_update(PyObject *self, PyObject *args, PyObject *kwds)
4165
2.01k
{
4166
2.01k
    if (dict_update_common(self, args, kwds, "update") != -1)
4167
2.01k
        Py_RETURN_NONE;
4168
0
    return NULL;
4169
2.01k
}
4170
4171
/* Update unconditionally replaces existing items.
4172
   Merge has a 3rd argument 'override'; if set, it acts like Update,
4173
   otherwise it leaves existing items unchanged.
4174
4175
   PyDict_{Update,Merge} update/merge from a mapping object.
4176
4177
   PyDict_MergeFromSeq2 updates/merges from any iterable object
4178
   producing iterable objects of length 2.
4179
*/
4180
4181
static int
4182
merge_from_seq2_lock_held(PyObject *d, PyObject *seq2, int override)
4183
372
{
4184
372
    PyObject *it;       /* iter(seq2) */
4185
372
    Py_ssize_t i;       /* index into seq2 of current element */
4186
372
    PyObject *item;     /* seq2[i] */
4187
372
    PyObject *fast;     /* item as a 2-tuple or 2-list */
4188
4189
372
    assert(d != NULL);
4190
372
    assert(PyAnyDict_Check(d));
4191
372
    assert(seq2 != NULL);
4192
372
    assert(can_modify_dict((PyDictObject*)d));
4193
4194
372
    it = PyObject_GetIter(seq2);
4195
372
    if (it == NULL)
4196
0
        return -1;
4197
4198
6.02k
    for (i = 0; ; ++i) {
4199
6.02k
        PyObject *key = NULL, *value = NULL;
4200
6.02k
        Py_ssize_t n;
4201
4202
6.02k
        fast = NULL;
4203
6.02k
        item = PyIter_Next(it);
4204
6.02k
        if (item == NULL) {
4205
372
            if (PyErr_Occurred())
4206
0
                goto Fail;
4207
372
            break;
4208
372
        }
4209
4210
        /* Convert item to sequence, and verify length 2. */
4211
5.65k
        fast = PySequence_Fast(item, "object is not iterable");
4212
5.65k
        if (fast == NULL) {
4213
0
            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4214
0
                _PyErr_FormatNote(
4215
0
                    "Cannot convert dictionary update "
4216
0
                    "sequence element #%zd to a sequence",
4217
0
                    i);
4218
0
            }
4219
0
            goto Fail;
4220
0
        }
4221
5.65k
        Py_BEGIN_CRITICAL_SECTION_SEQUENCE_FAST(item);
4222
5.65k
        n = PySequence_Fast_GET_SIZE(fast);
4223
5.65k
        if (n == 2) {
4224
5.65k
            key = Py_NewRef(PySequence_Fast_GET_ITEM(fast, 0));
4225
5.65k
            value = Py_NewRef(PySequence_Fast_GET_ITEM(fast, 1));
4226
5.65k
        }
4227
5.65k
        Py_END_CRITICAL_SECTION_SEQUENCE_FAST();
4228
5.65k
        if (n != 2) {
4229
0
            PyErr_Format(PyExc_ValueError,
4230
0
                         "dictionary update sequence element #%zd "
4231
0
                         "has length %zd; 2 is required",
4232
0
                         i, n);
4233
0
            goto Fail;
4234
0
        }
4235
4236
        /* Update/merge with this (key, value) pair. */
4237
5.65k
        if (override) {
4238
5.65k
            if (setitem_lock_held((PyDictObject *)d, key, value) < 0) {
4239
0
                Py_DECREF(key);
4240
0
                Py_DECREF(value);
4241
0
                goto Fail;
4242
0
            }
4243
5.65k
        }
4244
0
        else {
4245
0
            if (dict_setdefault_ref_lock_held(d, key, value, NULL, 0) < 0) {
4246
0
                Py_DECREF(key);
4247
0
                Py_DECREF(value);
4248
0
                goto Fail;
4249
0
            }
4250
0
        }
4251
4252
5.65k
        Py_DECREF(key);
4253
5.65k
        Py_DECREF(value);
4254
5.65k
        Py_DECREF(fast);
4255
5.65k
        Py_DECREF(item);
4256
5.65k
    }
4257
4258
372
    i = 0;
4259
372
    ASSERT_CONSISTENT(d);
4260
372
    goto Return;
4261
0
Fail:
4262
0
    Py_XDECREF(item);
4263
0
    Py_XDECREF(fast);
4264
0
    i = -1;
4265
372
Return:
4266
372
    Py_DECREF(it);
4267
372
    return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
4268
0
}
4269
4270
static int
4271
dict_merge_from_seq2(PyObject *d, PyObject *seq2, int override)
4272
372
{
4273
372
    int res;
4274
372
    Py_BEGIN_CRITICAL_SECTION(d);
4275
372
    res = merge_from_seq2_lock_held(d, seq2, override);
4276
372
    Py_END_CRITICAL_SECTION();
4277
4278
372
    return res;
4279
372
}
4280
4281
int
4282
PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
4283
0
{
4284
0
    assert(d != NULL);
4285
0
    assert(seq2 != NULL);
4286
0
    if (!PyDict_Check(d)) {
4287
0
        if (PyFrozenDict_Check(d)) {
4288
0
            frozendict_does_not_support("assignment");
4289
0
        }
4290
0
        else {
4291
0
            PyErr_BadInternalCall();
4292
0
        }
4293
0
        return -1;
4294
0
    }
4295
4296
0
    return dict_merge_from_seq2(d, seq2, override);
4297
0
}
4298
4299
4300
/* Copy only live entries from a combined table, preserving insertion order.
4301
   The source is locked while its keys and values are referenced. */
4302
static PyDictKeysObject *
4303
dict_copy_keys(PyDictObject *orig)
4304
532k
{
4305
532k
    assert(PyAnyDict_Check(orig));
4306
532k
    assert(Py_TYPE(orig)->tp_iter == dict_iter);
4307
532k
    assert(orig->ma_values == NULL);
4308
532k
    assert(orig->ma_used > 0);
4309
532k
    if (!PyFrozenDict_Check(orig)) {
4310
532k
        ASSERT_DICT_LOCKED(orig);
4311
532k
    }
4312
4313
532k
    PyDictKeysObject *oldkeys = orig->ma_keys;
4314
532k
    Py_ssize_t used = orig->ma_used;
4315
532k
    int unicode = DK_IS_UNICODE(oldkeys);
4316
532k
    PyDictKeysObject *keys = new_keys_object(estimate_log2_keysize(used),
4317
532k
                                            unicode);
4318
532k
    if (keys == NULL) {
4319
0
        return NULL;
4320
0
    }
4321
4322
532k
    if (unicode) {
4323
532k
        PyDictUnicodeEntry *src = DK_UNICODE_ENTRIES(oldkeys);
4324
532k
        PyDictUnicodeEntry *dst = DK_UNICODE_ENTRIES(keys);
4325
1.86M
        for (Py_ssize_t i = 0; i < used; i++) {
4326
1.59M
            while (src->me_value == NULL) {
4327
265k
                src++;
4328
265k
            }
4329
1.33M
            dst[i] = *src++;
4330
1.33M
            Py_INCREF(dst[i].me_key);
4331
1.33M
            Py_INCREF(dst[i].me_value);
4332
1.33M
        }
4333
532k
        build_indices_unicode(keys, dst, used);
4334
532k
    }
4335
0
    else {
4336
0
        PyDictKeyEntry *src = DK_ENTRIES(oldkeys);
4337
0
        PyDictKeyEntry *dst = DK_ENTRIES(keys);
4338
0
        for (Py_ssize_t i = 0; i < used; i++) {
4339
0
            while (src->me_value == NULL) {
4340
0
                src++;
4341
0
            }
4342
0
            dst[i] = *src++;
4343
0
            Py_INCREF(dst[i].me_key);
4344
0
            Py_INCREF(dst[i].me_value);
4345
0
        }
4346
0
        build_indices_generic(keys, dst, used);
4347
0
    }
4348
532k
    keys->dk_nentries = used;
4349
532k
    keys->dk_usable -= used;
4350
532k
    return keys;
4351
532k
}
4352
4353
static int
4354
dict_dict_merge(PyDictObject *mp, PyDictObject *other, int override, PyObject **dupkey)
4355
20.5M
{
4356
20.5M
    assert(can_modify_dict(mp));
4357
20.5M
    if (!PyFrozenDict_Check(other)) {
4358
20.5M
        ASSERT_DICT_LOCKED(other);
4359
20.5M
    }
4360
4361
20.5M
    if (other == mp || other->ma_used == 0)
4362
        /* a.update(a) or a.update({}); nothing to do */
4363
16.8M
        return 0;
4364
3.69M
    if (mp->ma_used == 0) {
4365
        // Copy a combined table directly, compacting deleted entries.
4366
3.69M
        if (mp->ma_values == NULL && other->ma_values == NULL) {
4367
3.69M
            PyDictKeysObject *okeys = other->ma_keys;
4368
3.69M
            PyDictKeysObject *keys;
4369
3.69M
            if (other->ma_used == okeys->dk_nentries &&
4370
3.15M
                (DK_LOG_SIZE(okeys) == PyDict_LOG_MINSIZE ||
4371
3.15M
                 USABLE_FRACTION(DK_SIZE(okeys)/2) < other->ma_used)) {
4372
3.15M
                keys = clone_combined_dict_keys(other);
4373
3.15M
            }
4374
532k
            else {
4375
532k
                keys = dict_copy_keys(other);
4376
532k
            }
4377
3.69M
            if (keys == NULL)
4378
0
                return -1;
4379
4380
3.69M
            _PyDict_NotifyEvent(PyDict_EVENT_CLONED, mp, (PyObject *)other, NULL);
4381
3.69M
            ensure_shared_on_resize(mp);
4382
3.69M
            dictkeys_decref(mp->ma_keys, IS_DICT_SHARED(mp));
4383
3.69M
            set_keys(mp, keys);
4384
3.69M
            STORE_USED(mp, keys->dk_nentries);
4385
3.69M
            ASSERT_CONSISTENT(mp);
4386
3.69M
            return 0;
4387
3.69M
        }
4388
4389
        /* Since the target dict is empty, _PyDict_Contains_KnownHash()
4390
         * always returns 0.  Setting override to 1
4391
         * skips the unnecessary test.
4392
         */
4393
16
        override = 1;
4394
16
    }
4395
    /* Do one big resize at the start, rather than
4396
        * incrementally resizing as we insert new items.  Expect
4397
        * that there will be no (or few) overlapping keys.
4398
        */
4399
3.85k
    if (USABLE_FRACTION(DK_SIZE(mp->ma_keys)) < other->ma_used) {
4400
27
        int unicode = DK_IS_UNICODE(other->ma_keys);
4401
27
        if (dictresize(mp, estimate_log2_keysize(mp->ma_used + other->ma_used),
4402
27
                        unicode)) {
4403
0
            return -1;
4404
0
        }
4405
27
    }
4406
4407
3.85k
    Py_ssize_t orig_size = other->ma_used;
4408
3.85k
    Py_ssize_t pos = 0;
4409
3.85k
    Py_hash_t hash;
4410
3.85k
    PyObject *key, *value;
4411
4412
73.3k
    while (_PyDict_Next((PyObject*)other, &pos, &key, &value, &hash)) {
4413
69.4k
        int err = 0;
4414
69.4k
        if (override == 1) {
4415
69.4k
            err = insertdict(mp, Py_NewRef(key), hash, Py_NewRef(value));
4416
69.4k
        }
4417
8
        else {
4418
8
            Py_INCREF(key);
4419
8
            Py_INCREF(value);
4420
8
            err = _PyDict_Contains_KnownHash((PyObject *)mp, key, hash);
4421
8
            if (err == 0) {
4422
8
                err = insertdict(mp, Py_NewRef(key), hash, Py_NewRef(value));
4423
8
            }
4424
0
            else if (err > 0) {
4425
0
                if (dupkey != NULL) {
4426
0
                    *dupkey = key;
4427
0
                    Py_DECREF(value);
4428
0
                    return -2;
4429
0
                }
4430
0
                err = 0;
4431
0
            }
4432
8
            Py_DECREF(value);
4433
8
            Py_DECREF(key);
4434
8
        }
4435
69.4k
        if (err != 0)
4436
0
            return -1;
4437
4438
69.4k
        if (orig_size != other->ma_used) {
4439
0
            PyErr_SetString(PyExc_RuntimeError,
4440
0
                    "dict mutated during update");
4441
0
            return -1;
4442
0
        }
4443
69.4k
    }
4444
3.85k
    return 0;
4445
3.85k
}
4446
4447
static int
4448
dict_merge(PyObject *a, PyObject *b, int override, PyObject **dupkey)
4449
20.5M
{
4450
20.5M
    assert(a != NULL);
4451
20.5M
    assert(b != NULL);
4452
20.5M
    assert(0 <= override && override <= 2);
4453
4454
20.5M
    PyDictObject *mp = _PyAnyDict_CAST(a);
4455
4456
20.5M
    int res = 0;
4457
20.5M
    if (PyAnyDict_Check(b) && (Py_TYPE(b)->tp_iter == dict_iter)) {
4458
20.5M
        PyDictObject *other = (PyDictObject*)b;
4459
20.5M
        int res;
4460
20.5M
        Py_BEGIN_CRITICAL_SECTION2(a, b);
4461
20.5M
        assert(can_modify_dict(mp));
4462
20.5M
        res = dict_dict_merge((PyDictObject *)a, other, override, dupkey);
4463
20.5M
        ASSERT_CONSISTENT(a);
4464
20.5M
        Py_END_CRITICAL_SECTION2();
4465
20.5M
        return res;
4466
20.5M
    }
4467
73.3k
    else {
4468
        /* Do it the generic, slower way */
4469
73.3k
        Py_BEGIN_CRITICAL_SECTION(a);
4470
73.3k
        assert(can_modify_dict(mp));
4471
4472
73.3k
        PyObject *keys = PyMapping_Keys(b);
4473
73.3k
        PyObject *iter;
4474
73.3k
        PyObject *key, *value;
4475
73.3k
        int status;
4476
4477
73.3k
        if (keys == NULL) {
4478
            /* Docstring says this is equivalent to E.keys() so
4479
             * if E doesn't have a .keys() method we want
4480
             * AttributeError to percolate up.  Might as well
4481
             * do the same for any other error.
4482
             */
4483
0
            res = -1;
4484
0
            goto slow_exit;
4485
0
        }
4486
4487
73.3k
        iter = PyObject_GetIter(keys);
4488
73.3k
        Py_DECREF(keys);
4489
73.3k
        if (iter == NULL) {
4490
0
            res = -1;
4491
0
            goto slow_exit;
4492
0
        }
4493
4494
1.49M
        for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
4495
1.42M
            if (override != 1) {
4496
0
                status = dict_contains(a, key);
4497
0
                if (status != 0) {
4498
0
                    if (status > 0) {
4499
0
                        if (dupkey == NULL) {
4500
0
                            Py_DECREF(key);
4501
0
                            continue;
4502
0
                        }
4503
0
                        *dupkey = key;
4504
0
                        res = -2;
4505
0
                    }
4506
0
                    else {
4507
0
                        Py_DECREF(key);
4508
0
                        res = -1;
4509
0
                    }
4510
0
                    Py_DECREF(iter);
4511
0
                    goto slow_exit;
4512
0
                }
4513
0
            }
4514
1.42M
            value = PyObject_GetItem(b, key);
4515
1.42M
            if (value == NULL) {
4516
0
                Py_DECREF(iter);
4517
0
                Py_DECREF(key);
4518
0
                res = -1;
4519
0
                goto slow_exit;
4520
0
            }
4521
1.42M
            status = setitem_lock_held(mp, key, value);
4522
1.42M
            Py_DECREF(key);
4523
1.42M
            Py_DECREF(value);
4524
1.42M
            if (status < 0) {
4525
0
                Py_DECREF(iter);
4526
0
                res = -1;
4527
0
                goto slow_exit;
4528
0
                return -1;
4529
0
            }
4530
1.42M
        }
4531
73.3k
        Py_DECREF(iter);
4532
73.3k
        if (PyErr_Occurred()) {
4533
            /* Iterator completed, via error */
4534
0
            res = -1;
4535
0
            goto slow_exit;
4536
0
        }
4537
4538
73.3k
slow_exit:
4539
73.3k
        ASSERT_CONSISTENT(a);
4540
73.3k
        Py_END_CRITICAL_SECTION();
4541
73.3k
        return res;
4542
73.3k
    }
4543
20.5M
}
4544
4545
static int
4546
dict_merge_api(PyObject *a, PyObject *b, int override, PyObject **dupkey)
4547
20.5M
{
4548
    /* We accept for the argument either a concrete dictionary object,
4549
     * or an abstract "mapping" object.  For the former, we can do
4550
     * things quite efficiently.  For the latter, we only require that
4551
     * PyMapping_Keys() and PyObject_GetItem() be supported.
4552
     */
4553
20.5M
    if (a == NULL || !PyDict_Check(a) || b == NULL) {
4554
0
        if (a != NULL && PyFrozenDict_Check(a)) {
4555
0
            frozendict_does_not_support("assignment");
4556
0
        }
4557
0
        else {
4558
0
            PyErr_BadInternalCall();
4559
0
        }
4560
0
        return -1;
4561
0
    }
4562
4563
20.5M
    int res = dict_merge(a, b, override, dupkey);
4564
20.5M
    assert(_PyObject_GC_IS_TRACKED(a));
4565
20.5M
    return res;
4566
20.5M
}
4567
4568
int
4569
PyDict_Update(PyObject *a, PyObject *b)
4570
77.0k
{
4571
77.0k
    return dict_merge_api(a, b, 1, NULL);
4572
77.0k
}
4573
4574
int
4575
PyDict_Merge(PyObject *a, PyObject *b, int override)
4576
0
{
4577
    /* XXX Deprecate override not in (0, 1). */
4578
0
    return dict_merge_api(a, b, override != 0, NULL);
4579
0
}
4580
4581
int
4582
_PyDict_MergeUniq(PyObject *a, PyObject *b, PyObject **dupkey)
4583
20.4M
{
4584
20.4M
    return dict_merge_api(a, b, 2, dupkey);
4585
20.4M
}
4586
4587
/*[clinic input]
4588
dict.copy
4589
4590
Return a shallow copy of the dict.
4591
[clinic start generated code]*/
4592
4593
static PyObject *
4594
dict_copy_impl(PyDictObject *self)
4595
/*[clinic end generated code: output=ffb782cf970a5c39 input=73935f042b639de4]*/
4596
664k
{
4597
664k
    return PyDict_Copy((PyObject *)self);
4598
664k
}
4599
4600
/* Copies the values, but does not change the reference
4601
 * counts of the objects in the array.
4602
 * Return NULL, but does *not* set an exception on failure  */
4603
static PyDictValues *
4604
copy_values(PyDictValues *values)
4605
83.8k
{
4606
83.8k
    PyDictValues *newvalues = new_values(values->capacity);
4607
83.8k
    if (newvalues == NULL) {
4608
0
        return NULL;
4609
0
    }
4610
83.8k
    newvalues->size = values->size;
4611
83.8k
    uint8_t *values_order = get_insertion_order_array(values);
4612
83.8k
    uint8_t *new_values_order = get_insertion_order_array(newvalues);
4613
83.8k
    memcpy(new_values_order, values_order, values->capacity);
4614
1.24M
    for (int i = 0; i < values->capacity; i++) {
4615
1.16M
        newvalues->values[i] = values->values[i];
4616
1.16M
    }
4617
83.8k
    assert(newvalues->embedded == 0);
4618
83.8k
    return newvalues;
4619
83.8k
}
4620
4621
static PyObject *
4622
copy_lock_held_untracked(PyObject *o, int as_frozendict)
4623
1.23M
{
4624
1.23M
    PyObject *copy;
4625
1.23M
    PyDictObject *mp;
4626
4627
    // frozendict is immutable and so doesn't need critical section
4628
1.23M
    if (!PyFrozenDict_Check(o)) {
4629
1.23M
        ASSERT_DICT_LOCKED(o);
4630
1.23M
    }
4631
4632
1.23M
    mp = (PyDictObject *)o;
4633
1.23M
    if (mp->ma_used == 0) {
4634
        /* The dict is empty; just return a new dict. */
4635
847k
        PyObject *d;
4636
847k
        if (as_frozendict) {
4637
0
            d = frozendict_new_untracked(&PyFrozenDict_Type);
4638
0
        }
4639
847k
        else {
4640
847k
            d = dict_new_untracked(&PyDict_Type);
4641
847k
        }
4642
847k
        assert(d == NULL || !_PyObject_GC_IS_TRACKED(d));
4643
847k
        return d;
4644
847k
    }
4645
4646
387k
    if (_PyDict_HasSplitTable(mp)) {
4647
6.62k
        PyDictObject *split_copy;
4648
6.62k
        PyDictValues *newvalues = copy_values(mp->ma_values);
4649
6.62k
        if (newvalues == NULL) {
4650
0
            return PyErr_NoMemory();
4651
0
        }
4652
6.62k
        if (as_frozendict) {
4653
0
            split_copy = (PyDictObject *)PyObject_GC_New(PyFrozenDictObject,
4654
0
                                                         &PyFrozenDict_Type);
4655
0
        }
4656
6.62k
        else {
4657
6.62k
            split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
4658
6.62k
        }
4659
6.62k
        if (split_copy == NULL) {
4660
0
            free_values(newvalues, false);
4661
0
            return NULL;
4662
0
        }
4663
198k
        for (size_t i = 0; i < newvalues->capacity; i++) {
4664
192k
            Py_XINCREF(newvalues->values[i]);
4665
192k
        }
4666
6.62k
        split_copy->ma_values = newvalues;
4667
6.62k
        split_copy->ma_keys = mp->ma_keys;
4668
6.62k
        split_copy->ma_used = mp->ma_used;
4669
6.62k
        split_copy->_ma_watcher_tag = 0;
4670
6.62k
        dictkeys_incref(mp->ma_keys);
4671
6.62k
        if (as_frozendict) {
4672
0
            PyFrozenDictObject *frozen = (PyFrozenDictObject *)split_copy;
4673
0
            frozen->ma_hash = -1;
4674
0
        }
4675
6.62k
        assert(!_PyObject_GC_IS_TRACKED(split_copy));
4676
6.62k
        return (PyObject *)split_copy;
4677
6.62k
    }
4678
4679
380k
    if (Py_TYPE(mp)->tp_iter == dict_iter) {
4680
        /* Use fast-copy if:
4681
4682
           (1) type(mp) doesn't override tp_iter; and
4683
4684
           (2) 'mp' is not a split-dict.
4685
4686
           Dicts don't compact themselves on del/pop operations, so a large
4687
           dict can have very few live entries. Previously, fast-copy was
4688
           restricted to tables with at most 1/3 non-used entries; otherwise
4689
           PyDict_Merge produced a compacted copy.
4690
4691
           Clone tables with few deleted entries as-is. For sparse tables,
4692
           copy only live entries into a compact table instead of retaining
4693
           deleted slots or reinserting entries one by one.
4694
        */
4695
380k
        PyDictKeysObject *keys;
4696
380k
        if (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3) {
4697
380k
            keys = clone_combined_dict_keys(mp);
4698
380k
        }
4699
0
        else {
4700
0
            keys = dict_copy_keys(mp);
4701
0
        }
4702
380k
        if (keys == NULL) {
4703
0
            return NULL;
4704
0
        }
4705
380k
        PyDictObject *new;
4706
380k
        if (as_frozendict) {
4707
0
            new = (PyDictObject *)new_frozendict_untracked(keys, NULL, 0, 0);
4708
0
        }
4709
380k
        else {
4710
380k
            new = (PyDictObject *)new_dict_untracked(keys, NULL, 0, 0);
4711
380k
        }
4712
380k
        if (new == NULL) {
4713
            /* In case of an error, new_dict()/new_frozendict() takes care of
4714
               cleaning up `keys`. */
4715
0
            return NULL;
4716
0
        }
4717
4718
380k
        new->ma_used = mp->ma_used;
4719
380k
        ASSERT_CONSISTENT(new);
4720
380k
        assert(!_PyObject_GC_IS_TRACKED(new));
4721
380k
        return (PyObject *)new;
4722
380k
    }
4723
4724
0
    if (as_frozendict) {
4725
0
        copy = frozendict_new_untracked(&PyFrozenDict_Type);
4726
0
    }
4727
0
    else {
4728
0
        copy = dict_new_untracked(&PyDict_Type);
4729
0
    }
4730
0
    if (copy == NULL)
4731
0
        return NULL;
4732
0
    if (dict_merge(copy, o, 1, NULL) < 0) {
4733
0
        Py_DECREF(copy);
4734
0
        return NULL;
4735
0
    }
4736
4737
0
    assert(!_PyObject_GC_IS_TRACKED(copy));
4738
0
    return copy;
4739
0
}
4740
4741
PyObject *
4742
PyDict_Copy(PyObject *o)
4743
953k
{
4744
953k
    if (o == NULL || !PyDict_Check(o)) {
4745
0
        PyErr_BadInternalCall();
4746
0
        return NULL;
4747
0
    }
4748
4749
953k
    PyObject *res;
4750
953k
    Py_BEGIN_CRITICAL_SECTION(o);
4751
953k
    res = copy_lock_held_untracked(o, 0);
4752
953k
    Py_END_CRITICAL_SECTION();
4753
953k
    if (res != NULL) {
4754
953k
        _PyObject_GC_TRACK(res);
4755
953k
    }
4756
953k
    return res;
4757
953k
}
4758
4759
// Similar to PyDict_Copy(), but return a frozendict if the argument
4760
// is a frozendict.
4761
static PyObject *
4762
anydict_copy_untracked(PyObject *o)
4763
6
{
4764
6
    assert(PyAnyDict_Check(o));
4765
4766
6
    PyObject *res;
4767
6
    if (PyFrozenDict_Check(o)) {
4768
0
        res = copy_lock_held_untracked(o, 1);
4769
0
    }
4770
6
    else {
4771
6
        Py_BEGIN_CRITICAL_SECTION(o);
4772
6
        res = copy_lock_held_untracked(o, 0);
4773
6
        Py_END_CRITICAL_SECTION();
4774
6
    }
4775
6
    return res;
4776
6
}
4777
4778
// Similar to PyDict_Copy(), but accept also frozendict:
4779
// convert frozendict to a new dict.
4780
PyObject*
4781
_PyDict_CopyAsDict(PyObject *o)
4782
281k
{
4783
281k
    assert(PyAnyDict_Check(o));
4784
4785
281k
    PyObject *res;
4786
281k
    if (PyFrozenDict_Check(o)) {
4787
0
        res = copy_lock_held_untracked(o, 0);
4788
0
    }
4789
281k
    else {
4790
281k
        Py_BEGIN_CRITICAL_SECTION(o);
4791
281k
        res = copy_lock_held_untracked(o, 0);
4792
281k
        Py_END_CRITICAL_SECTION();
4793
281k
    }
4794
281k
    if (res != NULL) {
4795
281k
        _PyObject_GC_TRACK(res);
4796
281k
    }
4797
281k
    return res;
4798
281k
}
4799
4800
Py_ssize_t
4801
PyDict_Size(PyObject *mp)
4802
535k
{
4803
535k
    if (mp == NULL || !PyAnyDict_Check(mp)) {
4804
0
        PyErr_BadInternalCall();
4805
0
        return -1;
4806
0
    }
4807
535k
    return GET_USED((PyDictObject *)mp);
4808
535k
}
4809
4810
/* Return 1 if dicts equal, 0 if not, -1 if error.
4811
 * Gets out as soon as any difference is detected.
4812
 * Uses only Py_EQ comparison.
4813
 */
4814
static int
4815
dict_equal_lock_held(PyDictObject *a, PyDictObject *b)
4816
678
{
4817
678
    Py_ssize_t i;
4818
4819
678
    ASSERT_DICT_LOCKED(a);
4820
678
    ASSERT_DICT_LOCKED(b);
4821
4822
678
    if (a->ma_used != b->ma_used)
4823
        /* can't be equal if # of entries differ */
4824
0
        return 0;
4825
    /* Same # of entries -- check all of 'em.  Exit early on any diff. */
4826
846
    for (i = 0; i < LOAD_KEYS_NENTRIES(a->ma_keys); i++) {
4827
168
        PyObject *key, *aval;
4828
168
        Py_hash_t hash;
4829
168
        if (DK_IS_UNICODE(a->ma_keys)) {
4830
168
            PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(a->ma_keys)[i];
4831
168
            key = ep->me_key;
4832
168
            if (key == NULL) {
4833
0
                continue;
4834
0
            }
4835
168
            hash = unicode_get_hash(key);
4836
168
            if (_PyDict_HasSplitTable(a))
4837
0
                aval = a->ma_values->values[i];
4838
168
            else
4839
168
                aval = ep->me_value;
4840
168
        }
4841
0
        else {
4842
0
            PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
4843
0
            key = ep->me_key;
4844
0
            aval = ep->me_value;
4845
0
            hash = ep->me_hash;
4846
0
        }
4847
168
        if (aval != NULL) {
4848
168
            int cmp;
4849
168
            PyObject *bval;
4850
            /* temporarily bump aval's refcount to ensure it stays
4851
               alive until we're done with it */
4852
168
            Py_INCREF(aval);
4853
            /* ditto for key */
4854
168
            Py_INCREF(key);
4855
            /* reuse the known hash value */
4856
168
            _Py_dict_lookup(b, key, hash, &bval);
4857
168
            if (bval == NULL) {
4858
0
                Py_DECREF(key);
4859
0
                Py_DECREF(aval);
4860
0
                if (PyErr_Occurred())
4861
0
                    return -1;
4862
0
                return 0;
4863
0
            }
4864
168
            Py_INCREF(bval);
4865
168
            cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
4866
168
            Py_DECREF(key);
4867
168
            Py_DECREF(aval);
4868
168
            Py_DECREF(bval);
4869
168
            if (cmp <= 0)  /* error or not equal */
4870
0
                return cmp;
4871
168
        }
4872
168
    }
4873
678
    return 1;
4874
678
}
4875
4876
static int
4877
dict_equal(PyDictObject *a, PyDictObject *b)
4878
678
{
4879
678
    int res;
4880
678
    Py_BEGIN_CRITICAL_SECTION2(a, b);
4881
678
    res = dict_equal_lock_held(a, b);
4882
678
    Py_END_CRITICAL_SECTION2();
4883
4884
678
    return res;
4885
678
}
4886
4887
static PyObject *
4888
dict_richcompare(PyObject *v, PyObject *w, int op)
4889
678
{
4890
678
    int cmp;
4891
678
    PyObject *res;
4892
4893
678
    if (!PyAnyDict_Check(v) || !PyAnyDict_Check(w)) {
4894
0
        res = Py_NotImplemented;
4895
0
    }
4896
678
    else if (op == Py_EQ || op == Py_NE) {
4897
678
        cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
4898
678
        if (cmp < 0)
4899
0
            return NULL;
4900
678
        res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
4901
678
    }
4902
0
    else
4903
0
        res = Py_NotImplemented;
4904
678
    return Py_NewRef(res);
4905
678
}
4906
4907
/*[clinic input]
4908
4909
@coexist
4910
dict.__contains__
4911
4912
  key: object
4913
  /
4914
4915
True if the dictionary has the specified key, else False.
4916
[clinic start generated code]*/
4917
4918
static PyObject *
4919
dict___contains___impl(PyDictObject *self, PyObject *key)
4920
/*[clinic end generated code: output=1b314e6da7687dae input=fe1cb42ad831e820]*/
4921
651
{
4922
651
    int contains = dict_contains((PyObject *)self, key);
4923
651
    if (contains < 0) {
4924
0
        return NULL;
4925
0
    }
4926
651
    if (contains) {
4927
0
        Py_RETURN_TRUE;
4928
0
    }
4929
651
    Py_RETURN_FALSE;
4930
651
}
4931
4932
/*[clinic input]
4933
dict.get
4934
4935
    key: object
4936
    default: object = None
4937
    /
4938
4939
Return the value for key if key is in the dictionary, else default.
4940
[clinic start generated code]*/
4941
4942
static PyObject *
4943
dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
4944
/*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
4945
142M
{
4946
142M
    PyObject *val = NULL;
4947
142M
    Py_hash_t hash;
4948
142M
    Py_ssize_t ix;
4949
4950
142M
    hash = _PyObject_HashDictKey(key);
4951
142M
    if (hash == -1) {
4952
0
        dict_unhashable_type((PyObject*)self, key);
4953
0
        return NULL;
4954
0
    }
4955
142M
    ix = _Py_dict_lookup_threadsafe(self, key, hash, &val);
4956
142M
    if (ix == DKIX_ERROR)
4957
0
        return NULL;
4958
142M
    if (ix == DKIX_EMPTY || val == NULL) {
4959
121M
        val = Py_NewRef(default_value);
4960
121M
    }
4961
142M
    return val;
4962
142M
}
4963
4964
static int
4965
dict_setdefault_ref_lock_held(PyObject *d, PyObject *key, PyObject *default_value,
4966
                    PyObject **result, int incref_result)
4967
15.4M
{
4968
15.4M
    if (!PyDict_Check(d)) {
4969
0
        if (PyFrozenDict_Check(d)) {
4970
0
            frozendict_does_not_support("assignment");
4971
0
        }
4972
0
        else {
4973
0
            PyErr_BadInternalCall();
4974
0
        }
4975
0
        if (result) {
4976
0
            *result = NULL;
4977
0
        }
4978
0
        return -1;
4979
0
    }
4980
15.4M
    assert(can_modify_dict((PyDictObject*)d));
4981
4982
15.4M
    PyDictObject *mp = (PyDictObject *)d;
4983
15.4M
    PyObject *value;
4984
15.4M
    Py_hash_t hash;
4985
15.4M
    Py_ssize_t ix;
4986
4987
15.4M
    hash = _PyObject_HashDictKey(key);
4988
15.4M
    if (hash == -1) {
4989
0
        dict_unhashable_type(d, key);
4990
0
        if (result) {
4991
0
            *result = NULL;
4992
0
        }
4993
0
        return -1;
4994
0
    }
4995
4996
15.4M
    if (mp->ma_keys == Py_EMPTY_KEYS) {
4997
356k
        if (insert_to_emptydict(mp, Py_NewRef(key), hash,
4998
356k
                                Py_NewRef(default_value)) < 0) {
4999
0
            if (result) {
5000
0
                *result = NULL;
5001
0
            }
5002
0
            return -1;
5003
0
        }
5004
356k
        if (result) {
5005
355k
            *result = incref_result ? Py_NewRef(default_value) : default_value;
5006
355k
        }
5007
356k
        return 0;
5008
356k
    }
5009
5010
15.1M
    if (_PyDict_HasSplitTable(mp) && PyUnicode_CheckExact(key)) {
5011
0
        ix = insert_split_key(mp->ma_keys, key, hash);
5012
0
        if (ix != DKIX_EMPTY) {
5013
0
            PyObject *value = mp->ma_values->values[ix];
5014
0
            int already_present = value != NULL;
5015
0
            if (!already_present) {
5016
0
                _PyDict_InsertSplitValue(mp, key, default_value, ix);
5017
0
                value = default_value;
5018
0
            }
5019
0
            if (result) {
5020
0
                *result = incref_result ? Py_NewRef(value) : value;
5021
0
            }
5022
0
            return already_present;
5023
0
        }
5024
        // No space in shared keys. Go to insert_combined_dict() below.
5025
0
    }
5026
15.1M
    else {
5027
15.1M
        ix = _Py_dict_lookup(mp, key, hash, &value);
5028
15.1M
        if (ix == DKIX_ERROR) {
5029
0
            if (result) {
5030
0
                *result = NULL;
5031
0
            }
5032
0
            return -1;
5033
0
        }
5034
15.1M
    }
5035
5036
15.1M
    if (ix == DKIX_EMPTY || value == NULL) {
5037
1.31M
        value = default_value;
5038
5039
        // See comment to this function in insertdict.
5040
1.31M
        if (insert_combined_dict(mp, hash, Py_NewRef(key), Py_NewRef(value)) < 0) {
5041
0
            Py_DECREF(key);
5042
0
            Py_DECREF(value);
5043
0
            if (result) {
5044
0
                *result = NULL;
5045
0
            }
5046
0
            return -1;
5047
0
        }
5048
5049
1.31M
        STORE_USED(mp, mp->ma_used + 1);
5050
1.31M
        assert(mp->ma_keys->dk_usable >= 0);
5051
1.31M
        ASSERT_CONSISTENT(mp);
5052
1.31M
        if (result) {
5053
1.24M
            *result = incref_result ? Py_NewRef(value) : value;
5054
1.24M
        }
5055
1.31M
        return 0;
5056
1.31M
    }
5057
5058
15.1M
    assert(value != NULL);
5059
13.8M
    ASSERT_CONSISTENT(mp);
5060
13.8M
    if (result) {
5061
13.8M
        *result = incref_result ? Py_NewRef(value) : value;
5062
13.8M
    }
5063
13.8M
    return 1;
5064
15.1M
}
5065
5066
int
5067
PyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value,
5068
                     PyObject **result)
5069
9.08M
{
5070
9.08M
    int res;
5071
9.08M
    Py_BEGIN_CRITICAL_SECTION(d);
5072
9.08M
    res = dict_setdefault_ref_lock_held(d, key, default_value, result, 1);
5073
9.08M
    Py_END_CRITICAL_SECTION();
5074
9.08M
    return res;
5075
9.08M
}
5076
5077
PyObject *
5078
PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
5079
0
{
5080
0
    PyObject *result;
5081
0
    Py_BEGIN_CRITICAL_SECTION(d);
5082
0
    dict_setdefault_ref_lock_held(d, key, defaultobj, &result, 0);
5083
0
    Py_END_CRITICAL_SECTION();
5084
0
    return result;
5085
0
}
5086
5087
/*[clinic input]
5088
@critical_section
5089
dict.setdefault
5090
5091
    key: object
5092
    default: object = None
5093
    /
5094
5095
Insert key with a value of default if key is not in the dictionary.
5096
5097
Return the value for key if key is in the dictionary, else default.
5098
[clinic start generated code]*/
5099
5100
static PyObject *
5101
dict_setdefault_impl(PyDictObject *self, PyObject *key,
5102
                     PyObject *default_value)
5103
/*[clinic end generated code: output=f8c1101ebf69e220 input=9237af9a0a224302]*/
5104
6.38M
{
5105
6.38M
    PyObject *val;
5106
6.38M
    dict_setdefault_ref_lock_held((PyObject *)self, key, default_value, &val, 1);
5107
6.38M
    return val;
5108
6.38M
}
5109
5110
5111
/*[clinic input]
5112
dict.clear
5113
5114
Remove all items from the dict.
5115
[clinic start generated code]*/
5116
5117
static PyObject *
5118
dict_clear_impl(PyDictObject *self)
5119
/*[clinic end generated code: output=5139a830df00830a input=0bf729baba97a4c2]*/
5120
23.7k
{
5121
23.7k
    PyDict_Clear((PyObject *)self);
5122
23.7k
    Py_RETURN_NONE;
5123
23.7k
}
5124
5125
/*[clinic input]
5126
@permit_long_summary
5127
dict.pop
5128
5129
    key: object
5130
    default: object = NULL
5131
    /
5132
5133
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
5134
5135
If the key is not found, return the default if given; otherwise,
5136
raise a KeyError.
5137
[clinic start generated code]*/
5138
5139
static PyObject *
5140
dict_pop_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
5141
/*[clinic end generated code: output=3abb47b89f24c21c input=d409c7eb2de67e38]*/
5142
766k
{
5143
766k
    return dict_pop_default((PyObject*)self, key, default_value);
5144
766k
}
5145
5146
/*[clinic input]
5147
@critical_section
5148
dict.popitem
5149
5150
Remove and return a (key, value) pair as a 2-tuple.
5151
5152
Pairs are returned in LIFO (last-in, first-out) order.
5153
Raises KeyError if the dict is empty.
5154
[clinic start generated code]*/
5155
5156
static PyObject *
5157
dict_popitem_impl(PyDictObject *self)
5158
/*[clinic end generated code: output=e65fcb04420d230d input=ef28b4da5f0f762e]*/
5159
43.8k
{
5160
43.8k
    assert(can_modify_dict(self));
5161
5162
43.8k
    Py_ssize_t i, j;
5163
43.8k
    PyObject *res;
5164
5165
    /* Allocate the result tuple before checking the size.  Believe it
5166
     * or not, this allocation could trigger a garbage collection which
5167
     * could empty the dict, so if we checked the size first and that
5168
     * happened, the result would be an infinite loop (searching for an
5169
     * entry that no longer exists).  Note that the usual popitem()
5170
     * idiom is "while d: k, v = d.popitem()". so needing to throw the
5171
     * tuple away if the dict *is* empty isn't a significant
5172
     * inefficiency -- possible, but unlikely in practice.
5173
     */
5174
43.8k
    res = PyTuple_New(2);
5175
43.8k
    if (res == NULL)
5176
0
        return NULL;
5177
43.8k
    if (self->ma_used == 0) {
5178
21.9k
        Py_DECREF(res);
5179
21.9k
        PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
5180
21.9k
        return NULL;
5181
21.9k
    }
5182
    /* Convert split table to combined table */
5183
21.9k
    if (_PyDict_HasSplitTable(self)) {
5184
0
        if (dictresize(self, DK_LOG_SIZE(self->ma_keys), 1) < 0) {
5185
0
            Py_DECREF(res);
5186
0
            return NULL;
5187
0
        }
5188
0
    }
5189
21.9k
    FT_ATOMIC_STORE_UINT32_RELAXED(self->ma_keys->dk_version, 0);
5190
5191
    /* Pop last item */
5192
21.9k
    PyObject *key, *value;
5193
21.9k
    Py_hash_t hash;
5194
21.9k
    if (DK_IS_UNICODE(self->ma_keys)) {
5195
0
        PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(self->ma_keys);
5196
0
        i = self->ma_keys->dk_nentries - 1;
5197
0
        while (i >= 0 && ep0[i].me_value == NULL) {
5198
0
            i--;
5199
0
        }
5200
0
        assert(i >= 0);
5201
5202
0
        key = ep0[i].me_key;
5203
0
        _PyDict_NotifyEvent(PyDict_EVENT_DELETED, self, key, NULL);
5204
0
        hash = unicode_get_hash(key);
5205
0
        value = ep0[i].me_value;
5206
0
        STORE_KEY(&ep0[i], NULL);
5207
0
        STORE_VALUE(&ep0[i], NULL);
5208
0
    }
5209
21.9k
    else {
5210
21.9k
        PyDictKeyEntry *ep0 = DK_ENTRIES(self->ma_keys);
5211
21.9k
        i = self->ma_keys->dk_nentries - 1;
5212
21.9k
        while (i >= 0 && ep0[i].me_value == NULL) {
5213
0
            i--;
5214
0
        }
5215
21.9k
        assert(i >= 0);
5216
5217
21.9k
        key = ep0[i].me_key;
5218
21.9k
        _PyDict_NotifyEvent(PyDict_EVENT_DELETED, self, key, NULL);
5219
21.9k
        hash = ep0[i].me_hash;
5220
21.9k
        value = ep0[i].me_value;
5221
21.9k
        STORE_KEY(&ep0[i], NULL);
5222
21.9k
        STORE_HASH(&ep0[i], -1);
5223
21.9k
        STORE_VALUE(&ep0[i], NULL);
5224
21.9k
    }
5225
5226
21.9k
    j = lookdict_index(self->ma_keys, hash, i);
5227
21.9k
    assert(j >= 0);
5228
21.9k
    assert(dictkeys_get_index(self->ma_keys, j) == i);
5229
21.9k
    dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
5230
5231
21.9k
    PyTuple_SET_ITEM(res, 0, key);
5232
21.9k
    PyTuple_SET_ITEM(res, 1, value);
5233
    /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
5234
21.9k
    STORE_KEYS_NENTRIES(self->ma_keys, i);
5235
21.9k
    STORE_USED(self, self->ma_used - 1);
5236
21.9k
    ASSERT_CONSISTENT(self);
5237
21.9k
    return res;
5238
21.9k
}
5239
5240
static int
5241
dict_traverse(PyObject *op, visitproc visit, void *arg)
5242
91.6M
{
5243
91.6M
    PyDictObject *mp = (PyDictObject *)op;
5244
91.6M
    PyDictKeysObject *keys = mp->ma_keys;
5245
91.6M
    Py_ssize_t i, n = keys->dk_nentries;
5246
5247
91.6M
    if (DK_IS_UNICODE(keys)) {
5248
90.9M
        if (_PyDict_HasSplitTable(mp)) {
5249
7.95M
            for (i = 0; i < n; i++) {
5250
6.95M
                Py_VISIT(mp->ma_values->values[i]);
5251
6.95M
            }
5252
997k
        }
5253
89.9M
        else {
5254
89.9M
            PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(keys);
5255
296M
            for (i = 0; i < n; i++) {
5256
207M
                Py_VISIT(entries[i].me_value);
5257
207M
            }
5258
89.9M
        }
5259
90.9M
    }
5260
726k
    else {
5261
726k
        PyDictKeyEntry *entries = DK_ENTRIES(keys);
5262
105M
        for (i = 0; i < n; i++) {
5263
105M
            if (entries[i].me_value != NULL) {
5264
104M
                Py_VISIT(entries[i].me_value);
5265
104M
                Py_VISIT(entries[i].me_key);
5266
104M
            }
5267
105M
        }
5268
726k
    }
5269
91.6M
    return 0;
5270
91.6M
}
5271
5272
static int
5273
dict_tp_clear(PyObject *op)
5274
259k
{
5275
259k
    PyDict_Clear(op);
5276
259k
    return 0;
5277
259k
}
5278
5279
static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
5280
5281
Py_ssize_t
5282
_PyDict_SizeOf_LockHeld(PyDictObject *mp)
5283
0
{
5284
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(mp);
5285
5286
0
    size_t res = _PyObject_SIZE(Py_TYPE(mp));
5287
0
    if (_PyDict_HasSplitTable(mp)) {
5288
0
        res += shared_keys_usable_size(mp->ma_keys) * sizeof(PyObject*);
5289
0
    }
5290
    /* If the dictionary is split, the keys portion is accounted-for
5291
       in the type object. */
5292
0
    if (mp->ma_keys->dk_refcnt == 1) {
5293
0
        res += _PyDict_KeysSize(mp->ma_keys);
5294
0
    }
5295
0
    assert(res <= (size_t)PY_SSIZE_T_MAX);
5296
0
    return (Py_ssize_t)res;
5297
0
}
5298
5299
void
5300
_PyDict_ClearKeysVersionLockHeld(PyObject *op)
5301
0
{
5302
0
    PyDictObject *mp = _PyAnyDict_CAST(op);
5303
0
    assert(can_modify_dict(mp));
5304
5305
0
    FT_ATOMIC_STORE_UINT32_RELAXED(mp->ma_keys->dk_version, 0);
5306
0
}
5307
5308
Py_ssize_t
5309
_PyDict_SizeOf(PyDictObject *mp)
5310
0
{
5311
0
    Py_ssize_t res;
5312
0
    Py_BEGIN_CRITICAL_SECTION(mp);
5313
0
    res = _PyDict_SizeOf_LockHeld(mp);
5314
0
    Py_END_CRITICAL_SECTION();
5315
5316
0
    return res;
5317
0
}
5318
5319
size_t
5320
_PyDict_KeysSize(PyDictKeysObject *keys)
5321
3.54M
{
5322
3.54M
    size_t es = (keys->dk_kind == DICT_KEYS_GENERAL
5323
3.54M
                 ? sizeof(PyDictKeyEntry) : sizeof(PyDictUnicodeEntry));
5324
3.54M
    size_t size = sizeof(PyDictKeysObject);
5325
3.54M
    size += (size_t)1 << keys->dk_log2_index_bytes;
5326
3.54M
    size += USABLE_FRACTION((size_t)DK_SIZE(keys)) * es;
5327
3.54M
    return size;
5328
3.54M
}
5329
5330
/*[clinic input]
5331
dict.__sizeof__
5332
5333
Return the size of the dict in memory, in bytes.
5334
[clinic start generated code]*/
5335
5336
static PyObject *
5337
dict___sizeof___impl(PyDictObject *self)
5338
/*[clinic end generated code: output=44279379b3824bda input=4fec4ddfc44a4d1a]*/
5339
0
{
5340
0
    return PyLong_FromSsize_t(_PyDict_SizeOf(self));
5341
0
}
5342
5343
PyObject *
5344
_PyDict_Or(PyObject *self, PyObject *other)
5345
6
{
5346
6
    if (!PyAnyDict_Check(self) || !PyAnyDict_Check(other)) {
5347
0
        Py_RETURN_NOTIMPLEMENTED;
5348
0
    }
5349
6
    PyObject *new = anydict_copy_untracked(self);
5350
6
    if (new == NULL) {
5351
0
        return NULL;
5352
0
    }
5353
6
    if (dict_update_arg(new, other)) {
5354
0
        Py_DECREF(new);
5355
0
        return NULL;
5356
0
    }
5357
6
    _PyObject_GC_TRACK(new);
5358
6
    return new;
5359
6
}
5360
5361
static PyObject *
5362
frozendict_or(PyObject *self, PyObject *other)
5363
0
{
5364
0
    if (PyFrozenDict_CheckExact(self)) {
5365
        // frozendict() | frozendict(...) => frozendict(...)
5366
0
        if (GET_USED((PyDictObject *)self) == 0
5367
0
            && PyFrozenDict_CheckExact(other))
5368
0
        {
5369
0
            return Py_NewRef(other);
5370
0
        }
5371
5372
        // frozendict(...) | frozendict() => frozendict(...)
5373
0
        if (PyAnyDict_CheckExact(other)
5374
0
            && GET_USED((PyDictObject *)other) == 0)
5375
0
        {
5376
0
            return Py_NewRef(self);
5377
0
        }
5378
0
    }
5379
5380
0
    return _PyDict_Or(self, other);
5381
0
}
5382
5383
5384
PyObject *
5385
_PyDict_IOr(PyObject *self, PyObject *other)
5386
74
{
5387
74
    if (dict_update_arg(self, other)) {
5388
0
        return NULL;
5389
0
    }
5390
74
    return Py_NewRef(self);
5391
74
}
5392
5393
PyDoc_STRVAR(getitem__doc__,
5394
"__getitem__($self, key, /)\n--\n\nReturn self[key].");
5395
5396
PyDoc_STRVAR(update__doc__,
5397
"D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.\n\
5398
If E is present and has a .keys() method, then does:  for k in E.keys(): D[k] = E[k]\n\
5399
If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v\n\
5400
In either case, this is followed by: for k in F:  D[k] = F[k]");
5401
5402
/* Forward */
5403
5404
static PyMethodDef mapp_methods[] = {
5405
    DICT___CONTAINS___METHODDEF
5406
    {"__getitem__",     _PyDict_Subscript,                 METH_O | METH_COEXIST,
5407
     getitem__doc__},
5408
    DICT___SIZEOF___METHODDEF
5409
    DICT_GET_METHODDEF
5410
    DICT_SETDEFAULT_METHODDEF
5411
    DICT_POP_METHODDEF
5412
    DICT_POPITEM_METHODDEF
5413
    DICT_KEYS_METHODDEF
5414
    DICT_ITEMS_METHODDEF
5415
    DICT_VALUES_METHODDEF
5416
    {"update",          _PyCFunction_CAST(dict_update), METH_VARARGS | METH_KEYWORDS,
5417
     update__doc__},
5418
    DICT_FROMKEYS_METHODDEF
5419
    DICT_CLEAR_METHODDEF
5420
    DICT_COPY_METHODDEF
5421
    DICT___REVERSED___METHODDEF
5422
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
5423
     PyDoc_STR("dicts are generic over two types, signifying (respectively) the types of their keys and values")},
5424
    {NULL,              NULL}   /* sentinel */
5425
};
5426
5427
static int
5428
dict_contains(PyObject *op, PyObject *key)
5429
780M
{
5430
780M
    Py_hash_t hash = _PyObject_HashDictKey(key);
5431
780M
    if (hash == -1) {
5432
0
        dict_unhashable_type(op, key);
5433
0
        return -1;
5434
0
    }
5435
5436
780M
    return _PyDict_Contains_KnownHash(op, key, hash);
5437
780M
}
5438
5439
/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
5440
int
5441
PyDict_Contains(PyObject *op, PyObject *key)
5442
780M
{
5443
780M
    if (!PyAnyDict_Check(op)) {
5444
0
        PyErr_BadInternalCall();
5445
0
        return -1;
5446
0
    }
5447
5448
780M
    return dict_contains(op, key);
5449
780M
}
5450
5451
int
5452
PyDict_ContainsString(PyObject *op, const char *key)
5453
2.40k
{
5454
2.40k
    PyObject *key_obj = PyUnicode_FromString(key);
5455
2.40k
    if (key_obj == NULL) {
5456
0
        return -1;
5457
0
    }
5458
2.40k
    int res = PyDict_Contains(op, key_obj);
5459
2.40k
    Py_DECREF(key_obj);
5460
2.40k
    return res;
5461
2.40k
}
5462
5463
/* Internal version of PyDict_Contains used when the hash value is already known */
5464
int
5465
_PyDict_Contains_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
5466
780M
{
5467
780M
    PyDictObject *mp = _PyAnyDict_CAST(op);
5468
780M
    PyObject *value;
5469
780M
    Py_ssize_t ix;
5470
5471
#ifdef Py_GIL_DISABLED
5472
    ix = _Py_dict_lookup_threadsafe(mp, key, hash, &value);
5473
#else
5474
780M
    ix = _Py_dict_lookup(mp, key, hash, &value);
5475
780M
#endif
5476
780M
    if (ix == DKIX_ERROR)
5477
0
        return -1;
5478
780M
    if (ix != DKIX_EMPTY && value != NULL) {
5479
#ifdef Py_GIL_DISABLED
5480
        Py_DECREF(value);
5481
#endif
5482
689M
        return 1;
5483
689M
    }
5484
91.8M
    return 0;
5485
780M
}
5486
5487
/* Hack to implement "key in dict" */
5488
static PySequenceMethods dict_as_sequence = {
5489
    0,                          /* sq_length */
5490
    0,                          /* sq_concat */
5491
    0,                          /* sq_repeat */
5492
    0,                          /* sq_item */
5493
    0,                          /* sq_slice */
5494
    0,                          /* sq_ass_item */
5495
    0,                          /* sq_ass_slice */
5496
    dict_contains,              /* sq_contains */
5497
    0,                          /* sq_inplace_concat */
5498
    0,                          /* sq_inplace_repeat */
5499
};
5500
5501
static PyNumberMethods dict_as_number = {
5502
    .nb_or = _PyDict_Or,
5503
    .nb_inplace_or = _PyDict_IOr,
5504
};
5505
5506
static PyObject*
5507
anydict_new_untracked(PyTypeObject *type)
5508
1.01M
{
5509
1.01M
    assert(type != NULL);
5510
    // dict and frozendict subclasses must implement the GC protocol
5511
1.01M
    assert(_PyType_IS_GC(type));
5512
5513
1.01M
    PyObject *self = _PyType_AllocNoTrack(type, 0);
5514
1.01M
    if (self == NULL) {
5515
0
        return NULL;
5516
0
    }
5517
1.01M
    PyDictObject *d = (PyDictObject *)self;
5518
5519
1.01M
    d->ma_used = 0;
5520
1.01M
    d->_ma_watcher_tag = 0;
5521
    // We don't inc ref empty keys because they're immortal
5522
1.01M
    assert((Py_EMPTY_KEYS)->dk_refcnt == _Py_DICT_IMMORTAL_INITIAL_REFCNT);
5523
1.01M
    d->ma_keys = Py_EMPTY_KEYS;
5524
1.01M
    d->ma_values = NULL;
5525
1.01M
    ASSERT_CONSISTENT(d);
5526
1.01M
    return self;
5527
1.01M
}
5528
5529
static PyObject*
5530
dict_new_untracked(PyTypeObject *type)
5531
1.01M
{
5532
1.01M
    assert(PyObject_IsSubclass((PyObject*)type, (PyObject*)&PyDict_Type));
5533
5534
1.01M
    return anydict_new_untracked(type);
5535
1.01M
}
5536
5537
static PyObject *
5538
dict_new(PyTypeObject *type, PyObject *Py_UNUSED(args), PyObject *Py_UNUSED(kwds))
5539
166k
{
5540
    /* tp_new ignores args/kwds; args/kwds are consumed by dict_init (tp_init). */
5541
166k
    PyObject *self = dict_new_untracked(type);
5542
166k
    if (self == NULL) {
5543
0
        return NULL;
5544
0
    }
5545
166k
    _PyObject_GC_TRACK(self);
5546
166k
    return self;
5547
166k
}
5548
5549
static int
5550
dict_init(PyObject *self, PyObject *args, PyObject *kwds)
5551
165k
{
5552
165k
    return dict_update_common(self, args, kwds, "dict");
5553
165k
}
5554
5555
static PyObject *
5556
dict_vectorcall(PyObject *type, PyObject * const*args,
5557
                size_t nargsf, PyObject *kwnames)
5558
1.21M
{
5559
1.21M
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
5560
1.21M
    if (!_PyArg_CheckPositional("dict", nargs, 0, 1)) {
5561
0
        return NULL;
5562
0
    }
5563
5564
1.21M
    assert(type == (PyObject *)&PyDict_Type);
5565
1.21M
    PyObject *self = PyDict_New();
5566
1.21M
    if (self == NULL) {
5567
0
        return NULL;
5568
0
    }
5569
1.21M
    if (nargs == 1) {
5570
4.28k
        if (dict_update_arg(self, args[0]) < 0) {
5571
0
            Py_DECREF(self);
5572
0
            return NULL;
5573
0
        }
5574
4.28k
        args++;
5575
4.28k
    }
5576
1.21M
    if (kwnames != NULL) {
5577
100k
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwnames); i++) {
5578
78.9k
            PyObject *key = PyTuple_GET_ITEM(kwnames, i);  // borrowed
5579
78.9k
            if (PyDict_SetItem(self, key, args[i]) < 0) {
5580
0
                Py_DECREF(self);
5581
0
                return NULL;
5582
0
            }
5583
78.9k
        }
5584
21.5k
    }
5585
1.21M
    return self;
5586
1.21M
}
5587
5588
static PyObject *
5589
frozendict_vectorcall(PyObject *type, PyObject * const*args,
5590
                      size_t nargsf, PyObject *kwnames)
5591
233
{
5592
233
    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
5593
233
    if (!_PyArg_CheckPositional("frozendict", nargs, 0, 1)) {
5594
0
        return NULL;
5595
0
    }
5596
5597
233
    if (nargs == 1 && kwnames == NULL
5598
233
        && PyFrozenDict_CheckExact(args[0])
5599
0
        && Py_Is((PyTypeObject*)type, &PyFrozenDict_Type))
5600
0
    {
5601
        // frozendict(frozendict) returns the same object unmodified
5602
0
        return Py_NewRef(args[0]);
5603
0
    }
5604
5605
    /* gh-151722: Keep the frozendict untracked until it is fully built,
5606
       so a half-built object is never reachable from another thread (using the gc module). */
5607
233
    PyObject *self = frozendict_new_untracked(_PyType_CAST(type));
5608
233
    if (self == NULL) {
5609
0
        return NULL;
5610
0
    }
5611
233
    if (nargs == 1) {
5612
68
        if (dict_update_arg(self, args[0]) < 0) {
5613
0
            Py_DECREF(self);
5614
0
            return NULL;
5615
0
        }
5616
68
        args++;
5617
68
    }
5618
233
    if (kwnames != NULL) {
5619
2.06k
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwnames); i++) {
5620
1.90k
            PyObject *key = PyTuple_GET_ITEM(kwnames, i);  // borrowed
5621
1.90k
            if (_PyAnyDict_SetItem(self, key, args[i]) < 0) {
5622
0
                Py_DECREF(self);
5623
0
                return NULL;
5624
0
            }
5625
1.90k
        }
5626
160
    }
5627
5628
233
    _PyObject_GC_TRACK(self);
5629
233
    return self;
5630
233
}
5631
5632
static PyObject *
5633
dict_iter(PyObject *self)
5634
158k
{
5635
158k
    PyDictObject *dict = (PyDictObject *)self;
5636
158k
    return dictiter_new(dict, &PyDictIterKey_Type);
5637
158k
}
5638
5639
PyDoc_STRVAR(dictionary_doc,
5640
"dict() -> new empty dictionary\n"
5641
"dict(mapping) -> new dictionary initialized from a mapping object's\n"
5642
"    (key, value) pairs\n"
5643
"dict(iterable) -> new dictionary initialized as if via:\n"
5644
"    d = {}\n"
5645
"    for k, v in iterable:\n"
5646
"        d[k] = v\n"
5647
"dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
5648
"    in the keyword argument list.  For example:  dict(one=1, two=2)");
5649
5650
PyTypeObject PyDict_Type = {
5651
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
5652
    "dict",
5653
    sizeof(PyDictObject),
5654
    0,
5655
    dict_dealloc,                               /* tp_dealloc */
5656
    0,                                          /* tp_vectorcall_offset */
5657
    0,                                          /* tp_getattr */
5658
    0,                                          /* tp_setattr */
5659
    0,                                          /* tp_as_async */
5660
    dict_repr,                                  /* tp_repr */
5661
    &dict_as_number,                            /* tp_as_number */
5662
    &dict_as_sequence,                          /* tp_as_sequence */
5663
    &dict_as_mapping,                           /* tp_as_mapping */
5664
    PyObject_HashNotImplemented,                /* tp_hash */
5665
    0,                                          /* tp_call */
5666
    0,                                          /* tp_str */
5667
    PyObject_GenericGetAttr,                    /* tp_getattro */
5668
    0,                                          /* tp_setattro */
5669
    0,                                          /* tp_as_buffer */
5670
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5671
        Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS |
5672
        _Py_TPFLAGS_MATCH_SELF | Py_TPFLAGS_MAPPING,  /* tp_flags */
5673
    dictionary_doc,                             /* tp_doc */
5674
    dict_traverse,                              /* tp_traverse */
5675
    dict_tp_clear,                              /* tp_clear */
5676
    dict_richcompare,                           /* tp_richcompare */
5677
    0,                                          /* tp_weaklistoffset */
5678
    dict_iter,                                  /* tp_iter */
5679
    0,                                          /* tp_iternext */
5680
    mapp_methods,                               /* tp_methods */
5681
    0,                                          /* tp_members */
5682
    0,                                          /* tp_getset */
5683
    0,                                          /* tp_base */
5684
    0,                                          /* tp_dict */
5685
    0,                                          /* tp_descr_get */
5686
    0,                                          /* tp_descr_set */
5687
    0,                                          /* tp_dictoffset */
5688
    dict_init,                                  /* tp_init */
5689
    _PyType_AllocNoTrack,                       /* tp_alloc */
5690
    dict_new,                                   /* tp_new */
5691
    PyObject_GC_Del,                            /* tp_free */
5692
    .tp_vectorcall = dict_vectorcall,
5693
    .tp_version_tag = _Py_TYPE_VERSION_DICT,
5694
};
5695
5696
5697
/* For backward compatibility with old dictionary interface */
5698
5699
PyObject *
5700
PyDict_GetItemString(PyObject *v, const char *key)
5701
0
{
5702
0
    PyObject *kv, *rv;
5703
0
    kv = PyUnicode_FromString(key);
5704
0
    if (kv == NULL) {
5705
0
        PyErr_FormatUnraisable(
5706
0
            "Exception ignored in PyDict_GetItemString(); consider using "
5707
0
            "PyDict_GetItemStringRef()");
5708
0
        return NULL;
5709
0
    }
5710
0
    rv = dict_getitem(v, kv,
5711
0
            "Exception ignored in PyDict_GetItemString(); consider using "
5712
0
            "PyDict_GetItemStringRef()");
5713
0
    Py_DECREF(kv);
5714
0
    return rv;  // borrowed reference
5715
0
}
5716
5717
int
5718
PyDict_GetItemStringRef(PyObject *v, const char *key, PyObject **result)
5719
2.76M
{
5720
2.76M
    PyObject *key_obj = PyUnicode_FromString(key);
5721
2.76M
    if (key_obj == NULL) {
5722
0
        *result = NULL;
5723
0
        return -1;
5724
0
    }
5725
2.76M
    int res = PyDict_GetItemRef(v, key_obj, result);
5726
2.76M
    Py_DECREF(key_obj);
5727
2.76M
    return res;
5728
2.76M
}
5729
5730
int
5731
PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
5732
41.7k
{
5733
41.7k
    PyObject *kv;
5734
41.7k
    int err;
5735
41.7k
    kv = PyUnicode_FromString(key);
5736
41.7k
    if (kv == NULL)
5737
0
        return -1;
5738
41.7k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5739
41.7k
    _PyUnicode_InternImmortal(interp, &kv); /* XXX Should we really? */
5740
41.7k
    err = PyDict_SetItem(v, kv, item);
5741
41.7k
    Py_DECREF(kv);
5742
41.7k
    return err;
5743
41.7k
}
5744
5745
int
5746
PyDict_DelItemString(PyObject *v, const char *key)
5747
0
{
5748
0
    PyObject *kv;
5749
0
    int err;
5750
0
    kv = PyUnicode_FromString(key);
5751
0
    if (kv == NULL)
5752
0
        return -1;
5753
0
    err = PyDict_DelItem(v, kv);
5754
0
    Py_DECREF(kv);
5755
0
    return err;
5756
0
}
5757
5758
/* Dictionary iterator types */
5759
5760
typedef struct {
5761
    PyObject_HEAD
5762
    /* Set to NULL when the iterator is exhausted, except in the free-threaded
5763
       build, where the reference is kept until the iterator is deallocated
5764
       (see dictiter_set_exhausted()). */
5765
    PyDictObject *di_dict;
5766
    Py_ssize_t di_used;
5767
    Py_ssize_t di_pos;
5768
    PyObject* di_result; /* reusable result tuple for iteritems */
5769
    Py_ssize_t len;
5770
} dictiterobject;
5771
5772
static PyObject *
5773
dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
5774
1.98M
{
5775
1.98M
    Py_ssize_t used;
5776
1.98M
    dictiterobject *di;
5777
1.98M
    di = PyObject_GC_New(dictiterobject, itertype);
5778
1.98M
    if (di == NULL) {
5779
0
        return NULL;
5780
0
    }
5781
1.98M
    di->di_dict = (PyDictObject*)Py_NewRef(dict);
5782
1.98M
    used = GET_USED(dict);
5783
1.98M
    di->di_used = used;
5784
1.98M
    di->len = used;
5785
1.98M
    di->di_result = NULL;
5786
1.98M
    if (itertype == &PyDictRevIterKey_Type ||
5787
1.98M
         itertype == &PyDictRevIterItem_Type ||
5788
1.98M
         itertype == &PyDictRevIterValue_Type) {
5789
0
        if (_PyDict_HasSplitTable(dict)) {
5790
0
            di->di_pos = used - 1;
5791
0
        }
5792
0
        else {
5793
0
            di->di_pos = load_keys_nentries(dict) - 1;
5794
0
        }
5795
0
    }
5796
1.98M
    else {
5797
1.98M
        di->di_pos = 0;
5798
1.98M
    }
5799
    /* gh-152107: track before allocating di_result. A dictiter with a NULL
5800
       di_result is a valid state for dictiter_traverse()/dictiter_dealloc(),
5801
       so a failure of the allocation below can safely DECREF a tracked di. */
5802
1.98M
    _PyObject_GC_TRACK(di);
5803
1.98M
    if (itertype == &PyDictIterItem_Type ||
5804
1.59M
        itertype == &PyDictRevIterItem_Type) {
5805
1.59M
        di->di_result = _PyTuple_FromPairSteal(Py_None, Py_None);
5806
1.59M
        if (di->di_result == NULL) {
5807
0
            Py_DECREF(di);
5808
0
            return NULL;
5809
0
        }
5810
1.59M
    }
5811
1.98M
    return (PyObject *)di;
5812
1.98M
}
5813
5814
static void
5815
dictiter_dealloc(PyObject *self)
5816
1.98M
{
5817
1.98M
    dictiterobject *di = (dictiterobject *)self;
5818
    /* bpo-31095: UnTrack is needed before calling any callbacks */
5819
1.98M
    _PyObject_GC_UNTRACK(di);
5820
1.98M
    Py_XDECREF(di->di_dict);
5821
1.98M
    Py_XDECREF(di->di_result);
5822
1.98M
    PyObject_GC_Del(di);
5823
1.98M
}
5824
5825
static int
5826
dictiter_traverse(PyObject *self, visitproc visit, void *arg)
5827
5.38k
{
5828
5.38k
    dictiterobject *di = (dictiterobject *)self;
5829
5.38k
    Py_VISIT(di->di_dict);
5830
5.38k
    Py_VISIT(di->di_result);
5831
5.38k
    return 0;
5832
5.38k
}
5833
5834
static PyObject *
5835
dictiter_len(PyObject *self, PyObject *Py_UNUSED(ignored))
5836
75.4k
{
5837
75.4k
    dictiterobject *di = (dictiterobject *)self;
5838
75.4k
    Py_ssize_t len = 0;
5839
75.4k
    if (di->di_dict != NULL && di->di_used == GET_USED(di->di_dict))
5840
75.4k
        len = FT_ATOMIC_LOAD_SSIZE_RELAXED(di->len);
5841
75.4k
    return PyLong_FromSize_t(len);
5842
75.4k
}
5843
5844
PyDoc_STRVAR(length_hint_doc,
5845
             "Private method returning an estimate of len(list(it)).");
5846
5847
static PyObject *
5848
dictiter_reduce(PyObject *di, PyObject *Py_UNUSED(ignored));
5849
5850
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
5851
5852
static PyMethodDef dictiter_methods[] = {
5853
    {"__length_hint__", dictiter_len,                   METH_NOARGS,
5854
     length_hint_doc},
5855
     {"__reduce__",     dictiter_reduce,                METH_NOARGS,
5856
     reduce_doc},
5857
    {NULL,              NULL}           /* sentinel */
5858
};
5859
5860
/* Mark the iterator as exhausted.  In the free-threaded build an iterator
5861
   may be advanced by several threads at once, each holding a borrowed
5862
   pointer to di_dict, so the iterator keeps its reference to the dict until
5863
   it is deallocated (as list and tuple iterators do) and records exhaustion
5864
   by setting di_pos to DICTITER_EXHAUSTED.  This is distinct from -1, the
5865
   starting position of a reverse iterator over an empty dict. */
5866
#ifdef Py_GIL_DISABLED
5867
#define DICTITER_EXHAUSTED PY_SSIZE_T_MIN
5868
#endif
5869
5870
static void
5871
dictiter_set_exhausted(dictiterobject *di, PyDictObject *d)
5872
1.59M
{
5873
#ifdef Py_GIL_DISABLED
5874
    _Py_atomic_store_ssize_relaxed(&di->di_pos, DICTITER_EXHAUSTED);
5875
    _Py_atomic_store_ssize_relaxed(&di->len, 0);
5876
#else
5877
1.59M
    di->di_dict = NULL;
5878
1.59M
    Py_DECREF(d);
5879
1.59M
#endif
5880
1.59M
}
5881
5882
#ifdef Py_GIL_DISABLED
5883
5884
static int
5885
dictiter_iternext_threadsafe(PyDictObject *d, PyObject *self,
5886
                             PyObject **out_key, PyObject **out_value);
5887
5888
#else /* Py_GIL_DISABLED */
5889
5890
static PyObject*
5891
dictiter_iternextkey_lock_held(PyDictObject *d, PyObject *self)
5892
1.98M
{
5893
1.98M
    dictiterobject *di = (dictiterobject *)self;
5894
1.98M
    PyObject *key;
5895
1.98M
    Py_ssize_t i;
5896
1.98M
    PyDictKeysObject *k;
5897
5898
1.98M
    assert (PyAnyDict_Check(d));
5899
1.98M
    ASSERT_DICT_LOCKED(d);
5900
5901
1.98M
    if (di->di_used != d->ma_used) {
5902
0
        PyErr_SetString(PyExc_RuntimeError,
5903
0
                        "dictionary changed size during iteration");
5904
0
        di->di_used = -1; /* Make this state sticky */
5905
0
        return NULL;
5906
0
    }
5907
5908
1.98M
    i = di->di_pos;
5909
1.98M
    k = d->ma_keys;
5910
1.98M
    assert(i >= 0);
5911
1.98M
    if (_PyDict_HasSplitTable(d)) {
5912
0
        if (i >= d->ma_used)
5913
0
            goto fail;
5914
0
        int index = get_index_from_order(d, i);
5915
0
        key = LOAD_SHARED_KEY(DK_UNICODE_ENTRIES(k)[index].me_key);
5916
0
        assert(d->ma_values->values[index] != NULL);
5917
0
    }
5918
1.98M
    else {
5919
1.98M
        Py_ssize_t n = k->dk_nentries;
5920
1.98M
        if (DK_IS_UNICODE(k)) {
5921
1.98M
            PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(k)[i];
5922
2.04M
            while (i < n && entry_ptr->me_value == NULL) {
5923
60.9k
                entry_ptr++;
5924
60.9k
                i++;
5925
60.9k
            }
5926
1.98M
            if (i >= n)
5927
284k
                goto fail;
5928
1.69M
            key = entry_ptr->me_key;
5929
1.69M
        }
5930
742
        else {
5931
742
            PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
5932
742
            while (i < n && entry_ptr->me_value == NULL) {
5933
0
                entry_ptr++;
5934
0
                i++;
5935
0
            }
5936
742
            if (i >= n)
5937
132
                goto fail;
5938
610
            key = entry_ptr->me_key;
5939
610
        }
5940
1.98M
    }
5941
    // We found an element (key), but did not expect it
5942
1.69M
    if (di->len == 0) {
5943
0
        PyErr_SetString(PyExc_RuntimeError,
5944
0
                        "dictionary keys changed during iteration");
5945
0
        goto fail;
5946
0
    }
5947
1.69M
    di->di_pos = i+1;
5948
1.69M
    di->len--;
5949
1.69M
    return Py_NewRef(key);
5950
5951
284k
fail:
5952
284k
    di->di_dict = NULL;
5953
284k
    Py_DECREF(d);
5954
284k
    return NULL;
5955
1.69M
}
5956
5957
#endif  /* Py_GIL_DISABLED */
5958
5959
static PyObject*
5960
dictiter_iternextkey(PyObject *self)
5961
1.98M
{
5962
1.98M
    dictiterobject *di = (dictiterobject *)self;
5963
1.98M
    PyDictObject *d = di->di_dict;
5964
5965
1.98M
    if (d == NULL)
5966
0
        return NULL;
5967
5968
1.98M
    PyObject *value;
5969
#ifdef Py_GIL_DISABLED
5970
    if (dictiter_iternext_threadsafe(d, self, &value, NULL) < 0) {
5971
        value = NULL;
5972
    }
5973
#else
5974
1.98M
    value = dictiter_iternextkey_lock_held(d, self);
5975
1.98M
#endif
5976
5977
1.98M
    return value;
5978
1.98M
}
5979
5980
PyTypeObject PyDictIterKey_Type = {
5981
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
5982
    "dict_keyiterator",                         /* tp_name */
5983
    sizeof(dictiterobject),                     /* tp_basicsize */
5984
    0,                                          /* tp_itemsize */
5985
    /* methods */
5986
    dictiter_dealloc,                           /* tp_dealloc */
5987
    0,                                          /* tp_vectorcall_offset */
5988
    0,                                          /* tp_getattr */
5989
    0,                                          /* tp_setattr */
5990
    0,                                          /* tp_as_async */
5991
    0,                                          /* tp_repr */
5992
    0,                                          /* tp_as_number */
5993
    0,                                          /* tp_as_sequence */
5994
    0,                                          /* tp_as_mapping */
5995
    0,                                          /* tp_hash */
5996
    0,                                          /* tp_call */
5997
    0,                                          /* tp_str */
5998
    PyObject_GenericGetAttr,                    /* tp_getattro */
5999
    0,                                          /* tp_setattro */
6000
    0,                                          /* tp_as_buffer */
6001
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
6002
    0,                                          /* tp_doc */
6003
    dictiter_traverse,                          /* tp_traverse */
6004
    0,                                          /* tp_clear */
6005
    0,                                          /* tp_richcompare */
6006
    0,                                          /* tp_weaklistoffset */
6007
    PyObject_SelfIter,                          /* tp_iter */
6008
    dictiter_iternextkey,                       /* tp_iternext */
6009
    dictiter_methods,                           /* tp_methods */
6010
    0,
6011
};
6012
6013
#ifndef Py_GIL_DISABLED
6014
6015
static PyObject *
6016
dictiter_iternextvalue_lock_held(PyDictObject *d, PyObject *self)
6017
479k
{
6018
479k
    dictiterobject *di = (dictiterobject *)self;
6019
479k
    PyObject *value;
6020
479k
    Py_ssize_t i;
6021
6022
479k
    assert (PyAnyDict_Check(d));
6023
479k
    ASSERT_DICT_LOCKED(d);
6024
6025
479k
    if (di->di_used != d->ma_used) {
6026
0
        PyErr_SetString(PyExc_RuntimeError,
6027
0
                        "dictionary changed size during iteration");
6028
0
        di->di_used = -1; /* Make this state sticky */
6029
0
        return NULL;
6030
0
    }
6031
6032
479k
    i = di->di_pos;
6033
479k
    assert(i >= 0);
6034
479k
    if (_PyDict_HasSplitTable(d)) {
6035
0
        if (i >= d->ma_used)
6036
0
            goto fail;
6037
0
        int index = get_index_from_order(d, i);
6038
0
        value = d->ma_values->values[index];
6039
0
        assert(value != NULL);
6040
0
    }
6041
479k
    else {
6042
479k
        Py_ssize_t n = d->ma_keys->dk_nentries;
6043
479k
        if (DK_IS_UNICODE(d->ma_keys)) {
6044
12.1k
            PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(d->ma_keys)[i];
6045
12.2k
            while (i < n && entry_ptr->me_value == NULL) {
6046
88
                entry_ptr++;
6047
88
                i++;
6048
88
            }
6049
12.1k
            if (i >= n)
6050
763
                goto fail;
6051
11.3k
            value = entry_ptr->me_value;
6052
11.3k
        }
6053
467k
        else {
6054
467k
            PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
6055
467k
            while (i < n && entry_ptr->me_value == NULL) {
6056
0
                entry_ptr++;
6057
0
                i++;
6058
0
            }
6059
467k
            if (i >= n)
6060
90.1k
                goto fail;
6061
377k
            value = entry_ptr->me_value;
6062
377k
        }
6063
479k
    }
6064
    // We found an element, but did not expect it
6065
388k
    if (di->len == 0) {
6066
0
        PyErr_SetString(PyExc_RuntimeError,
6067
0
                        "dictionary keys changed during iteration");
6068
0
        goto fail;
6069
0
    }
6070
388k
    di->di_pos = i+1;
6071
388k
    di->len--;
6072
388k
    return Py_NewRef(value);
6073
6074
90.8k
fail:
6075
90.8k
    di->di_dict = NULL;
6076
90.8k
    Py_DECREF(d);
6077
90.8k
    return NULL;
6078
388k
}
6079
6080
#endif  /* Py_GIL_DISABLED */
6081
6082
static PyObject *
6083
dictiter_iternextvalue(PyObject *self)
6084
479k
{
6085
479k
    dictiterobject *di = (dictiterobject *)self;
6086
479k
    PyDictObject *d = di->di_dict;
6087
6088
479k
    if (d == NULL)
6089
0
        return NULL;
6090
6091
479k
    PyObject *value;
6092
#ifdef Py_GIL_DISABLED
6093
    if (dictiter_iternext_threadsafe(d, self, NULL, &value) < 0) {
6094
        value = NULL;
6095
    }
6096
#else
6097
479k
    value = dictiter_iternextvalue_lock_held(d, self);
6098
479k
#endif
6099
6100
479k
    return value;
6101
479k
}
6102
6103
PyTypeObject PyDictIterValue_Type = {
6104
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
6105
    "dict_valueiterator",                       /* tp_name */
6106
    sizeof(dictiterobject),                     /* tp_basicsize */
6107
    0,                                          /* tp_itemsize */
6108
    /* methods */
6109
    dictiter_dealloc,                           /* tp_dealloc */
6110
    0,                                          /* tp_vectorcall_offset */
6111
    0,                                          /* tp_getattr */
6112
    0,                                          /* tp_setattr */
6113
    0,                                          /* tp_as_async */
6114
    0,                                          /* tp_repr */
6115
    0,                                          /* tp_as_number */
6116
    0,                                          /* tp_as_sequence */
6117
    0,                                          /* tp_as_mapping */
6118
    0,                                          /* tp_hash */
6119
    0,                                          /* tp_call */
6120
    0,                                          /* tp_str */
6121
    PyObject_GenericGetAttr,                    /* tp_getattro */
6122
    0,                                          /* tp_setattro */
6123
    0,                                          /* tp_as_buffer */
6124
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
6125
    0,                                          /* tp_doc */
6126
    dictiter_traverse,                          /* tp_traverse */
6127
    0,                                          /* tp_clear */
6128
    0,                                          /* tp_richcompare */
6129
    0,                                          /* tp_weaklistoffset */
6130
    PyObject_SelfIter,                          /* tp_iter */
6131
    dictiter_iternextvalue,                     /* tp_iternext */
6132
    dictiter_methods,                           /* tp_methods */
6133
    0,
6134
};
6135
6136
static int
6137
dictiter_iternextitem_lock_held(PyDictObject *d, PyObject *self,
6138
                                PyObject **out_key, PyObject **out_value)
6139
4.80M
{
6140
4.80M
    dictiterobject *di = (dictiterobject *)self;
6141
4.80M
    PyObject *key, *value;
6142
4.80M
    Py_ssize_t i;
6143
6144
4.80M
    assert (PyAnyDict_Check(d));
6145
4.80M
    ASSERT_DICT_LOCKED(d);
6146
6147
4.80M
    i = FT_ATOMIC_LOAD_SSIZE_RELAXED(di->di_pos);
6148
4.80M
    if (i < 0) {
6149
0
        return -1;  /* exhausted */
6150
0
    }
6151
6152
4.80M
    if (di->di_used != d->ma_used) {
6153
0
        PyErr_SetString(PyExc_RuntimeError,
6154
0
                        "dictionary changed size during iteration");
6155
0
        di->di_used = -1; /* Make this state sticky */
6156
0
        return -1;
6157
0
    }
6158
6159
4.80M
    if (_PyDict_HasSplitTable(d)) {
6160
10
        if (i >= d->ma_used)
6161
8
            goto fail;
6162
2
        int index = get_index_from_order(d, i);
6163
2
        key = LOAD_SHARED_KEY(DK_UNICODE_ENTRIES(d->ma_keys)[index].me_key);
6164
2
        value = d->ma_values->values[index];
6165
2
        assert(value != NULL);
6166
2
    }
6167
4.80M
    else {
6168
4.80M
        Py_ssize_t n = d->ma_keys->dk_nentries;
6169
4.80M
        if (DK_IS_UNICODE(d->ma_keys)) {
6170
4.48M
            PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(d->ma_keys)[i];
6171
4.49M
            while (i < n && entry_ptr->me_value == NULL) {
6172
5.44k
                entry_ptr++;
6173
5.44k
                i++;
6174
5.44k
            }
6175
4.48M
            if (i >= n)
6176
1.42M
                goto fail;
6177
3.05M
            key = entry_ptr->me_key;
6178
3.05M
            value = entry_ptr->me_value;
6179
3.05M
        }
6180
322k
        else {
6181
322k
            PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
6182
322k
            while (i < n && entry_ptr->me_value == NULL) {
6183
0
                entry_ptr++;
6184
0
                i++;
6185
0
            }
6186
322k
            if (i >= n)
6187
161k
                goto fail;
6188
161k
            key = entry_ptr->me_key;
6189
161k
            value = entry_ptr->me_value;
6190
161k
        }
6191
4.80M
    }
6192
    // We found an element, but did not expect it
6193
3.21M
    if (di->len == 0) {
6194
0
        PyErr_SetString(PyExc_RuntimeError,
6195
0
                        "dictionary keys changed during iteration");
6196
0
        goto fail;
6197
0
    }
6198
3.21M
    di->di_pos = i+1;
6199
3.21M
    di->len--;
6200
3.21M
    if (out_key != NULL) {
6201
3.21M
        *out_key = Py_NewRef(key);
6202
3.21M
    }
6203
3.21M
    if (out_value != NULL) {
6204
3.21M
        *out_value = Py_NewRef(value);
6205
3.21M
    }
6206
3.21M
    return 0;
6207
6208
1.59M
fail:
6209
1.59M
    dictiter_set_exhausted(di, d);
6210
1.59M
    return -1;
6211
3.21M
}
6212
6213
#ifdef Py_GIL_DISABLED
6214
6215
// Grabs the key and/or value from the provided locations and if successful
6216
// returns them with an increased reference count.  If either one is unsuccessful
6217
// nothing is incref'd and returns -1.
6218
static int
6219
acquire_key_value(PyObject **key_loc, PyObject *value, PyObject **value_loc,
6220
                  PyObject **out_key, PyObject **out_value)
6221
{
6222
    if (out_key) {
6223
        *out_key = _Py_TryXGetRef(key_loc);
6224
        if (*out_key == NULL) {
6225
            return -1;
6226
        }
6227
    }
6228
6229
    if (out_value) {
6230
        if (!_Py_TryIncrefCompare(value_loc, value)) {
6231
            if (out_key) {
6232
                Py_DECREF(*out_key);
6233
            }
6234
            return -1;
6235
        }
6236
        *out_value = value;
6237
    }
6238
6239
    return 0;
6240
}
6241
6242
static int
6243
dictiter_iternext_threadsafe(PyDictObject *d, PyObject *self,
6244
                             PyObject **out_key, PyObject **out_value)
6245
{
6246
    int res;
6247
    dictiterobject *di = (dictiterobject *)self;
6248
    Py_ssize_t i;
6249
    PyDictKeysObject *k;
6250
6251
    assert (PyAnyDict_Check(d));
6252
6253
    i = _Py_atomic_load_ssize_relaxed(&di->di_pos);
6254
    if (i == DICTITER_EXHAUSTED) {
6255
        return -1;
6256
    }
6257
6258
    if (di->di_used != _Py_atomic_load_ssize_relaxed(&d->ma_used)) {
6259
        PyErr_SetString(PyExc_RuntimeError,
6260
                        "dictionary changed size during iteration");
6261
        di->di_used = -1; /* Make this state sticky */
6262
        return -1;
6263
    }
6264
6265
    ensure_shared_on_read(d);
6266
6267
    k = _Py_atomic_load_ptr_acquire(&d->ma_keys);
6268
    if (_PyDict_HasSplitTable(d)) {
6269
        PyDictValues *values = _Py_atomic_load_ptr_consume(&d->ma_values);
6270
        if (values == NULL) {
6271
            goto concurrent_modification;
6272
        }
6273
6274
        Py_ssize_t used = (Py_ssize_t)_Py_atomic_load_uint8(&values->size);
6275
        if (i >= used) {
6276
            goto fail;
6277
        }
6278
6279
        // We're racing against writes to the order from delete_index_from_values, but
6280
        // single threaded can suffer from concurrent modification to those as well and
6281
        // can have either duplicated or skipped attributes, so we strive to do no better
6282
        // here. Use the same values snapshot as the size load above.
6283
        uint8_t *order = get_insertion_order_array(values);
6284
        int index = _Py_atomic_load_uint8_relaxed(&order[i]);
6285
        PyObject *value = _Py_atomic_load_ptr(&values->values[index]);
6286
        if (value == NULL) {
6287
            // Deletion clears the slot before decrementing values->size.
6288
            goto try_locked;
6289
        }
6290
        if (acquire_key_value(&DK_UNICODE_ENTRIES(k)[index].me_key, value,
6291
                               &values->values[index], out_key, out_value) < 0) {
6292
            goto try_locked;
6293
        }
6294
    }
6295
    else {
6296
        Py_ssize_t n = _Py_atomic_load_ssize_relaxed(&k->dk_nentries);
6297
        if (DK_IS_UNICODE(k)) {
6298
            PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(k)[i];
6299
            PyObject *value;
6300
            while (i < n &&
6301
                  (value = _Py_atomic_load_ptr(&entry_ptr->me_value)) == NULL) {
6302
                entry_ptr++;
6303
                i++;
6304
            }
6305
            if (i >= n)
6306
                goto fail;
6307
6308
            if (acquire_key_value(&entry_ptr->me_key, value,
6309
                                   &entry_ptr->me_value, out_key, out_value) < 0) {
6310
                goto try_locked;
6311
            }
6312
        }
6313
        else {
6314
            PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
6315
            PyObject *value;
6316
            while (i < n &&
6317
                  (value = _Py_atomic_load_ptr(&entry_ptr->me_value)) == NULL) {
6318
                entry_ptr++;
6319
                i++;
6320
            }
6321
6322
            if (i >= n)
6323
                goto fail;
6324
6325
            if (acquire_key_value(&entry_ptr->me_key, value,
6326
                                   &entry_ptr->me_value, out_key, out_value) < 0) {
6327
                goto try_locked;
6328
            }
6329
        }
6330
    }
6331
    // We found an element (key), but did not expect it
6332
    Py_ssize_t len;
6333
    if ((len = _Py_atomic_load_ssize_relaxed(&di->len)) == 0) {
6334
        goto concurrent_modification;
6335
    }
6336
6337
    _Py_atomic_store_ssize_relaxed(&di->di_pos, i + 1);
6338
    _Py_atomic_store_ssize_relaxed(&di->len, len - 1);
6339
    return 0;
6340
6341
concurrent_modification:
6342
    PyErr_SetString(PyExc_RuntimeError,
6343
                    "dictionary keys changed during iteration");
6344
6345
fail:
6346
    dictiter_set_exhausted(di, d);
6347
    return -1;
6348
6349
try_locked:
6350
    Py_BEGIN_CRITICAL_SECTION(d);
6351
    res = dictiter_iternextitem_lock_held(d, self, out_key, out_value);
6352
    Py_END_CRITICAL_SECTION();
6353
    return res;
6354
}
6355
6356
#endif
6357
6358
static bool
6359
acquire_iter_result(PyObject *result)
6360
3.21M
{
6361
3.21M
    if (_PyObject_IsUniquelyReferenced(result)) {
6362
3.19M
        Py_INCREF(result);
6363
3.19M
        return true;
6364
3.19M
    }
6365
22.9k
    return false;
6366
3.21M
}
6367
6368
static PyObject *
6369
dictiter_iternextitem(PyObject *self)
6370
4.80M
{
6371
4.80M
    dictiterobject *di = (dictiterobject *)self;
6372
4.80M
    PyDictObject *d = di->di_dict;
6373
6374
4.80M
    if (d == NULL)
6375
0
        return NULL;
6376
6377
4.80M
    PyObject *key, *value;
6378
#ifdef Py_GIL_DISABLED
6379
    if (dictiter_iternext_threadsafe(d, self, &key, &value) == 0) {
6380
#else
6381
4.80M
    if (dictiter_iternextitem_lock_held(d, self, &key, &value) == 0) {
6382
6383
3.21M
#endif
6384
3.21M
        PyObject *result = di->di_result;
6385
3.21M
        if (acquire_iter_result(result)) {
6386
3.19M
            PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
6387
3.19M
            PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
6388
3.19M
            PyTuple_SET_ITEM(result, 0, key);
6389
3.19M
            PyTuple_SET_ITEM(result, 1, value);
6390
3.19M
            Py_DECREF(oldkey);
6391
3.19M
            Py_DECREF(oldvalue);
6392
            // bpo-42536: The GC may have untracked this result tuple. Since we're
6393
            // recycling it, make sure it's tracked again:
6394
3.19M
            _PyTuple_Recycle(result);
6395
3.19M
        }
6396
22.9k
        else {
6397
22.9k
            result = _PyTuple_FromPairSteal(key, value);
6398
22.9k
        }
6399
3.21M
        return result;
6400
3.21M
    }
6401
1.59M
    return NULL;
6402
4.80M
}
6403
6404
PyTypeObject PyDictIterItem_Type = {
6405
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
6406
    "dict_itemiterator",                        /* tp_name */
6407
    sizeof(dictiterobject),                     /* tp_basicsize */
6408
    0,                                          /* tp_itemsize */
6409
    /* methods */
6410
    dictiter_dealloc,                           /* tp_dealloc */
6411
    0,                                          /* tp_vectorcall_offset */
6412
    0,                                          /* tp_getattr */
6413
    0,                                          /* tp_setattr */
6414
    0,                                          /* tp_as_async */
6415
    0,                                          /* tp_repr */
6416
    0,                                          /* tp_as_number */
6417
    0,                                          /* tp_as_sequence */
6418
    0,                                          /* tp_as_mapping */
6419
    0,                                          /* tp_hash */
6420
    0,                                          /* tp_call */
6421
    0,                                          /* tp_str */
6422
    PyObject_GenericGetAttr,                    /* tp_getattro */
6423
    0,                                          /* tp_setattro */
6424
    0,                                          /* tp_as_buffer */
6425
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
6426
    0,                                          /* tp_doc */
6427
    dictiter_traverse,                          /* tp_traverse */
6428
    0,                                          /* tp_clear */
6429
    0,                                          /* tp_richcompare */
6430
    0,                                          /* tp_weaklistoffset */
6431
    PyObject_SelfIter,                          /* tp_iter */
6432
    dictiter_iternextitem,                      /* tp_iternext */
6433
    dictiter_methods,                           /* tp_methods */
6434
    0,
6435
};
6436
6437
6438
/* dictreviter */
6439
6440
static PyObject *
6441
dictreviter_iter_lock_held(PyDictObject *d, PyObject *self)
6442
0
{
6443
0
    dictiterobject *di = (dictiterobject *)self;
6444
6445
0
    assert (PyAnyDict_Check(d));
6446
0
    ASSERT_DICT_LOCKED(d);
6447
6448
#ifdef Py_GIL_DISABLED
6449
    if (di->di_pos == DICTITER_EXHAUSTED) {
6450
        return NULL;
6451
    }
6452
#endif
6453
6454
0
    if (di->di_used != d->ma_used) {
6455
0
        PyErr_SetString(PyExc_RuntimeError,
6456
0
                         "dictionary changed size during iteration");
6457
0
        di->di_used = -1; /* Make this state sticky */
6458
0
        return NULL;
6459
0
    }
6460
6461
0
    Py_ssize_t i = di->di_pos;
6462
0
    PyDictKeysObject *k = d->ma_keys;
6463
0
    PyObject *key, *value, *result;
6464
6465
0
    if (i < 0) {
6466
0
        goto fail;
6467
0
    }
6468
0
    if (_PyDict_HasSplitTable(d)) {
6469
0
        int index = get_index_from_order(d, i);
6470
0
        key = LOAD_SHARED_KEY(DK_UNICODE_ENTRIES(k)[index].me_key);
6471
0
        value = d->ma_values->values[index];
6472
0
        assert(value != NULL);
6473
0
    }
6474
0
    else {
6475
0
        if (i >= k->dk_nentries) {
6476
0
            goto fail;
6477
0
        }
6478
0
        if (DK_IS_UNICODE(k)) {
6479
0
            PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(k)[i];
6480
0
            while (entry_ptr->me_value == NULL) {
6481
0
                if (--i < 0) {
6482
0
                    goto fail;
6483
0
                }
6484
0
                entry_ptr--;
6485
0
            }
6486
0
            key = entry_ptr->me_key;
6487
0
            value = entry_ptr->me_value;
6488
0
        }
6489
0
        else {
6490
0
            PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
6491
0
            while (entry_ptr->me_value == NULL) {
6492
0
                if (--i < 0) {
6493
0
                    goto fail;
6494
0
                }
6495
0
                entry_ptr--;
6496
0
            }
6497
0
            key = entry_ptr->me_key;
6498
0
            value = entry_ptr->me_value;
6499
0
        }
6500
0
    }
6501
    // We found an element, but did not expect it
6502
0
    if (di->len == 0) {
6503
0
        PyErr_SetString(PyExc_RuntimeError,
6504
0
                        "dictionary keys changed during iteration");
6505
0
        goto fail;
6506
0
    }
6507
0
    di->di_pos = i-1;
6508
0
    di->len--;
6509
6510
0
    if (Py_IS_TYPE(di, &PyDictRevIterKey_Type)) {
6511
0
        return Py_NewRef(key);
6512
0
    }
6513
0
    else if (Py_IS_TYPE(di, &PyDictRevIterValue_Type)) {
6514
0
        return Py_NewRef(value);
6515
0
    }
6516
0
    else if (Py_IS_TYPE(di, &PyDictRevIterItem_Type)) {
6517
0
        result = di->di_result;
6518
0
        if (_PyObject_IsUniquelyReferenced(result)) {
6519
0
            PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
6520
0
            PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
6521
0
            PyTuple_SET_ITEM(result, 0, Py_NewRef(key));
6522
0
            PyTuple_SET_ITEM(result, 1, Py_NewRef(value));
6523
0
            Py_INCREF(result);
6524
0
            Py_DECREF(oldkey);
6525
0
            Py_DECREF(oldvalue);
6526
            // bpo-42536: The GC may have untracked this result tuple. Since
6527
            // we're recycling it, make sure it's tracked again:
6528
0
            _PyTuple_Recycle(result);
6529
0
        }
6530
0
        else {
6531
0
            result = _PyTuple_FromPair(key, value);
6532
0
        }
6533
0
        return result;
6534
0
    }
6535
0
    else {
6536
0
        Py_UNREACHABLE();
6537
0
    }
6538
6539
0
fail:
6540
0
    dictiter_set_exhausted(di, d);
6541
0
    return NULL;
6542
0
}
6543
6544
static PyObject *
6545
dictreviter_iternext(PyObject *self)
6546
0
{
6547
0
    dictiterobject *di = (dictiterobject *)self;
6548
0
    PyDictObject *d = di->di_dict;
6549
6550
0
    if (d == NULL)
6551
0
        return NULL;
6552
6553
0
    PyObject *value;
6554
0
    Py_BEGIN_CRITICAL_SECTION(d);
6555
0
    value = dictreviter_iter_lock_held(d, self);
6556
0
    Py_END_CRITICAL_SECTION();
6557
6558
0
    return value;
6559
0
}
6560
6561
PyTypeObject PyDictRevIterKey_Type = {
6562
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
6563
    "dict_reversekeyiterator",
6564
    sizeof(dictiterobject),
6565
    .tp_dealloc = dictiter_dealloc,
6566
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
6567
    .tp_traverse = dictiter_traverse,
6568
    .tp_iter = PyObject_SelfIter,
6569
    .tp_iternext = dictreviter_iternext,
6570
    .tp_methods = dictiter_methods
6571
};
6572
6573
6574
/*[clinic input]
6575
dict.__reversed__
6576
6577
Return a reverse iterator over the dict keys.
6578
[clinic start generated code]*/
6579
6580
static PyObject *
6581
dict___reversed___impl(PyDictObject *self)
6582
/*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
6583
0
{
6584
0
    assert (PyAnyDict_Check(self));
6585
0
    return dictiter_new(self, &PyDictRevIterKey_Type);
6586
0
}
6587
6588
static PyObject *
6589
dictiter_reduce(PyObject *self, PyObject *Py_UNUSED(ignored))
6590
0
{
6591
0
    dictiterobject *di = (dictiterobject *)self;
6592
    /* copy the iterator state */
6593
0
    dictiterobject tmp = *di;
6594
0
    Py_XINCREF(tmp.di_dict);
6595
0
    PyObject *list = PySequence_List((PyObject*)&tmp);
6596
0
    Py_XDECREF(tmp.di_dict);
6597
0
    if (list == NULL) {
6598
0
        return NULL;
6599
0
    }
6600
0
    return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(iter)), list);
6601
0
}
6602
6603
PyTypeObject PyDictRevIterItem_Type = {
6604
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
6605
    "dict_reverseitemiterator",
6606
    sizeof(dictiterobject),
6607
    .tp_dealloc = dictiter_dealloc,
6608
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
6609
    .tp_traverse = dictiter_traverse,
6610
    .tp_iter = PyObject_SelfIter,
6611
    .tp_iternext = dictreviter_iternext,
6612
    .tp_methods = dictiter_methods
6613
};
6614
6615
PyTypeObject PyDictRevIterValue_Type = {
6616
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
6617
    "dict_reversevalueiterator",
6618
    sizeof(dictiterobject),
6619
    .tp_dealloc = dictiter_dealloc,
6620
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
6621
    .tp_traverse = dictiter_traverse,
6622
    .tp_iter = PyObject_SelfIter,
6623
    .tp_iternext = dictreviter_iternext,
6624
    .tp_methods = dictiter_methods
6625
};
6626
6627
/***********************************************/
6628
/* View objects for keys(), items(), values(). */
6629
/***********************************************/
6630
6631
/* The instance lay-out is the same for all three; but the type differs. */
6632
6633
static void
6634
dictview_dealloc(PyObject *self)
6635
1.87M
{
6636
1.87M
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
6637
    /* bpo-31095: UnTrack is needed before calling any callbacks */
6638
1.87M
    _PyObject_GC_UNTRACK(dv);
6639
1.87M
    Py_XDECREF(dv->dv_dict);
6640
1.87M
    PyObject_GC_Del(dv);
6641
1.87M
}
6642
6643
static int
6644
dictview_traverse(PyObject *self, visitproc visit, void *arg)
6645
428
{
6646
428
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
6647
428
    Py_VISIT(dv->dv_dict);
6648
428
    return 0;
6649
428
}
6650
6651
static Py_ssize_t
6652
dictview_len(PyObject *self)
6653
12
{
6654
12
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
6655
12
    Py_ssize_t len = 0;
6656
12
    if (dv->dv_dict != NULL)
6657
12
        len = GET_USED(dv->dv_dict);
6658
12
    return len;
6659
12
}
6660
6661
PyObject *
6662
_PyDictView_New(PyObject *dict, PyTypeObject *type)
6663
1.87M
{
6664
1.87M
    _PyDictViewObject *dv;
6665
1.87M
    if (dict == NULL) {
6666
0
        PyErr_BadInternalCall();
6667
0
        return NULL;
6668
0
    }
6669
1.87M
    if (!PyAnyDict_Check(dict)) {
6670
        /* XXX Get rid of this restriction later */
6671
0
        PyErr_Format(PyExc_TypeError,
6672
0
                     "%s() requires a dict argument, not '%s'",
6673
0
                     type->tp_name, Py_TYPE(dict)->tp_name);
6674
0
        return NULL;
6675
0
    }
6676
1.87M
    dv = PyObject_GC_New(_PyDictViewObject, type);
6677
1.87M
    if (dv == NULL)
6678
0
        return NULL;
6679
1.87M
    dv->dv_dict = (PyDictObject *)Py_NewRef(dict);
6680
1.87M
    _PyObject_GC_TRACK(dv);
6681
1.87M
    return (PyObject *)dv;
6682
1.87M
}
6683
6684
static PyObject *
6685
0
dictview_mapping(PyObject *view, void *Py_UNUSED(ignored)) {
6686
0
    assert(view != NULL);
6687
0
    assert(PyDictKeys_Check(view)
6688
0
           || PyDictValues_Check(view)
6689
0
           || PyDictItems_Check(view));
6690
0
    PyObject *mapping = (PyObject *)((_PyDictViewObject *)view)->dv_dict;
6691
0
    return PyDictProxy_New(mapping);
6692
0
}
6693
6694
static PyGetSetDef dictview_getset[] = {
6695
    {"mapping", dictview_mapping, NULL,
6696
     PyDoc_STR("dictionary that this view refers to"), NULL},
6697
    {0}
6698
};
6699
6700
/* TODO(guido): The views objects are not complete:
6701
6702
 * support more set operations
6703
 * support arbitrary mappings?
6704
   - either these should be static or exported in dictobject.h
6705
   - if public then they should probably be in builtins
6706
*/
6707
6708
/* Return 1 if self is a subset of other, iterating over self;
6709
   0 if not; -1 if an error occurred. */
6710
static int
6711
all_contained_in(PyObject *self, PyObject *other)
6712
0
{
6713
0
    PyObject *iter = PyObject_GetIter(self);
6714
0
    int ok = 1;
6715
6716
0
    if (iter == NULL)
6717
0
        return -1;
6718
0
    for (;;) {
6719
0
        PyObject *next = PyIter_Next(iter);
6720
0
        if (next == NULL) {
6721
0
            if (PyErr_Occurred())
6722
0
                ok = -1;
6723
0
            break;
6724
0
        }
6725
0
        ok = PySequence_Contains(other, next);
6726
0
        Py_DECREF(next);
6727
0
        if (ok <= 0)
6728
0
            break;
6729
0
    }
6730
0
    Py_DECREF(iter);
6731
0
    return ok;
6732
0
}
6733
6734
static PyObject *
6735
dictview_richcompare(PyObject *self, PyObject *other, int op)
6736
0
{
6737
0
    Py_ssize_t len_self, len_other;
6738
0
    int ok;
6739
0
    PyObject *result;
6740
6741
0
    assert(self != NULL);
6742
0
    assert(PyDictViewSet_Check(self));
6743
0
    assert(other != NULL);
6744
6745
0
    if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
6746
0
        Py_RETURN_NOTIMPLEMENTED;
6747
6748
0
    len_self = PyObject_Size(self);
6749
0
    if (len_self < 0)
6750
0
        return NULL;
6751
0
    len_other = PyObject_Size(other);
6752
0
    if (len_other < 0)
6753
0
        return NULL;
6754
6755
0
    ok = 0;
6756
0
    switch(op) {
6757
6758
0
    case Py_NE:
6759
0
    case Py_EQ:
6760
0
        if (len_self == len_other)
6761
0
            ok = all_contained_in(self, other);
6762
0
        if (op == Py_NE && ok >= 0)
6763
0
            ok = !ok;
6764
0
        break;
6765
6766
0
    case Py_LT:
6767
0
        if (len_self < len_other)
6768
0
            ok = all_contained_in(self, other);
6769
0
        break;
6770
6771
0
      case Py_LE:
6772
0
          if (len_self <= len_other)
6773
0
              ok = all_contained_in(self, other);
6774
0
          break;
6775
6776
0
    case Py_GT:
6777
0
        if (len_self > len_other)
6778
0
            ok = all_contained_in(other, self);
6779
0
        break;
6780
6781
0
    case Py_GE:
6782
0
        if (len_self >= len_other)
6783
0
            ok = all_contained_in(other, self);
6784
0
        break;
6785
6786
0
    }
6787
0
    if (ok < 0)
6788
0
        return NULL;
6789
0
    result = ok ? Py_True : Py_False;
6790
0
    return Py_NewRef(result);
6791
0
}
6792
6793
static PyObject *
6794
dictview_repr(PyObject *self)
6795
0
{
6796
0
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
6797
0
    PyObject *seq;
6798
0
    PyObject *result = NULL;
6799
0
    Py_ssize_t rc;
6800
6801
0
    rc = Py_ReprEnter((PyObject *)dv);
6802
0
    if (rc != 0) {
6803
0
        return rc > 0 ? PyUnicode_FromString("...") : NULL;
6804
0
    }
6805
0
    seq = PySequence_List((PyObject *)dv);
6806
0
    if (seq == NULL) {
6807
0
        goto Done;
6808
0
    }
6809
0
    result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
6810
0
    Py_DECREF(seq);
6811
6812
0
Done:
6813
0
    Py_ReprLeave((PyObject *)dv);
6814
0
    return result;
6815
0
}
6816
6817
/*** dict_keys ***/
6818
6819
static PyObject *
6820
dictkeys_iter(PyObject *self)
6821
126k
{
6822
126k
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
6823
126k
    if (dv->dv_dict == NULL) {
6824
0
        Py_RETURN_NONE;
6825
0
    }
6826
126k
    return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
6827
126k
}
6828
6829
static int
6830
dictkeys_contains(PyObject *self, PyObject *obj)
6831
26.3k
{
6832
26.3k
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
6833
26.3k
    if (dv->dv_dict == NULL)
6834
0
        return 0;
6835
26.3k
    return dict_contains((PyObject *)dv->dv_dict, obj);
6836
26.3k
}
6837
6838
static PySequenceMethods dictkeys_as_sequence = {
6839
    dictview_len,                       /* sq_length */
6840
    0,                                  /* sq_concat */
6841
    0,                                  /* sq_repeat */
6842
    0,                                  /* sq_item */
6843
    0,                                  /* sq_slice */
6844
    0,                                  /* sq_ass_item */
6845
    0,                                  /* sq_ass_slice */
6846
    dictkeys_contains,                  /* sq_contains */
6847
};
6848
6849
// Create a set object from dictviews object.
6850
// Returns a new reference.
6851
// This utility function is used by set operations.
6852
static PyObject*
6853
dictviews_to_set(PyObject *self)
6854
0
{
6855
0
    PyObject *left = self;
6856
0
    if (PyDictKeys_Check(self)) {
6857
        // PySet_New() has fast path for the dict object.
6858
0
        PyObject *dict = (PyObject *)((_PyDictViewObject *)self)->dv_dict;
6859
0
        if (PyAnyDict_CheckExact(dict)) {
6860
0
            left = dict;
6861
0
        }
6862
0
    }
6863
0
    return PySet_New(left);
6864
0
}
6865
6866
static PyObject*
6867
dictviews_sub(PyObject *self, PyObject *other)
6868
0
{
6869
0
    PyObject *result = dictviews_to_set(self);
6870
0
    if (result == NULL) {
6871
0
        return NULL;
6872
0
    }
6873
6874
0
    PyObject *tmp = PyObject_CallMethodOneArg(
6875
0
            result, &_Py_ID(difference_update), other);
6876
0
    if (tmp == NULL) {
6877
0
        Py_DECREF(result);
6878
0
        return NULL;
6879
0
    }
6880
6881
0
    Py_DECREF(tmp);
6882
0
    return result;
6883
0
}
6884
6885
static int
6886
dictitems_contains(PyObject *dv, PyObject *obj);
6887
6888
PyObject *
6889
_PyDictView_Intersect(PyObject* self, PyObject *other)
6890
4
{
6891
4
    PyObject *result;
6892
4
    PyObject *it;
6893
4
    PyObject *key;
6894
4
    Py_ssize_t len_self;
6895
4
    int rv;
6896
4
    objobjproc dict_contains;
6897
6898
    /* Python interpreter swaps parameters when dict view
6899
       is on right side of & */
6900
4
    if (!PyDictViewSet_Check(self)) {
6901
0
        PyObject *tmp = other;
6902
0
        other = self;
6903
0
        self = tmp;
6904
0
    }
6905
6906
4
    len_self = dictview_len(self);
6907
6908
    /* if other is a set and self is smaller than other,
6909
       reuse set intersection logic */
6910
4
    if (PySet_CheckExact(other) && len_self <= PyObject_Size(other)) {
6911
0
        return PyObject_CallMethodObjArgs(
6912
0
                other, &_Py_ID(intersection), self, NULL);
6913
0
    }
6914
6915
    /* if other is another dict view, and it is bigger than self,
6916
       swap them */
6917
4
    if (PyDictViewSet_Check(other)) {
6918
0
        Py_ssize_t len_other = dictview_len(other);
6919
0
        if (len_other > len_self) {
6920
0
            PyObject *tmp = other;
6921
0
            other = self;
6922
0
            self = tmp;
6923
0
        }
6924
0
    }
6925
6926
    /* at this point, two things should be true
6927
       1. self is a dictview
6928
       2. if other is a dictview then it is smaller than self */
6929
4
    result = PySet_New(NULL);
6930
4
    if (result == NULL)
6931
0
        return NULL;
6932
6933
4
    it = PyObject_GetIter(other);
6934
4
    if (it == NULL) {
6935
0
        Py_DECREF(result);
6936
0
        return NULL;
6937
0
    }
6938
6939
4
    if (PyDictKeys_Check(self)) {
6940
4
        dict_contains = dictkeys_contains;
6941
4
    }
6942
    /* else PyDictItems_Check(self) */
6943
0
    else {
6944
0
        dict_contains = dictitems_contains;
6945
0
    }
6946
6947
224
    while ((key = PyIter_Next(it)) != NULL) {
6948
220
        rv = dict_contains(self, key);
6949
220
        if (rv < 0) {
6950
0
            goto error;
6951
0
        }
6952
220
        if (rv) {
6953
220
            if (PySet_Add(result, key)) {
6954
0
                goto error;
6955
0
            }
6956
220
        }
6957
220
        Py_DECREF(key);
6958
220
    }
6959
4
    Py_DECREF(it);
6960
4
    if (PyErr_Occurred()) {
6961
0
        Py_DECREF(result);
6962
0
        return NULL;
6963
0
    }
6964
4
    return result;
6965
6966
0
error:
6967
0
    Py_DECREF(it);
6968
0
    Py_DECREF(result);
6969
0
    Py_DECREF(key);
6970
0
    return NULL;
6971
4
}
6972
6973
static PyObject*
6974
dictviews_or(PyObject* self, PyObject *other)
6975
0
{
6976
0
    PyObject *result = dictviews_to_set(self);
6977
0
    if (result == NULL) {
6978
0
        return NULL;
6979
0
    }
6980
6981
0
    if (_PySet_Update(result, other) < 0) {
6982
0
        Py_DECREF(result);
6983
0
        return NULL;
6984
0
    }
6985
0
    return result;
6986
0
}
6987
6988
static PyObject *
6989
dictitems_xor_lock_held(PyObject *d1, PyObject *d2)
6990
0
{
6991
0
    ASSERT_DICT_LOCKED(d1);
6992
0
    ASSERT_DICT_LOCKED(d2);
6993
6994
0
    PyObject *temp_dict = copy_lock_held_untracked(d1, 0);
6995
0
    if (temp_dict == NULL) {
6996
0
        return NULL;
6997
0
    }
6998
0
    _PyObject_GC_TRACK(temp_dict);
6999
7000
0
    PyObject *result_set = PySet_New(NULL);
7001
0
    if (result_set == NULL) {
7002
0
        Py_CLEAR(temp_dict);
7003
0
        return NULL;
7004
0
    }
7005
7006
0
    PyObject *key = NULL, *val1 = NULL, *val2 = NULL;
7007
0
    Py_ssize_t pos = 0;
7008
0
    Py_hash_t hash;
7009
7010
0
    while (_PyDict_Next(d2, &pos, &key, &val2, &hash)) {
7011
0
        Py_INCREF(key);
7012
0
        Py_INCREF(val2);
7013
0
        val1 = _PyDict_GetItem_KnownHash(temp_dict, key, hash);
7014
7015
0
        int to_delete;
7016
0
        if (val1 == NULL) {
7017
0
            if (PyErr_Occurred()) {
7018
0
                goto error;
7019
0
            }
7020
0
            to_delete = 0;
7021
0
        }
7022
0
        else {
7023
0
            Py_INCREF(val1);
7024
0
            to_delete = PyObject_RichCompareBool(val1, val2, Py_EQ);
7025
0
            Py_CLEAR(val1);
7026
0
            if (to_delete < 0) {
7027
0
                goto error;
7028
0
            }
7029
0
        }
7030
7031
0
        if (to_delete) {
7032
0
            Py_CLEAR(val2);
7033
0
            if (_PyDict_DelItem_KnownHash(temp_dict, key, hash) < 0) {
7034
0
                goto error;
7035
0
            }
7036
0
            Py_CLEAR(key);
7037
0
        }
7038
0
        else {
7039
0
            PyObject *pair = _PyTuple_FromPairSteal(key, val2);
7040
0
            key = val2 = NULL;
7041
0
            if (pair == NULL) {
7042
0
                goto error;
7043
0
            }
7044
0
            if (PySet_Add(result_set, pair) < 0) {
7045
0
                Py_DECREF(pair);
7046
0
                goto error;
7047
0
            }
7048
0
            Py_DECREF(pair);
7049
0
        }
7050
0
    }
7051
7052
0
    PyObject *remaining_pairs = PyObject_CallMethodNoArgs(
7053
0
            temp_dict, &_Py_ID(items));
7054
0
    if (remaining_pairs == NULL) {
7055
0
        goto error;
7056
0
    }
7057
0
    if (_PySet_Update(result_set, remaining_pairs) < 0) {
7058
0
        Py_DECREF(remaining_pairs);
7059
0
        goto error;
7060
0
    }
7061
0
    Py_DECREF(temp_dict);
7062
0
    Py_DECREF(remaining_pairs);
7063
0
    return result_set;
7064
7065
0
error:
7066
0
    Py_XDECREF(temp_dict);
7067
0
    Py_XDECREF(result_set);
7068
0
    Py_XDECREF(key);
7069
0
    Py_XDECREF(val1);
7070
0
    Py_XDECREF(val2);
7071
0
    return NULL;
7072
0
}
7073
7074
static PyObject *
7075
dictitems_xor(PyObject *self, PyObject *other)
7076
0
{
7077
0
    assert(PyDictItems_Check(self));
7078
0
    assert(PyDictItems_Check(other));
7079
0
    PyObject *d1 = (PyObject *)((_PyDictViewObject *)self)->dv_dict;
7080
0
    PyObject *d2 = (PyObject *)((_PyDictViewObject *)other)->dv_dict;
7081
7082
0
    PyObject *res;
7083
0
    Py_BEGIN_CRITICAL_SECTION2(d1, d2);
7084
0
    res = dictitems_xor_lock_held(d1, d2);
7085
0
    Py_END_CRITICAL_SECTION2();
7086
7087
0
    return res;
7088
0
}
7089
7090
static PyObject*
7091
dictviews_xor(PyObject* self, PyObject *other)
7092
0
{
7093
0
    if (PyDictItems_Check(self) && PyDictItems_Check(other)) {
7094
0
        return dictitems_xor(self, other);
7095
0
    }
7096
0
    PyObject *result = dictviews_to_set(self);
7097
0
    if (result == NULL) {
7098
0
        return NULL;
7099
0
    }
7100
7101
0
    PyObject *tmp = PyObject_CallMethodOneArg(
7102
0
            result, &_Py_ID(symmetric_difference_update), other);
7103
0
    if (tmp == NULL) {
7104
0
        Py_DECREF(result);
7105
0
        return NULL;
7106
0
    }
7107
7108
0
    Py_DECREF(tmp);
7109
0
    return result;
7110
0
}
7111
7112
static PyNumberMethods dictviews_as_number = {
7113
    0,                                  /*nb_add*/
7114
    dictviews_sub,                      /*nb_subtract*/
7115
    0,                                  /*nb_multiply*/
7116
    0,                                  /*nb_remainder*/
7117
    0,                                  /*nb_divmod*/
7118
    0,                                  /*nb_power*/
7119
    0,                                  /*nb_negative*/
7120
    0,                                  /*nb_positive*/
7121
    0,                                  /*nb_absolute*/
7122
    0,                                  /*nb_bool*/
7123
    0,                                  /*nb_invert*/
7124
    0,                                  /*nb_lshift*/
7125
    0,                                  /*nb_rshift*/
7126
    _PyDictView_Intersect,              /*nb_and*/
7127
    dictviews_xor,                      /*nb_xor*/
7128
    dictviews_or,                       /*nb_or*/
7129
};
7130
7131
static PyObject*
7132
dictviews_isdisjoint(PyObject *self, PyObject *other)
7133
0
{
7134
0
    PyObject *it;
7135
0
    PyObject *item = NULL;
7136
7137
0
    if (self == other) {
7138
0
        if (dictview_len(self) == 0)
7139
0
            Py_RETURN_TRUE;
7140
0
        else
7141
0
            Py_RETURN_FALSE;
7142
0
    }
7143
7144
    /* Iterate over the shorter object (only if other is a set,
7145
     * because PySequence_Contains may be expensive otherwise): */
7146
0
    if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
7147
0
        Py_ssize_t len_self = dictview_len(self);
7148
0
        Py_ssize_t len_other = PyObject_Size(other);
7149
0
        if (len_other == -1)
7150
0
            return NULL;
7151
7152
0
        if ((len_other > len_self)) {
7153
0
            PyObject *tmp = other;
7154
0
            other = self;
7155
0
            self = tmp;
7156
0
        }
7157
0
    }
7158
7159
0
    it = PyObject_GetIter(other);
7160
0
    if (it == NULL)
7161
0
        return NULL;
7162
7163
0
    while ((item = PyIter_Next(it)) != NULL) {
7164
0
        int contains = PySequence_Contains(self, item);
7165
0
        Py_DECREF(item);
7166
0
        if (contains == -1) {
7167
0
            Py_DECREF(it);
7168
0
            return NULL;
7169
0
        }
7170
7171
0
        if (contains) {
7172
0
            Py_DECREF(it);
7173
0
            Py_RETURN_FALSE;
7174
0
        }
7175
0
    }
7176
0
    Py_DECREF(it);
7177
0
    if (PyErr_Occurred())
7178
0
        return NULL; /* PyIter_Next raised an exception. */
7179
0
    Py_RETURN_TRUE;
7180
0
}
7181
7182
PyDoc_STRVAR(isdisjoint_doc,
7183
"Return True if the view and the given iterable have a null intersection.");
7184
7185
static PyObject* dictkeys_reversed(PyObject *dv, PyObject *Py_UNUSED(ignored));
7186
7187
PyDoc_STRVAR(reversed_keys_doc,
7188
"Return a reverse iterator over the dict keys.");
7189
7190
static PyMethodDef dictkeys_methods[] = {
7191
    {"isdisjoint",      dictviews_isdisjoint,           METH_O,
7192
     isdisjoint_doc},
7193
    {"__reversed__",    dictkeys_reversed,              METH_NOARGS,
7194
     reversed_keys_doc},
7195
    {NULL,              NULL}           /* sentinel */
7196
};
7197
7198
PyTypeObject PyDictKeys_Type = {
7199
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
7200
    "dict_keys",                                /* tp_name */
7201
    sizeof(_PyDictViewObject),                  /* tp_basicsize */
7202
    0,                                          /* tp_itemsize */
7203
    /* methods */
7204
    dictview_dealloc,                           /* tp_dealloc */
7205
    0,                                          /* tp_vectorcall_offset */
7206
    0,                                          /* tp_getattr */
7207
    0,                                          /* tp_setattr */
7208
    0,                                          /* tp_as_async */
7209
    dictview_repr,                              /* tp_repr */
7210
    &dictviews_as_number,                       /* tp_as_number */
7211
    &dictkeys_as_sequence,                      /* tp_as_sequence */
7212
    0,                                          /* tp_as_mapping */
7213
    0,                                          /* tp_hash */
7214
    0,                                          /* tp_call */
7215
    0,                                          /* tp_str */
7216
    PyObject_GenericGetAttr,                    /* tp_getattro */
7217
    0,                                          /* tp_setattro */
7218
    0,                                          /* tp_as_buffer */
7219
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
7220
    0,                                          /* tp_doc */
7221
    dictview_traverse,                          /* tp_traverse */
7222
    0,                                          /* tp_clear */
7223
    dictview_richcompare,                       /* tp_richcompare */
7224
    0,                                          /* tp_weaklistoffset */
7225
    dictkeys_iter,                              /* tp_iter */
7226
    0,                                          /* tp_iternext */
7227
    dictkeys_methods,                           /* tp_methods */
7228
    .tp_getset = dictview_getset,
7229
};
7230
7231
/*[clinic input]
7232
dict.keys
7233
7234
Return a set-like object providing a view on the dict's keys.
7235
[clinic start generated code]*/
7236
7237
static PyObject *
7238
dict_keys_impl(PyDictObject *self)
7239
/*[clinic end generated code: output=aac2830c62990358 input=42f48a7a771212a7]*/
7240
126k
{
7241
126k
    return _PyDictView_New((PyObject *)self, &PyDictKeys_Type);
7242
126k
}
7243
7244
static PyObject *
7245
dictkeys_reversed(PyObject *self, PyObject *Py_UNUSED(ignored))
7246
0
{
7247
0
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
7248
0
    if (dv->dv_dict == NULL) {
7249
0
        Py_RETURN_NONE;
7250
0
    }
7251
0
    return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
7252
0
}
7253
7254
/*** dict_items ***/
7255
7256
static PyObject *
7257
dictitems_iter(PyObject *self)
7258
1.59M
{
7259
1.59M
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
7260
1.59M
    if (dv->dv_dict == NULL) {
7261
0
        Py_RETURN_NONE;
7262
0
    }
7263
1.59M
    return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
7264
1.59M
}
7265
7266
static int
7267
dictitems_contains(PyObject *self, PyObject *obj)
7268
0
{
7269
0
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
7270
0
    int result;
7271
0
    PyObject *key, *value, *found;
7272
0
    if (dv->dv_dict == NULL)
7273
0
        return 0;
7274
0
    if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
7275
0
        return 0;
7276
0
    key = PyTuple_GET_ITEM(obj, 0);
7277
0
    value = PyTuple_GET_ITEM(obj, 1);
7278
0
    result = PyDict_GetItemRef((PyObject *)dv->dv_dict, key, &found);
7279
0
    if (result == 1) {
7280
0
        result = PyObject_RichCompareBool(found, value, Py_EQ);
7281
0
        Py_DECREF(found);
7282
0
    }
7283
0
    return result;
7284
0
}
7285
7286
static PySequenceMethods dictitems_as_sequence = {
7287
    dictview_len,                       /* sq_length */
7288
    0,                                  /* sq_concat */
7289
    0,                                  /* sq_repeat */
7290
    0,                                  /* sq_item */
7291
    0,                                  /* sq_slice */
7292
    0,                                  /* sq_ass_item */
7293
    0,                                  /* sq_ass_slice */
7294
    dictitems_contains,                 /* sq_contains */
7295
};
7296
7297
static PyObject* dictitems_reversed(PyObject *dv, PyObject *Py_UNUSED(ignored));
7298
7299
PyDoc_STRVAR(reversed_items_doc,
7300
"Return a reverse iterator over the dict items.");
7301
7302
static PyMethodDef dictitems_methods[] = {
7303
    {"isdisjoint",      dictviews_isdisjoint,           METH_O,
7304
     isdisjoint_doc},
7305
    {"__reversed__",    dictitems_reversed,             METH_NOARGS,
7306
     reversed_items_doc},
7307
    {NULL,              NULL}           /* sentinel */
7308
};
7309
7310
PyTypeObject PyDictItems_Type = {
7311
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
7312
    "dict_items",                               /* tp_name */
7313
    sizeof(_PyDictViewObject),                  /* tp_basicsize */
7314
    0,                                          /* tp_itemsize */
7315
    /* methods */
7316
    dictview_dealloc,                           /* tp_dealloc */
7317
    0,                                          /* tp_vectorcall_offset */
7318
    0,                                          /* tp_getattr */
7319
    0,                                          /* tp_setattr */
7320
    0,                                          /* tp_as_async */
7321
    dictview_repr,                              /* tp_repr */
7322
    &dictviews_as_number,                       /* tp_as_number */
7323
    &dictitems_as_sequence,                     /* tp_as_sequence */
7324
    0,                                          /* tp_as_mapping */
7325
    0,                                          /* tp_hash */
7326
    0,                                          /* tp_call */
7327
    0,                                          /* tp_str */
7328
    PyObject_GenericGetAttr,                    /* tp_getattro */
7329
    0,                                          /* tp_setattro */
7330
    0,                                          /* tp_as_buffer */
7331
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
7332
    0,                                          /* tp_doc */
7333
    dictview_traverse,                          /* tp_traverse */
7334
    0,                                          /* tp_clear */
7335
    dictview_richcompare,                       /* tp_richcompare */
7336
    0,                                          /* tp_weaklistoffset */
7337
    dictitems_iter,                             /* tp_iter */
7338
    0,                                          /* tp_iternext */
7339
    dictitems_methods,                          /* tp_methods */
7340
    .tp_getset = dictview_getset,
7341
};
7342
7343
/*[clinic input]
7344
dict.items
7345
7346
Return a set-like object providing a view on the dict's items.
7347
[clinic start generated code]*/
7348
7349
static PyObject *
7350
dict_items_impl(PyDictObject *self)
7351
/*[clinic end generated code: output=88c7db7150c7909a input=87c822872eb71f5a]*/
7352
1.63M
{
7353
1.63M
    return _PyDictView_New((PyObject *)self, &PyDictItems_Type);
7354
1.63M
}
7355
7356
static PyObject *
7357
dictitems_reversed(PyObject *self, PyObject *Py_UNUSED(ignored))
7358
0
{
7359
0
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
7360
0
    if (dv->dv_dict == NULL) {
7361
0
        Py_RETURN_NONE;
7362
0
    }
7363
0
    return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
7364
0
}
7365
7366
/*** dict_values ***/
7367
7368
static PyObject *
7369
dictvalues_iter(PyObject *self)
7370
107k
{
7371
107k
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
7372
107k
    if (dv->dv_dict == NULL) {
7373
0
        Py_RETURN_NONE;
7374
0
    }
7375
107k
    return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
7376
107k
}
7377
7378
static PySequenceMethods dictvalues_as_sequence = {
7379
    dictview_len,                       /* sq_length */
7380
    0,                                  /* sq_concat */
7381
    0,                                  /* sq_repeat */
7382
    0,                                  /* sq_item */
7383
    0,                                  /* sq_slice */
7384
    0,                                  /* sq_ass_item */
7385
    0,                                  /* sq_ass_slice */
7386
    0,                                  /* sq_contains */
7387
};
7388
7389
static PyObject* dictvalues_reversed(PyObject *dv, PyObject *Py_UNUSED(ignored));
7390
7391
PyDoc_STRVAR(reversed_values_doc,
7392
"Return a reverse iterator over the dict values.");
7393
7394
static PyMethodDef dictvalues_methods[] = {
7395
    {"__reversed__",    dictvalues_reversed,            METH_NOARGS,
7396
     reversed_values_doc},
7397
    {NULL,              NULL}           /* sentinel */
7398
};
7399
7400
PyTypeObject PyDictValues_Type = {
7401
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
7402
    "dict_values",                              /* tp_name */
7403
    sizeof(_PyDictViewObject),                  /* tp_basicsize */
7404
    0,                                          /* tp_itemsize */
7405
    /* methods */
7406
    dictview_dealloc,                           /* tp_dealloc */
7407
    0,                                          /* tp_vectorcall_offset */
7408
    0,                                          /* tp_getattr */
7409
    0,                                          /* tp_setattr */
7410
    0,                                          /* tp_as_async */
7411
    dictview_repr,                              /* tp_repr */
7412
    0,                                          /* tp_as_number */
7413
    &dictvalues_as_sequence,                    /* tp_as_sequence */
7414
    0,                                          /* tp_as_mapping */
7415
    0,                                          /* tp_hash */
7416
    0,                                          /* tp_call */
7417
    0,                                          /* tp_str */
7418
    PyObject_GenericGetAttr,                    /* tp_getattro */
7419
    0,                                          /* tp_setattro */
7420
    0,                                          /* tp_as_buffer */
7421
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
7422
    0,                                          /* tp_doc */
7423
    dictview_traverse,                          /* tp_traverse */
7424
    0,                                          /* tp_clear */
7425
    0,                                          /* tp_richcompare */
7426
    0,                                          /* tp_weaklistoffset */
7427
    dictvalues_iter,                            /* tp_iter */
7428
    0,                                          /* tp_iternext */
7429
    dictvalues_methods,                         /* tp_methods */
7430
    .tp_getset = dictview_getset,
7431
};
7432
7433
/*[clinic input]
7434
dict.values
7435
7436
Return an object providing a view on the dict's values.
7437
[clinic start generated code]*/
7438
7439
static PyObject *
7440
dict_values_impl(PyDictObject *self)
7441
/*[clinic end generated code: output=ce9f2e9e8a959dd4 input=b46944f85493b230]*/
7442
107k
{
7443
107k
    return _PyDictView_New((PyObject *)self, &PyDictValues_Type);
7444
107k
}
7445
7446
static PyObject *
7447
dictvalues_reversed(PyObject *self, PyObject *Py_UNUSED(ignored))
7448
0
{
7449
0
    _PyDictViewObject *dv = (_PyDictViewObject *)self;
7450
0
    if (dv->dv_dict == NULL) {
7451
0
        Py_RETURN_NONE;
7452
0
    }
7453
0
    return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
7454
0
}
7455
7456
7457
/* Returns NULL if cannot allocate a new PyDictKeysObject,
7458
   but does not set an error */
7459
PyDictKeysObject *
7460
_PyDict_NewKeysForClass(PyHeapTypeObject *cls)
7461
278k
{
7462
278k
    int log2_bytes = get_log2_bytes(NEXT_LOG2_SHARED_KEYS_MAX_SIZE);
7463
278k
    Py_ssize_t usable = USABLE_FRACTION((size_t)1<<NEXT_LOG2_SHARED_KEYS_MAX_SIZE);
7464
7465
278k
    struct _instancekeysobject *shared_keys =
7466
278k
                          PyMem_Malloc(sizeof(struct _instancekeysobject)
7467
278k
                          + ((size_t)1 << log2_bytes)
7468
278k
                          + sizeof(PyDictUnicodeEntry) * usable);
7469
278k
    if (shared_keys == NULL) {
7470
0
        PyErr_Clear();
7471
0
        return NULL;
7472
0
    }
7473
7474
278k
    shared_keys->dsk_owning_type = (PyTypeObject *)cls;
7475
278k
    PyDictKeysObject* keys = &shared_keys->dsk_keys;
7476
278k
    init_keys_object(keys, NEXT_LOG2_SHARED_KEYS_MAX_SIZE, log2_bytes, DICT_KEYS_SPLIT,
7477
278k
                     SHARED_KEYS_MAX_SIZE, sizeof(PyDictUnicodeEntry));
7478
278k
    assert(keys->dk_nentries == 0);
7479
    /* Set to max size+1 as it will shrink by one before each new object */
7480
278k
    if (cls->ht_type.tp_dict) {
7481
278k
        PyObject *attrs = PyDict_GetItem(cls->ht_type.tp_dict, &_Py_ID(__static_attributes__));
7482
278k
        if (attrs != NULL && PyTuple_Check(attrs)) {
7483
20.6k
            for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(attrs); i++) {
7484
12.1k
                PyObject *key = PyTuple_GET_ITEM(attrs, i);
7485
12.1k
                Py_hash_t hash;
7486
12.1k
                if (PyUnicode_CheckExact(key) && (hash = unicode_get_hash(key)) != -1) {
7487
                    /* An attribute stored in a slot never uses the dict. */
7488
12.1k
                    PyObject *descr = _PyType_Lookup((PyTypeObject *)cls, key);
7489
12.1k
                    if (descr != NULL && Py_IS_TYPE(descr, &PyMemberDescr_Type)) {
7490
226
                        continue;
7491
226
                    }
7492
11.9k
                    if (insert_split_key(keys, key, hash) == DKIX_EMPTY) {
7493
8
                        break;
7494
8
                    }
7495
11.9k
                }
7496
12.1k
            }
7497
8.52k
        }
7498
278k
    }
7499
278k
    return keys;
7500
278k
}
7501
7502
void
7503
_PyDict_RemoveKeysForClass(PyHeapTypeObject *cls)
7504
267k
{
7505
267k
    struct _instancekeysobject *shared_keys = _PyDictKeys_AsSharedKeys(cls->ht_cached_keys);
7506
267k
    FT_ATOMIC_STORE_PTR_RELEASE(shared_keys->dsk_owning_type, NULL);
7507
7508
267k
    _PyDictKeys_DecRef(cls->ht_cached_keys);
7509
267k
}
7510
7511
void
7512
_PyObject_InitInlineValues(PyObject *obj, PyTypeObject *tp)
7513
37.0M
{
7514
37.0M
    assert(tp->tp_flags & Py_TPFLAGS_HEAPTYPE);
7515
37.0M
    assert(tp->tp_flags & Py_TPFLAGS_INLINE_VALUES);
7516
37.0M
    assert(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
7517
37.0M
    PyDictKeysObject *keys = CACHED_KEYS(tp);
7518
37.0M
    assert(keys != NULL);
7519
37.0M
    OBJECT_STAT_INC(inline_values);
7520
#ifdef Py_GIL_DISABLED
7521
    Py_ssize_t usable = _Py_atomic_load_ssize_relaxed(&keys->dk_usable);
7522
    if (usable > 1) {
7523
        LOCK_KEYS(keys);
7524
        if (keys->dk_usable > 1) {
7525
            _Py_atomic_store_ssize(&keys->dk_usable, keys->dk_usable - 1);
7526
        }
7527
        UNLOCK_KEYS(keys);
7528
    }
7529
#else
7530
37.0M
    if (keys->dk_usable > 1) {
7531
286k
        keys->dk_usable--;
7532
286k
    }
7533
37.0M
#endif
7534
37.0M
    size_t size = shared_keys_usable_size(keys);
7535
37.0M
    PyDictValues *values = _PyObject_InlineValues(obj);
7536
37.0M
    assert(size < 256);
7537
37.0M
    values->capacity = (uint8_t)size;
7538
37.0M
    values->size = 0;
7539
37.0M
    values->embedded = 1;
7540
37.0M
    values->valid = 1;
7541
232M
    for (size_t i = 0; i < size; i++) {
7542
195M
        values->values[i] = NULL;
7543
195M
    }
7544
37.0M
    _PyObject_ManagedDictPointer(obj)->dict = NULL;
7545
37.0M
}
7546
7547
static PyDictObject *
7548
make_dict_from_instance_attributes(PyDictKeysObject *keys, PyDictValues *values)
7549
726k
{
7550
726k
    dictkeys_incref(keys);
7551
726k
    Py_ssize_t used = 0;
7552
726k
    size_t size = shared_keys_usable_size(keys);
7553
3.67M
    for (size_t i = 0; i < size; i++) {
7554
2.94M
        PyObject *val = values->values[i];
7555
2.94M
        if (val != NULL) {
7556
1.79M
            used += 1;
7557
1.79M
        }
7558
2.94M
    }
7559
726k
    PyDictObject *res = (PyDictObject *)new_dict(keys, values, used, 0);
7560
726k
    return res;
7561
726k
}
7562
7563
PyDictObject *
7564
_PyObject_MaterializeManagedDict_LockHeld(PyObject *obj)
7565
84.1k
{
7566
84.1k
    ASSERT_WORLD_STOPPED_OR_OBJ_LOCKED(obj);
7567
7568
84.1k
    OBJECT_STAT_INC(dict_materialized_on_request);
7569
7570
84.1k
    PyDictValues *values = _PyObject_InlineValues(obj);
7571
84.1k
    PyDictObject *dict;
7572
84.1k
    if (values->valid) {
7573
84.1k
        PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
7574
84.1k
        dict = make_dict_from_instance_attributes(keys, values);
7575
84.1k
    }
7576
0
    else {
7577
0
        dict = (PyDictObject *)PyDict_New();
7578
0
    }
7579
84.1k
    FT_ATOMIC_STORE_PTR_RELEASE(_PyObject_ManagedDictPointer(obj)->dict,
7580
84.1k
                                dict);
7581
84.1k
    return dict;
7582
84.1k
}
7583
7584
PyDictObject *
7585
_PyObject_MaterializeManagedDict(PyObject *obj)
7586
156M
{
7587
156M
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
7588
156M
    if (dict != NULL) {
7589
156M
        return dict;
7590
156M
    }
7591
7592
84.1k
    Py_BEGIN_CRITICAL_SECTION(obj);
7593
7594
#ifdef Py_GIL_DISABLED
7595
    dict = _PyObject_GetManagedDict(obj);
7596
    if (dict != NULL) {
7597
        // We raced with another thread creating the dict
7598
        goto exit;
7599
    }
7600
#endif
7601
84.1k
    dict = _PyObject_MaterializeManagedDict_LockHeld(obj);
7602
7603
#ifdef Py_GIL_DISABLED
7604
exit:
7605
#endif
7606
84.1k
    Py_END_CRITICAL_SECTION();
7607
84.1k
    return dict;
7608
156M
}
7609
7610
int
7611
_PyDict_SetItem_LockHeld(PyDictObject *dict, PyObject *name, PyObject *value)
7612
82.3M
{
7613
82.3M
    if (!PyDict_Check(dict)) {
7614
0
        if (PyFrozenDict_Check(dict)) {
7615
0
            if (value == NULL) {
7616
0
                frozendict_does_not_support("deletion");
7617
0
            }
7618
0
            else {
7619
0
                frozendict_does_not_support("assignment");
7620
0
            }
7621
0
        }
7622
0
        else {
7623
0
            PyErr_BadInternalCall();
7624
0
        }
7625
0
        return -1;
7626
0
    }
7627
7628
82.3M
    if (value == NULL) {
7629
15.3k
        Py_hash_t hash = _PyObject_HashDictKey(name);
7630
15.3k
        if (hash == -1) {
7631
0
            dict_unhashable_type((PyObject*)dict, name);
7632
0
            return -1;
7633
0
        }
7634
15.3k
        return _PyDict_DelItem_KnownHash_LockHeld((PyObject *)dict, name, hash);
7635
82.2M
    } else {
7636
82.2M
        return setitem_lock_held(dict, name, value);
7637
82.2M
    }
7638
82.3M
}
7639
7640
// Called with either the object's lock or the dict's lock held
7641
// depending on whether or not a dict has been materialized for
7642
// the object.
7643
static int
7644
store_instance_attr_lock_held(PyObject *obj, PyDictValues *values,
7645
                              PyObject *name, PyObject *value)
7646
17.8M
{
7647
17.8M
    PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
7648
17.8M
    assert(keys != NULL);
7649
17.8M
    assert(values != NULL);
7650
17.8M
    assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES);
7651
17.8M
    Py_ssize_t ix = DKIX_EMPTY;
7652
17.8M
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
7653
17.8M
    assert(dict == NULL || ((PyDictObject *)dict)->ma_values == values);
7654
17.8M
    if (PyUnicode_CheckExact(name)) {
7655
17.8M
        Py_hash_t hash = unicode_get_hash(name);
7656
17.8M
        if (hash == -1) {
7657
0
            hash = PyUnicode_Type.tp_hash(name);
7658
0
            assert(hash != -1);
7659
0
        }
7660
7661
17.8M
        ix = insert_split_key(keys, name, hash);
7662
7663
#ifdef Py_STATS
7664
        if (ix == DKIX_EMPTY) {
7665
            if (PyUnicode_CheckExact(name)) {
7666
                if (shared_keys_usable_size(keys) == SHARED_KEYS_MAX_SIZE) {
7667
                    OBJECT_STAT_INC(dict_materialized_too_big);
7668
                }
7669
                else {
7670
                    OBJECT_STAT_INC(dict_materialized_new_key);
7671
                }
7672
            }
7673
            else {
7674
                OBJECT_STAT_INC(dict_materialized_str_subclass);
7675
            }
7676
        }
7677
#endif
7678
17.8M
    }
7679
7680
17.8M
    if (ix == DKIX_EMPTY) {
7681
649k
        int res;
7682
649k
        if (dict == NULL) {
7683
            // Make the dict but don't publish it in the object
7684
            // so that no one else will see it.
7685
642k
            dict = make_dict_from_instance_attributes(keys, values);
7686
642k
            if (dict == NULL ||
7687
642k
                _PyDict_SetItem_LockHeld(dict, name, value) < 0) {
7688
0
                Py_XDECREF(dict);
7689
0
                return -1;
7690
0
            }
7691
7692
642k
            FT_ATOMIC_STORE_PTR_RELEASE(_PyObject_ManagedDictPointer(obj)->dict,
7693
642k
                                        (PyDictObject *)dict);
7694
642k
            return 0;
7695
642k
        }
7696
7697
6.62k
        _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(dict);
7698
7699
6.62k
        res = _PyDict_SetItem_LockHeld(dict, name, value);
7700
6.62k
        return res;
7701
649k
    }
7702
7703
17.2M
    PyObject *old_value = values->values[ix];
7704
17.2M
    if (old_value == NULL && value == NULL) {
7705
0
        PyErr_Format(PyExc_AttributeError,
7706
0
                        "'%.100s' object has no attribute '%U'",
7707
0
                        Py_TYPE(obj)->tp_name, name);
7708
0
        (void)_PyObject_SetAttributeErrorContext(obj, name);
7709
0
        return -1;
7710
0
    }
7711
7712
17.2M
    if (dict) {
7713
288k
        PyDict_WatchEvent event = (old_value == NULL ? PyDict_EVENT_ADDED :
7714
288k
                                   value == NULL ? PyDict_EVENT_DELETED :
7715
55.4k
                                   PyDict_EVENT_MODIFIED);
7716
288k
        _PyDict_NotifyEvent(event, dict, name, value);
7717
288k
    }
7718
7719
17.2M
    FT_ATOMIC_STORE_PTR_RELEASE(values->values[ix], Py_XNewRef(value));
7720
7721
17.2M
    if (old_value == NULL) {
7722
16.6M
        _PyDictValues_AddToInsertionOrder(values, ix);
7723
16.6M
        if (dict) {
7724
232k
            assert(dict->ma_values == values);
7725
232k
            STORE_USED(dict, dict->ma_used + 1);
7726
232k
        }
7727
16.6M
    }
7728
555k
    else {
7729
555k
        if (value == NULL) {
7730
432k
            delete_index_from_values(values, ix);
7731
432k
            if (dict) {
7732
0
                assert(dict->ma_values == values);
7733
0
                STORE_USED(dict, dict->ma_used - 1);
7734
0
            }
7735
432k
        }
7736
555k
        Py_DECREF(old_value);
7737
555k
    }
7738
17.2M
    return 0;
7739
17.2M
}
7740
7741
static inline int
7742
store_instance_attr_dict(PyObject *obj, PyDictObject *dict, PyObject *name, PyObject *value)
7743
48.2M
{
7744
48.2M
    PyDictValues *values = _PyObject_InlineValues(obj);
7745
48.2M
    int res;
7746
48.2M
    Py_BEGIN_CRITICAL_SECTION(dict);
7747
48.2M
    if (dict->ma_values == values) {
7748
0
        res = store_instance_attr_lock_held(obj, values, name, value);
7749
0
    }
7750
48.2M
    else {
7751
48.2M
        res = _PyDict_SetItem_LockHeld(dict, name, value);
7752
48.2M
    }
7753
48.2M
    Py_END_CRITICAL_SECTION();
7754
48.2M
    return res;
7755
48.2M
}
7756
7757
int
7758
_PyObject_StoreInstanceAttribute(PyObject *obj, PyObject *name, PyObject *value)
7759
66.1M
{
7760
66.1M
    PyDictValues *values = _PyObject_InlineValues(obj);
7761
66.1M
    if (!FT_ATOMIC_LOAD_UINT8(values->valid)) {
7762
48.2M
        PyDictObject *dict;
7763
48.2M
        int res;
7764
#ifdef Py_GIL_DISABLED
7765
        Py_BEGIN_CRITICAL_SECTION(obj);
7766
#endif
7767
48.2M
        dict = _PyObject_GetManagedDict(obj);
7768
48.2M
        Py_XINCREF(dict);
7769
#ifdef Py_GIL_DISABLED
7770
        Py_END_CRITICAL_SECTION();
7771
#endif
7772
48.2M
        if (dict == NULL) {
7773
0
            dict = (PyDictObject *)PyObject_GenericGetDict(obj, NULL);
7774
0
            if (dict == NULL) {
7775
0
                return -1;
7776
0
            }
7777
0
        }
7778
48.2M
        res = store_instance_attr_dict(obj, dict, name, value);
7779
48.2M
        Py_DECREF(dict);
7780
48.2M
        return res;
7781
48.2M
    }
7782
7783
#ifdef Py_GIL_DISABLED
7784
    // We have a valid inline values, at least for now...  There are two potential
7785
    // races with having the values become invalid.  One is the dictionary
7786
    // being detached from the object.  The other is if someone is inserting
7787
    // into the dictionary directly and therefore causing it to resize.
7788
    //
7789
    // If we haven't materialized the dictionary yet we lock on the object, which
7790
    // will also be used to prevent the dictionary from being materialized while
7791
    // we're doing the insertion.  If we race and the dictionary gets created
7792
    // then we'll need to release the object lock and lock the dictionary to
7793
    // prevent resizing.
7794
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
7795
    if (dict == NULL) {
7796
        int res;
7797
        Py_BEGIN_CRITICAL_SECTION(obj);
7798
        dict = _PyObject_GetManagedDict(obj);
7799
7800
        if (dict == NULL) {
7801
            res = store_instance_attr_lock_held(obj, values, name, value);
7802
        }
7803
        Py_END_CRITICAL_SECTION();
7804
7805
        if (dict == NULL) {
7806
            return res;
7807
        }
7808
    }
7809
    return store_instance_attr_dict(obj, dict, name, value);
7810
#else
7811
17.8M
    return store_instance_attr_lock_held(obj, values, name, value);
7812
66.1M
#endif
7813
66.1M
}
7814
7815
/* Sanity check for managed dicts */
7816
#if 0
7817
#define CHECK(val) assert(val); if (!(val)) { return 0; }
7818
7819
int
7820
_PyObject_ManagedDictValidityCheck(PyObject *obj)
7821
{
7822
    PyTypeObject *tp = Py_TYPE(obj);
7823
    CHECK(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
7824
    PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer(obj);
7825
    if (_PyManagedDictPointer_IsValues(*managed_dict)) {
7826
        PyDictValues *values = _PyManagedDictPointer_GetValues(*managed_dict);
7827
        int size = ((uint8_t *)values)[-2];
7828
        int count = 0;
7829
        PyDictKeysObject *keys = CACHED_KEYS(tp);
7830
        for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
7831
            if (values->values[i] != NULL) {
7832
                count++;
7833
            }
7834
        }
7835
        CHECK(size == count);
7836
    }
7837
    else {
7838
        if (managed_dict->dict != NULL) {
7839
            CHECK(PyDict_Check(managed_dict->dict));
7840
        }
7841
    }
7842
    return 1;
7843
}
7844
#endif
7845
7846
// Attempts to get an instance attribute from the inline values. Returns true
7847
// if successful, or false if the caller needs to lookup in the dictionary.
7848
bool
7849
_PyObject_TryGetInstanceAttribute(PyObject *obj, PyObject *name, PyObject **attr)
7850
277M
{
7851
277M
    assert(PyUnicode_CheckExact(name));
7852
277M
    PyDictValues *values = _PyObject_InlineValues(obj);
7853
277M
    if (!FT_ATOMIC_LOAD_UINT8(values->valid)) {
7854
202M
        return false;
7855
202M
    }
7856
7857
75.5M
    PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
7858
75.5M
    assert(keys != NULL);
7859
75.5M
    Py_ssize_t ix = _PyDictKeys_StringLookupSplit(keys, name);
7860
75.5M
    if (ix == DKIX_EMPTY) {
7861
31.4M
        *attr = NULL;
7862
31.4M
        return true;
7863
31.4M
    }
7864
7865
#ifdef Py_GIL_DISABLED
7866
    PyObject *value = _Py_atomic_load_ptr_acquire(&values->values[ix]);
7867
    if (value == NULL) {
7868
        if (FT_ATOMIC_LOAD_UINT8(values->valid)) {
7869
            *attr = NULL;
7870
            return true;
7871
        }
7872
    }
7873
    else if (_Py_TryIncrefCompare(&values->values[ix], value)) {
7874
        *attr = value;
7875
        return true;
7876
    }
7877
7878
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
7879
    if (dict == NULL) {
7880
        // No dict, lock the object to prevent one from being
7881
        // materialized...
7882
        bool success = false;
7883
        Py_BEGIN_CRITICAL_SECTION(obj);
7884
7885
        dict = _PyObject_GetManagedDict(obj);
7886
        if (dict == NULL) {
7887
            // Still no dict, we can read from the values
7888
            assert(values->valid);
7889
            value = values->values[ix];
7890
            *attr = _Py_XNewRefWithLock(value);
7891
            success = true;
7892
        }
7893
7894
        Py_END_CRITICAL_SECTION();
7895
7896
        if (success) {
7897
            return true;
7898
        }
7899
    }
7900
7901
    // We have a dictionary, we'll need to lock it to prevent
7902
    // the values from being resized.
7903
    assert(dict != NULL);
7904
7905
    bool success;
7906
    Py_BEGIN_CRITICAL_SECTION(dict);
7907
7908
    if (dict->ma_values == values && FT_ATOMIC_LOAD_UINT8(values->valid)) {
7909
        value = _Py_atomic_load_ptr_consume(&values->values[ix]);
7910
        *attr = _Py_XNewRefWithLock(value);
7911
        success = true;
7912
    } else {
7913
        // Caller needs to lookup from the dictionary
7914
        success = false;
7915
    }
7916
7917
    Py_END_CRITICAL_SECTION();
7918
7919
    return success;
7920
#else
7921
44.1M
    PyObject *value = values->values[ix];
7922
44.1M
    *attr = Py_XNewRef(value);
7923
44.1M
    return true;
7924
75.5M
#endif
7925
75.5M
}
7926
7927
int
7928
_PyObject_IsInstanceDictEmpty(PyObject *obj)
7929
6.20k
{
7930
6.20k
    PyTypeObject *tp = Py_TYPE(obj);
7931
6.20k
    if (tp->tp_dictoffset == 0) {
7932
6.20k
        return 1;
7933
6.20k
    }
7934
0
    PyDictObject *dict;
7935
0
    if (tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
7936
0
        PyDictValues *values = _PyObject_InlineValues(obj);
7937
0
        if (FT_ATOMIC_LOAD_UINT8(values->valid)) {
7938
0
            PyDictKeysObject *keys = CACHED_KEYS(tp);
7939
0
            for (Py_ssize_t i = 0; i < LOAD_KEYS_NENTRIES(keys); i++) {
7940
0
                if (FT_ATOMIC_LOAD_PTR_RELAXED(values->values[i]) != NULL) {
7941
0
                    return 0;
7942
0
                }
7943
0
            }
7944
0
            return 1;
7945
0
        }
7946
0
        dict = _PyObject_GetManagedDict(obj);
7947
0
    }
7948
0
    else if (tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
7949
0
        dict = _PyObject_GetManagedDict(obj);
7950
0
    }
7951
0
    else {
7952
0
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
7953
0
        dict = (PyDictObject *)*dictptr;
7954
0
    }
7955
0
    if (dict == NULL) {
7956
0
        return 1;
7957
0
    }
7958
0
    return GET_USED((PyDictObject *)dict) == 0;
7959
0
}
7960
7961
int
7962
PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)
7963
81.7M
{
7964
81.7M
    PyTypeObject *tp = Py_TYPE(obj);
7965
81.7M
    if((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
7966
0
        return 0;
7967
0
    }
7968
81.7M
    PyDictObject *dict = _PyObject_ManagedDictPointer(obj)->dict;
7969
81.7M
    if (dict != NULL) {
7970
        // GH-130327: If there's a managed dictionary available, we should
7971
        // *always* traverse it. The dict is responsible for traversing the
7972
        // inline values if it points to them.
7973
1.50M
        Py_VISIT(dict);
7974
1.50M
    }
7975
80.2M
    else if (tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
7976
80.2M
        PyDictValues *values = _PyObject_InlineValues(obj);
7977
80.2M
        if (values->valid) {
7978
568M
            for (Py_ssize_t i = 0; i < values->capacity; i++) {
7979
488M
                Py_VISIT(values->values[i]);
7980
488M
            }
7981
80.2M
        }
7982
80.2M
    }
7983
81.7M
    return 0;
7984
81.7M
}
7985
7986
static void
7987
clear_inline_values(PyDictValues *values)
7988
36.9M
{
7989
36.9M
    if (values->valid) {
7990
36.2M
        FT_ATOMIC_STORE_UINT8(values->valid, 0);
7991
228M
        for (Py_ssize_t i = 0; i < values->capacity; i++) {
7992
192M
            PyObject *value = values->values[i];
7993
            // The attribute read fast-path may read these without holding the
7994
            // per-object lock.
7995
192M
            FT_ATOMIC_STORE_PTR_RELEASE(values->values[i], NULL);
7996
192M
            Py_XDECREF(value);
7997
192M
        }
7998
36.2M
    }
7999
36.9M
}
8000
8001
static void
8002
set_dict_inline_values(PyObject *obj, PyDictObject *new_dict)
8003
0
{
8004
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(obj);
8005
8006
0
    PyDictValues *values = _PyObject_InlineValues(obj);
8007
8008
0
    Py_XINCREF(new_dict);
8009
0
    FT_ATOMIC_STORE_PTR(_PyObject_ManagedDictPointer(obj)->dict, new_dict);
8010
8011
0
    clear_inline_values(values);
8012
0
}
8013
8014
#ifdef Py_GIL_DISABLED
8015
8016
// Trys and sets the dictionary for an object in the easy case when our current
8017
// dictionary is either completely not materialized or is a dictionary which
8018
// does not point at the inline values.
8019
static bool
8020
try_set_dict_inline_only_or_other_dict(PyObject *obj, PyObject *new_dict, PyDictObject **cur_dict)
8021
{
8022
    bool replaced = false;
8023
    Py_BEGIN_CRITICAL_SECTION(obj);
8024
8025
    PyDictObject *dict = *cur_dict = _PyObject_GetManagedDict(obj);
8026
    if (dict == NULL) {
8027
        // We only have inline values, we can just completely replace them.
8028
        set_dict_inline_values(obj, (PyDictObject *)new_dict);
8029
        replaced = true;
8030
        goto exit_lock;
8031
    }
8032
8033
    if (FT_ATOMIC_LOAD_PTR_RELAXED(dict->ma_values) != _PyObject_InlineValues(obj)) {
8034
        // We have a materialized dict which doesn't point at the inline values,
8035
        // We get to simply swap dictionaries and free the old dictionary.
8036
        FT_ATOMIC_STORE_PTR(_PyObject_ManagedDictPointer(obj)->dict,
8037
                            (PyDictObject *)Py_XNewRef(new_dict));
8038
        replaced = true;
8039
        goto exit_lock;
8040
    }
8041
    else {
8042
        // We have inline values, we need to lock the dict and the object
8043
        // at the same time to safely dematerialize them. To do that while releasing
8044
        // the object lock we need a strong reference to the current dictionary.
8045
        Py_INCREF(dict);
8046
    }
8047
exit_lock:
8048
    Py_END_CRITICAL_SECTION();
8049
    return replaced;
8050
}
8051
8052
// Replaces a dictionary that is probably the dictionary which has been
8053
// materialized and points at the inline values. We could have raced
8054
// and replaced it with another dictionary though.
8055
static int
8056
replace_dict_probably_inline_materialized(PyObject *obj, PyDictObject *inline_dict,
8057
                                          PyDictObject *cur_dict, PyObject *new_dict)
8058
{
8059
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(obj);
8060
8061
    if (cur_dict == inline_dict) {
8062
        assert(FT_ATOMIC_LOAD_PTR_RELAXED(inline_dict->ma_values) == _PyObject_InlineValues(obj));
8063
8064
        int err = _PyDict_DetachFromObject(inline_dict, obj);
8065
        if (err != 0) {
8066
            assert(new_dict == NULL);
8067
            return err;
8068
        }
8069
    }
8070
8071
    FT_ATOMIC_STORE_PTR(_PyObject_ManagedDictPointer(obj)->dict,
8072
                        (PyDictObject *)Py_XNewRef(new_dict));
8073
    return 0;
8074
}
8075
8076
#endif
8077
8078
static void
8079
decref_maybe_delay(PyObject *obj, bool delay)
8080
0
{
8081
0
    if (delay) {
8082
0
        _PyObject_XDecRefDelayed(obj);
8083
0
    }
8084
0
    else {
8085
0
        Py_XDECREF(obj);
8086
0
    }
8087
0
}
8088
8089
int
8090
_PyObject_SetManagedDict(PyObject *obj, PyObject *new_dict)
8091
0
{
8092
0
    assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
8093
#ifndef NDEBUG
8094
    Py_BEGIN_CRITICAL_SECTION(obj);
8095
    assert(_PyObject_InlineValuesConsistencyCheck(obj));
8096
    Py_END_CRITICAL_SECTION();
8097
#endif
8098
0
    int err = 0;
8099
0
    PyTypeObject *tp = Py_TYPE(obj);
8100
0
    if (tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
8101
#ifdef Py_GIL_DISABLED
8102
        PyDictObject *prev_dict;
8103
        if (!try_set_dict_inline_only_or_other_dict(obj, new_dict, &prev_dict)) {
8104
            // We had a materialized dictionary which pointed at the inline
8105
            // values. We need to lock both the object and the dict at the
8106
            // same time to safely replace it. We can't merely lock the dictionary
8107
            // while the object is locked because it could suspend the object lock.
8108
            PyDictObject *cur_dict;
8109
8110
            assert(prev_dict != NULL);
8111
            Py_BEGIN_CRITICAL_SECTION2(obj, prev_dict);
8112
8113
            // We could have had another thread race in between the call to
8114
            // try_set_dict_inline_only_or_other_dict where we locked the object
8115
            // and when we unlocked and re-locked the dictionary.
8116
            cur_dict = _PyObject_GetManagedDict(obj);
8117
8118
            err = replace_dict_probably_inline_materialized(obj, prev_dict,
8119
                                                            cur_dict, new_dict);
8120
8121
            Py_END_CRITICAL_SECTION2();
8122
8123
            // Decref for the dictionary we incref'd in try_set_dict_inline_only_or_other_dict
8124
            // while the object was locked
8125
            decref_maybe_delay((PyObject *)prev_dict, prev_dict != cur_dict);
8126
            if (err != 0) {
8127
                return err;
8128
            }
8129
8130
            prev_dict = cur_dict;
8131
        }
8132
8133
        if (prev_dict != NULL) {
8134
            // decref for the dictionary that we replaced
8135
            decref_maybe_delay((PyObject *)prev_dict, true);
8136
        }
8137
8138
        return 0;
8139
#else
8140
0
        PyDictObject *dict = _PyObject_GetManagedDict(obj);
8141
0
        if (dict == NULL) {
8142
0
            set_dict_inline_values(obj, (PyDictObject *)new_dict);
8143
0
            return 0;
8144
0
        }
8145
0
        if (_PyDict_DetachFromObject(dict, obj) == 0) {
8146
0
            _PyObject_ManagedDictPointer(obj)->dict = (PyDictObject *)Py_XNewRef(new_dict);
8147
0
            Py_DECREF(dict);
8148
0
            return 0;
8149
0
        }
8150
0
        assert(new_dict == NULL);
8151
0
        return -1;
8152
0
#endif
8153
0
    }
8154
0
    else {
8155
0
        PyDictObject *dict;
8156
8157
0
        Py_BEGIN_CRITICAL_SECTION(obj);
8158
8159
0
        dict = _PyObject_ManagedDictPointer(obj)->dict;
8160
8161
0
        FT_ATOMIC_STORE_PTR(_PyObject_ManagedDictPointer(obj)->dict,
8162
0
                            (PyDictObject *)Py_XNewRef(new_dict));
8163
8164
0
        Py_END_CRITICAL_SECTION();
8165
0
        decref_maybe_delay((PyObject *)dict, true);
8166
0
    }
8167
0
    assert(_PyObject_InlineValuesConsistencyCheck(obj));
8168
0
    return err;
8169
0
}
8170
8171
static int
8172
detach_dict_from_object(PyDictObject *mp, PyObject *obj)
8173
77.2k
{
8174
77.2k
    assert(_PyObject_ManagedDictPointer(obj)->dict == mp);
8175
77.2k
    assert(_PyObject_InlineValuesConsistencyCheck(obj));
8176
8177
77.2k
    if (FT_ATOMIC_LOAD_PTR_RELAXED(mp->ma_values) != _PyObject_InlineValues(obj)) {
8178
0
        return 0;
8179
0
    }
8180
8181
    // We could be called with an unlocked dict when the caller knows the
8182
    // values are already detached, so we assert after inline values check.
8183
77.2k
    ASSERT_WORLD_STOPPED_OR_OBJ_LOCKED(mp);
8184
77.2k
    assert(mp->ma_values->embedded == 1);
8185
77.2k
    assert(mp->ma_values->valid == 1);
8186
77.2k
    assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES);
8187
8188
77.2k
    PyDictValues *values = copy_values(mp->ma_values);
8189
8190
77.2k
    if (values == NULL) {
8191
0
        PyErr_NoMemory();
8192
0
        return -1;
8193
0
    }
8194
77.2k
    mp->ma_values = values;
8195
8196
77.2k
    invalidate_and_clear_inline_values(_PyObject_InlineValues(obj));
8197
8198
77.2k
    assert(_PyObject_InlineValuesConsistencyCheck(obj));
8199
77.2k
    ASSERT_CONSISTENT(mp);
8200
77.2k
    return 0;
8201
77.2k
}
8202
8203
8204
void
8205
PyObject_ClearManagedDict(PyObject *obj)
8206
37.6M
{
8207
    // This is called when the object is being freed or cleared
8208
    // by the GC and therefore known to have no references.
8209
37.6M
    if (Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
8210
37.6M
        PyDictObject *dict = _PyObject_GetManagedDict(obj);
8211
37.6M
        if (dict == NULL) {
8212
            // We have no materialized dictionary and inline values
8213
            // that just need to be cleared.
8214
            // No dict to clear, we're done
8215
36.9M
            clear_inline_values(_PyObject_InlineValues(obj));
8216
36.9M
            return;
8217
36.9M
        }
8218
726k
        if (FT_ATOMIC_LOAD_PTR_ACQUIRE(dict->ma_values) ==
8219
726k
                    _PyObject_InlineValues(obj)) {
8220
            // We have a materialized object which points at the inline
8221
            // values. We need to materialize the keys. Nothing can modify
8222
            // this object, but we need to lock the dictionary.
8223
77.2k
            int err;
8224
77.2k
            Py_BEGIN_CRITICAL_SECTION(dict);
8225
77.2k
            err = detach_dict_from_object(dict, obj);
8226
77.2k
            Py_END_CRITICAL_SECTION();
8227
8228
77.2k
            if (err) {
8229
                /* Must be out of memory */
8230
0
                assert(PyErr_Occurred() == PyExc_MemoryError);
8231
0
                PyErr_FormatUnraisable("Exception ignored while "
8232
0
                                       "clearing an object managed dict");
8233
                /* Clear the dict */
8234
0
                Py_BEGIN_CRITICAL_SECTION(dict);
8235
0
                PyDictKeysObject *oldkeys = dict->ma_keys;
8236
0
                ensure_shared_on_resize(dict);
8237
0
                set_keys(dict, Py_EMPTY_KEYS);
8238
0
                dict->ma_values = NULL;
8239
0
                dictkeys_decref(oldkeys, IS_DICT_SHARED(dict));
8240
0
                STORE_USED(dict, 0);
8241
0
                clear_inline_values(_PyObject_InlineValues(obj));
8242
0
                Py_END_CRITICAL_SECTION();
8243
0
            }
8244
77.2k
        }
8245
726k
    }
8246
728k
    Py_CLEAR(_PyObject_ManagedDictPointer(obj)->dict);
8247
728k
}
8248
8249
int
8250
_PyDict_DetachFromObject(PyDictObject *mp, PyObject *obj)
8251
0
{
8252
0
    ASSERT_WORLD_STOPPED_OR_OBJ_LOCKED(obj);
8253
8254
0
    return detach_dict_from_object(mp, obj);
8255
0
}
8256
8257
static inline PyObject *
8258
ensure_managed_dict(PyObject *obj)
8259
1.08M
{
8260
1.08M
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
8261
1.08M
    if (dict == NULL) {
8262
84.1k
        PyTypeObject *tp = Py_TYPE(obj);
8263
84.1k
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
8264
84.1k
            FT_ATOMIC_LOAD_UINT8(_PyObject_InlineValues(obj)->valid)) {
8265
84.1k
            dict = _PyObject_MaterializeManagedDict(obj);
8266
84.1k
        }
8267
0
        else {
8268
#ifdef Py_GIL_DISABLED
8269
            // Check again that we're not racing with someone else creating the dict
8270
            Py_BEGIN_CRITICAL_SECTION(obj);
8271
            dict = _PyObject_GetManagedDict(obj);
8272
            if (dict != NULL) {
8273
                goto done;
8274
            }
8275
#endif
8276
0
            dict = (PyDictObject *)new_dict_with_shared_keys(CACHED_KEYS(tp));
8277
0
            FT_ATOMIC_STORE_PTR_RELEASE(_PyObject_ManagedDictPointer(obj)->dict,
8278
0
                                        (PyDictObject *)dict);
8279
8280
#ifdef Py_GIL_DISABLED
8281
done:
8282
            Py_END_CRITICAL_SECTION();
8283
#endif
8284
0
        }
8285
84.1k
    }
8286
1.08M
    return (PyObject *)dict;
8287
1.08M
}
8288
8289
static inline PyObject *
8290
ensure_nonmanaged_dict(PyObject *obj, PyObject **dictptr)
8291
33.3M
{
8292
33.3M
    PyDictKeysObject *cached;
8293
8294
33.3M
    PyObject *dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
8295
33.3M
    if (dict == NULL) {
8296
#ifdef Py_GIL_DISABLED
8297
        Py_BEGIN_CRITICAL_SECTION(obj);
8298
        dict = *dictptr;
8299
        if (dict != NULL) {
8300
            goto done;
8301
        }
8302
#endif
8303
13.4M
        PyTypeObject *tp = Py_TYPE(obj);
8304
13.4M
        if (_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
8305
7.62k
            assert(!_PyType_HasFeature(tp, Py_TPFLAGS_INLINE_VALUES));
8306
7.62k
            dict = new_dict_with_shared_keys(cached);
8307
7.62k
        }
8308
13.4M
        else {
8309
13.4M
            dict = PyDict_New();
8310
13.4M
        }
8311
13.4M
        FT_ATOMIC_STORE_PTR_RELEASE(*dictptr, dict);
8312
#ifdef Py_GIL_DISABLED
8313
done:
8314
        Py_END_CRITICAL_SECTION();
8315
#endif
8316
13.4M
    }
8317
33.3M
    return dict;
8318
33.3M
}
8319
8320
PyObject *
8321
PyObject_GenericGetDict(PyObject *obj, void *context)
8322
1.08M
{
8323
1.08M
    PyTypeObject *tp = Py_TYPE(obj);
8324
1.08M
    if (_PyType_HasFeature(tp, Py_TPFLAGS_MANAGED_DICT)) {
8325
1.08M
        return Py_XNewRef(ensure_managed_dict(obj));
8326
1.08M
    }
8327
2.17k
    else {
8328
2.17k
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
8329
2.17k
        if (dictptr == NULL) {
8330
0
            PyErr_SetString(PyExc_AttributeError,
8331
0
                            "This object has no __dict__");
8332
0
            return NULL;
8333
0
        }
8334
8335
2.17k
        return Py_XNewRef(ensure_nonmanaged_dict(obj, dictptr));
8336
2.17k
    }
8337
1.08M
}
8338
8339
int
8340
_PyObjectDict_SetItem(PyTypeObject *tp, PyObject *obj, PyObject **dictptr,
8341
                      PyObject *key, PyObject *value)
8342
33.3M
{
8343
33.3M
    PyObject *dict;
8344
33.3M
    int res;
8345
8346
33.3M
    assert(dictptr != NULL);
8347
33.3M
    dict = ensure_nonmanaged_dict(obj, dictptr);
8348
33.3M
    if (dict == NULL) {
8349
0
        return -1;
8350
0
    }
8351
8352
33.3M
    Py_BEGIN_CRITICAL_SECTION(dict);
8353
33.3M
    res = _PyDict_SetItem_LockHeld((PyDictObject *)dict, key, value);
8354
33.3M
    ASSERT_CONSISTENT(dict);
8355
33.3M
    Py_END_CRITICAL_SECTION();
8356
33.3M
    return res;
8357
33.3M
}
8358
8359
void
8360
_PyDictKeys_DecRef(PyDictKeysObject *keys)
8361
267k
{
8362
267k
    dictkeys_decref(keys, false);
8363
267k
}
8364
8365
static inline uint32_t
8366
get_next_dict_keys_version(PyInterpreterState *interp)
8367
14.4k
{
8368
#ifdef Py_GIL_DISABLED
8369
    uint32_t v;
8370
    do {
8371
        v = _Py_atomic_load_uint32_relaxed(
8372
            &interp->dict_state.next_keys_version);
8373
        if (v == 0) {
8374
            return 0;
8375
        }
8376
    } while (!_Py_atomic_compare_exchange_uint32(
8377
        &interp->dict_state.next_keys_version, &v, v + 1));
8378
#else
8379
14.4k
    if (interp->dict_state.next_keys_version == 0) {
8380
0
        return 0;
8381
0
    }
8382
14.4k
    uint32_t v = interp->dict_state.next_keys_version++;
8383
14.4k
#endif
8384
14.4k
    return v;
8385
14.4k
}
8386
8387
// In free-threaded builds the caller must ensure that the keys object is not
8388
// being mutated concurrently by another thread.
8389
uint32_t
8390
_PyDictKeys_GetVersionForCurrentState(PyInterpreterState *interp,
8391
                                      PyDictKeysObject *dictkeys)
8392
4.47M
{
8393
4.47M
    uint32_t dk_version = FT_ATOMIC_LOAD_UINT32_RELAXED(dictkeys->dk_version);
8394
4.47M
    if (dk_version != 0) {
8395
4.46M
        return dk_version;
8396
4.46M
    }
8397
14.4k
    dk_version = get_next_dict_keys_version(interp);
8398
14.4k
    FT_ATOMIC_STORE_UINT32_RELAXED(dictkeys->dk_version, dk_version);
8399
14.4k
    return dk_version;
8400
4.47M
}
8401
8402
uint32_t
8403
_PyDict_GetKeysVersionForCurrentState(PyInterpreterState *interp,
8404
                                      PyDictObject *dict)
8405
61.6k
{
8406
61.6k
    ASSERT_DICT_LOCKED((PyObject *) dict);
8407
61.6k
    uint32_t dk_version =
8408
61.6k
        _PyDictKeys_GetVersionForCurrentState(interp, dict->ma_keys);
8409
61.6k
    ensure_shared_on_keys_version_assignment(dict);
8410
61.6k
    return dk_version;
8411
61.6k
}
8412
8413
static inline int
8414
validate_watcher_id(PyInterpreterState *interp, int watcher_id)
8415
59.0k
{
8416
59.0k
    if (watcher_id < 0 || watcher_id >= DICT_MAX_WATCHERS) {
8417
0
        PyErr_Format(PyExc_ValueError, "Invalid dict watcher ID %d", watcher_id);
8418
0
        return -1;
8419
0
    }
8420
59.0k
    PyDict_WatchCallback cb = FT_ATOMIC_LOAD_PTR_RELAXED(
8421
59.0k
        interp->dict_state.watchers[watcher_id]);
8422
59.0k
    if (cb == NULL) {
8423
0
        PyErr_Format(PyExc_ValueError, "No dict watcher set for ID %d", watcher_id);
8424
0
        return -1;
8425
0
    }
8426
59.0k
    return 0;
8427
59.0k
}
8428
8429
// In free-threaded builds, Add/Clear serialize on watcher_mutex and publish
8430
// callbacks with release stores. SendEvent reads them lock-free using
8431
// acquire loads.
8432
8433
int
8434
PyDict_Watch(int watcher_id, PyObject* dict)
8435
59.0k
{
8436
59.0k
    if (!PyDict_Check(dict)) {
8437
0
        PyErr_SetString(PyExc_ValueError, "Cannot watch non-dictionary");
8438
0
        return -1;
8439
0
    }
8440
59.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
8441
59.0k
    if (validate_watcher_id(interp, watcher_id)) {
8442
0
        return -1;
8443
0
    }
8444
59.0k
    FT_ATOMIC_OR_UINT64(((PyDictObject*)dict)->_ma_watcher_tag,
8445
59.0k
                        1ULL << watcher_id);
8446
59.0k
    return 0;
8447
59.0k
}
8448
8449
int
8450
PyDict_Unwatch(int watcher_id, PyObject* dict)
8451
0
{
8452
0
    if (!PyDict_Check(dict)) {
8453
0
        PyErr_SetString(PyExc_ValueError, "Cannot watch non-dictionary");
8454
0
        return -1;
8455
0
    }
8456
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
8457
0
    if (validate_watcher_id(interp, watcher_id)) {
8458
0
        return -1;
8459
0
    }
8460
0
    FT_ATOMIC_AND_UINT64(((PyDictObject*)dict)->_ma_watcher_tag,
8461
0
                         ~(1ULL << watcher_id));
8462
0
    return 0;
8463
0
}
8464
8465
int
8466
PyDict_AddWatcher(PyDict_WatchCallback callback)
8467
0
{
8468
0
    int watcher_id = -1;
8469
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
8470
8471
0
    FT_MUTEX_LOCK_FLAGS(&interp->dict_state.watcher_mutex,
8472
0
                        _Py_LOCK_DONT_DETACH);
8473
    /* Some watchers are reserved for CPython, start at the first available one */
8474
0
    for (int i = FIRST_AVAILABLE_WATCHER; i < DICT_MAX_WATCHERS; i++) {
8475
0
        if (!interp->dict_state.watchers[i]) {
8476
0
            FT_ATOMIC_STORE_PTR_RELEASE(interp->dict_state.watchers[i], callback);
8477
0
            watcher_id = i;
8478
0
            goto done;
8479
0
        }
8480
0
    }
8481
0
    PyErr_SetString(PyExc_RuntimeError, "no more dict watcher IDs available");
8482
0
done:
8483
0
    FT_MUTEX_UNLOCK(&interp->dict_state.watcher_mutex);
8484
0
    return watcher_id;
8485
0
}
8486
8487
int
8488
PyDict_ClearWatcher(int watcher_id)
8489
0
{
8490
0
    int res = 0;
8491
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
8492
0
    FT_MUTEX_LOCK_FLAGS(&interp->dict_state.watcher_mutex,
8493
0
                        _Py_LOCK_DONT_DETACH);
8494
0
    if (validate_watcher_id(interp, watcher_id)) {
8495
0
        res = -1;
8496
0
        goto done;
8497
0
    }
8498
0
    FT_ATOMIC_STORE_PTR_RELEASE(interp->dict_state.watchers[watcher_id], NULL);
8499
0
done:
8500
0
    FT_MUTEX_UNLOCK(&interp->dict_state.watcher_mutex);
8501
0
    return res;
8502
0
}
8503
8504
static const char *
8505
0
dict_event_name(PyDict_WatchEvent event) {
8506
0
    switch (event) {
8507
0
        #define CASE(op)                \
8508
0
        case PyDict_EVENT_##op:         \
8509
0
            return "PyDict_EVENT_" #op;
8510
0
        PY_FOREACH_DICT_EVENT(CASE)
8511
0
        #undef CASE
8512
0
    }
8513
0
    Py_UNREACHABLE();
8514
0
}
8515
8516
void
8517
_PyDict_SendEvent(int watcher_bits,
8518
                  PyDict_WatchEvent event,
8519
                  PyDictObject *mp,
8520
                  PyObject *key,
8521
                  PyObject *value)
8522
235k
{
8523
235k
    PyInterpreterState *interp = _PyInterpreterState_GET();
8524
2.11M
    for (int i = 0; i < DICT_MAX_WATCHERS; i++) {
8525
1.88M
        if (watcher_bits & 1) {
8526
235k
            PyDict_WatchCallback cb = FT_ATOMIC_LOAD_PTR_ACQUIRE(
8527
235k
                interp->dict_state.watchers[i]);
8528
235k
            if (cb && (cb(event, (PyObject*)mp, key, value) < 0)) {
8529
                // We don't want to resurrect the dict by potentially having an
8530
                // unraisablehook keep a reference to it, so we don't pass the
8531
                // dict as context, just an informative string message.  Dict
8532
                // repr can call arbitrary code, so we invent a simpler version.
8533
0
                PyErr_FormatUnraisable(
8534
0
                    "Exception ignored in %s watcher callback for <dict at %p>",
8535
0
                    dict_event_name(event), mp);
8536
0
            }
8537
235k
        }
8538
1.88M
        watcher_bits >>= 1;
8539
1.88M
    }
8540
235k
}
8541
8542
#ifndef NDEBUG
8543
static int
8544
_PyObject_InlineValuesConsistencyCheck(PyObject *obj)
8545
{
8546
    if ((Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES) == 0) {
8547
        return 1;
8548
    }
8549
    assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
8550
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
8551
    if (dict == NULL) {
8552
        return 1;
8553
    }
8554
    if (dict->ma_values == _PyObject_InlineValues(obj) ||
8555
        _PyObject_InlineValues(obj)->valid == 0) {
8556
        return 1;
8557
    }
8558
    assert(0);
8559
    return 0;
8560
}
8561
#endif
8562
8563
// --- frozendict implementation ---------------------------------------------
8564
8565
static PyObject *
8566
frozendict_getnewargs(PyObject *op, PyObject *Py_UNUSED(dummy))
8567
0
{
8568
    // Call dict(op): convert 'op' frozendict to a dict
8569
0
    PyObject *arg = PyObject_CallOneArg((PyObject*)&PyDict_Type, op);
8570
0
    if (arg == NULL) {
8571
0
        return NULL;
8572
0
    }
8573
0
    return Py_BuildValue("(N)", arg);
8574
0
}
8575
8576
8577
static PyNumberMethods frozendict_as_number = {
8578
    .nb_or = frozendict_or,
8579
};
8580
8581
static PyMappingMethods frozendict_as_mapping = {
8582
    .mp_length = frozendict_length,
8583
    .mp_subscript = _PyDict_Subscript,
8584
};
8585
8586
static PyMethodDef frozendict_methods[] = {
8587
    DICT___CONTAINS___METHODDEF
8588
    {"__getitem__", _PyDict_Subscript, METH_O | METH_COEXIST, getitem__doc__},
8589
    DICT___SIZEOF___METHODDEF
8590
    DICT_GET_METHODDEF
8591
    DICT_KEYS_METHODDEF
8592
    DICT_ITEMS_METHODDEF
8593
    DICT_VALUES_METHODDEF
8594
    DICT_FROMKEYS_METHODDEF
8595
    FROZENDICT_COPY_METHODDEF
8596
    DICT___REVERSED___METHODDEF
8597
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
8598
     PyDoc_STR("frozendicts are generic over two types, signifying (respectively) the types of the frozendict's keys and values")},
8599
    {"__getnewargs__", frozendict_getnewargs, METH_NOARGS},
8600
    {NULL,              NULL}   /* sentinel */
8601
};
8602
8603
8604
static PyObject *
8605
frozendict_repr(PyObject *self)
8606
0
{
8607
0
    PyDictObject *mp = _PyAnyDict_CAST(self);
8608
0
    if (mp->ma_used == 0) {
8609
0
        return PyUnicode_FromFormat("%s()", Py_TYPE(self)->tp_name);
8610
0
    }
8611
8612
0
    PyObject *repr = anydict_repr_impl(self);
8613
0
    if (repr == NULL) {
8614
0
        return NULL;
8615
0
    }
8616
0
    assert(PyUnicode_Check(repr));
8617
8618
0
    PyObject *res = PyUnicode_FromFormat("%s(%U)",
8619
0
                                         Py_TYPE(self)->tp_name,
8620
0
                                         repr);
8621
0
    Py_DECREF(repr);
8622
0
    return res;
8623
0
}
8624
8625
static Py_uhash_t
8626
_shuffle_bits(Py_uhash_t h)
8627
0
{
8628
0
    return ((h ^ 89869747UL) ^ (h << 16)) * 3644798167UL;
8629
0
}
8630
8631
// Compute hash((key, value)).
8632
// Code copied from tuple_hash().
8633
static Py_hash_t
8634
frozendict_pair_hash(Py_hash_t key_hash, PyObject *value)
8635
0
{
8636
0
    assert(key_hash != -1);
8637
8638
0
    const Py_ssize_t len = 2;
8639
0
    Py_uhash_t acc = _PyTuple_HASH_XXPRIME_5;
8640
8641
0
    Py_uhash_t lane = key_hash;
8642
0
    acc += lane * _PyTuple_HASH_XXPRIME_2;
8643
0
    acc = _PyTuple_HASH_XXROTATE(acc);
8644
0
    acc *= _PyTuple_HASH_XXPRIME_1;
8645
8646
0
    lane = PyObject_Hash(value);
8647
0
    if (lane == (Py_uhash_t)-1) {
8648
0
        return -1;
8649
0
    }
8650
0
    acc += lane * _PyTuple_HASH_XXPRIME_2;
8651
0
    acc = _PyTuple_HASH_XXROTATE(acc);
8652
0
    acc *= _PyTuple_HASH_XXPRIME_1;
8653
8654
    /* Add input length, mangled to keep the historical value of hash(()). */
8655
0
    acc += len ^ (_PyTuple_HASH_XXPRIME_5 ^ 3527539UL);
8656
8657
0
    if (acc == (Py_uhash_t)-1) {
8658
0
        acc = 1546275796;
8659
0
    }
8660
0
    return acc;
8661
0
}
8662
8663
8664
// Code copied from frozenset_hash()
8665
static Py_hash_t
8666
frozendict_hash(PyObject *op)
8667
0
{
8668
0
    PyFrozenDictObject *self = _PyFrozenDictObject_CAST(op);
8669
0
    Py_hash_t shash = FT_ATOMIC_LOAD_SSIZE_RELAXED(self->ma_hash);
8670
0
    if (shash != -1) {
8671
0
        return shash;
8672
0
    }
8673
8674
0
    PyDictObject *mp = _PyAnyDict_CAST(op);
8675
0
    Py_uhash_t hash = 0;
8676
8677
    /* Hashing a value recurses back into frozendict_hash() when that value
8678
       is itself a frozendict, so guard the descent to raise RecursionError
8679
       rather than overflow the C stack on a deeply nested frozendict.  Keys
8680
       are safe: their hashes are already computed at construction time. */
8681
0
    if (_Py_EnterRecursiveCall(" while hashing a frozendict")) {
8682
0
        return -1;
8683
0
    }
8684
8685
0
    PyObject *value;  // borrowed ref
8686
0
    Py_ssize_t pos = 0;
8687
0
    Py_hash_t key_hash;
8688
0
    while (_PyDict_Next(op, &pos, NULL, &value, &key_hash)) {
8689
0
        Py_hash_t pair_hash = frozendict_pair_hash(key_hash, value);
8690
0
        if (pair_hash == -1) {
8691
0
            _Py_LeaveRecursiveCall();
8692
0
            return -1;
8693
0
        }
8694
0
        hash ^= _shuffle_bits(pair_hash);
8695
0
    }
8696
0
    _Py_LeaveRecursiveCall();
8697
8698
    /* Factor in the number of active entries */
8699
0
    hash ^= ((Py_uhash_t)mp->ma_used + 1) * 1927868237UL;
8700
8701
    /* Disperse patterns arising in nested frozendicts */
8702
0
    hash ^= (hash >> 11) ^ (hash >> 25);
8703
0
    hash = hash * 69069U + 907133923UL;
8704
8705
    /* -1 is reserved as an error code */
8706
0
    if (hash == (Py_uhash_t)-1) {
8707
0
        hash = 590923713UL;
8708
0
    }
8709
8710
0
    FT_ATOMIC_STORE_SSIZE_RELAXED(self->ma_hash, (Py_hash_t)hash);
8711
0
    return (Py_hash_t)hash;
8712
0
}
8713
8714
8715
/* Allocate an empty, GC-untracked frozendict; the constructor tracks it once
8716
   fully built. */
8717
static PyObject *
8718
frozendict_new_untracked(PyTypeObject *type)
8719
233
{
8720
233
    assert(PyObject_IsSubclass((PyObject*)type, (PyObject*)&PyFrozenDict_Type));
8721
8722
233
    PyObject *d = anydict_new_untracked(type);
8723
233
    if (d == NULL) {
8724
0
        return NULL;
8725
0
    }
8726
233
    assert(can_modify_dict(_PyAnyDict_CAST(d)));
8727
233
    _PyFrozenDictObject_CAST(d)->ma_hash = -1;
8728
233
    return d;
8729
233
}
8730
8731
static PyObject *
8732
frozendict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
8733
0
{
8734
0
    PyObject *d = frozendict_new_untracked(type);
8735
0
    if (d == NULL) {
8736
0
        return NULL;
8737
0
    }
8738
8739
0
    if (args != NULL) {
8740
0
        if (dict_update_common(d, args, kwds, "frozendict") < 0) {
8741
0
            Py_DECREF(d);
8742
0
            return NULL;
8743
0
        }
8744
0
    }
8745
0
    else {
8746
0
        assert(kwds == NULL);
8747
0
    }
8748
8749
0
    _PyObject_GC_TRACK(d);
8750
0
    return d;
8751
0
}
8752
8753
static int
8754
transfer_keys_and_values_lock_held(PyObject *res, PyObject *dict)
8755
0
{
8756
0
    PyDictObject *new = (PyDictObject *)res;
8757
0
    PyDictObject *old = (PyDictObject *)dict;
8758
0
    assert(can_modify_dict(old));
8759
8760
0
    if (old->ma_values && old->ma_values->embedded) {
8761
0
        PyErr_SetString(PyExc_ValueError,
8762
0
                        "can't convert dict with embedded values");
8763
0
        return -1;
8764
0
    }
8765
8766
    // Fast path: do nothing on an empty dict:
8767
0
    if (old->ma_keys == Py_EMPTY_KEYS) {
8768
0
        return 0;
8769
0
    }
8770
8771
0
    Py_ssize_t used = old->ma_used;
8772
0
    PyDictKeysObject *keys = old->ma_keys;
8773
0
    PyDictValues *values = old->ma_values;
8774
8775
    // Clear the old dict keys and values, but do not decref them:
8776
0
    clear_common(old);
8777
0
    set_keys(old, Py_EMPTY_KEYS);
8778
0
    set_values(old, NULL);
8779
0
    ASSERT_CONSISTENT(old);
8780
8781
    // Transfer keys and values from dict to frozendict:
8782
0
    new->ma_used = used;
8783
0
    new->ma_keys = keys;
8784
0
    new->ma_values = values;
8785
0
    ASSERT_CONSISTENT(new);
8786
0
    return 0;
8787
0
}
8788
8789
PyObject *
8790
PyDict_AsFrozenDictAndClear(PyObject *dict)
8791
0
{
8792
0
    if (dict == NULL || !PyDict_Check(dict)) {
8793
0
        PyErr_BadInternalCall();
8794
0
        return NULL;
8795
0
    }
8796
8797
0
    PyObject *res = frozendict_new_untracked(&PyFrozenDict_Type);
8798
0
    if (res == NULL) {
8799
0
        return NULL;
8800
0
    }
8801
8802
0
    int transfer;
8803
0
    Py_BEGIN_CRITICAL_SECTION(dict);
8804
0
    transfer = transfer_keys_and_values_lock_held(res, dict);
8805
0
    Py_END_CRITICAL_SECTION();
8806
0
    if (transfer < 0) {
8807
0
        Py_DECREF(res);
8808
0
        return NULL;
8809
0
    }
8810
8811
0
    _PyObject_GC_TRACK(res);
8812
0
    assert(_PyFrozenDictObject_CAST(res)->ma_hash == -1);
8813
0
    return res;
8814
0
}
8815
8816
8817
PyObject*
8818
PyFrozenDict_New(PyObject *iterable)
8819
0
{
8820
0
    if (iterable != NULL) {
8821
0
        if (PyFrozenDict_CheckExact(iterable)) {
8822
            // PyFrozenDict_New(frozendict) returns the same object unmodified
8823
0
            return Py_NewRef(iterable);
8824
0
        }
8825
8826
0
        PyObject *args = PyTuple_Pack(1, iterable);
8827
0
        if (args == NULL) {
8828
0
            return NULL;
8829
0
        }
8830
0
        PyObject *frozendict = frozendict_new(&PyFrozenDict_Type, args, NULL);
8831
0
        Py_DECREF(args);
8832
0
        return frozendict;
8833
0
    }
8834
0
    else {
8835
0
        PyObject *args = Py_GetConstantBorrowed(Py_CONSTANT_EMPTY_TUPLE);
8836
0
        return frozendict_new(&PyFrozenDict_Type, args, NULL);
8837
0
    }
8838
0
}
8839
8840
/*[clinic input]
8841
frozendict.copy
8842
8843
Return a shallow copy of the frozendict.
8844
[clinic start generated code]*/
8845
8846
static PyObject *
8847
frozendict_copy_impl(PyFrozenDictObject *self)
8848
/*[clinic end generated code: output=e580fd91d9fc2cf7 input=35f6abeaa08fd4bc]*/
8849
0
{
8850
0
    assert(PyFrozenDict_Check(self));
8851
8852
0
    if (PyFrozenDict_CheckExact(self)) {
8853
0
        return Py_NewRef(self);
8854
0
    }
8855
8856
0
    PyObject *copy = anydict_copy_untracked((PyObject*)self);
8857
0
    if (copy != NULL) {
8858
0
        _PyObject_GC_TRACK(copy);
8859
0
    }
8860
0
    return copy;
8861
0
}
8862
8863
PyDoc_STRVAR(frozendict_doc,
8864
"frozendict() -> new empty immutable dictionary\n"
8865
"frozendict(mapping) -> new immutable dictionary initialized from a mapping\n"
8866
"    object's (key, value) pairs\n"
8867
"frozendict(iterable) -> new immutable dictionary initialized as if via:\n"
8868
"    d = {}\n"
8869
"    for k, v in iterable:\n"
8870
"        d[k] = v\n"
8871
"    d = frozendict(d)\n"
8872
"frozendict(**kwargs) -> new immutable dictionary initialized with the name=value\n"
8873
"    pairs in the keyword argument list.  For example:  frozendict(one=1, two=2)");
8874
8875
PyTypeObject PyFrozenDict_Type = {
8876
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
8877
    .tp_name = "frozendict",
8878
    .tp_basicsize = sizeof(PyFrozenDictObject),
8879
    .tp_dealloc = dict_dealloc,
8880
    .tp_repr = frozendict_repr,
8881
    .tp_as_number = &frozendict_as_number,
8882
    .tp_as_sequence = &dict_as_sequence,
8883
    .tp_as_mapping = &frozendict_as_mapping,
8884
    .tp_hash = frozendict_hash,
8885
    .tp_getattro = PyObject_GenericGetAttr,
8886
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
8887
                | Py_TPFLAGS_BASETYPE
8888
                | _Py_TPFLAGS_MATCH_SELF | Py_TPFLAGS_MAPPING,
8889
    .tp_doc = frozendict_doc,
8890
    .tp_traverse = dict_traverse,
8891
    .tp_clear = dict_tp_clear,
8892
    .tp_richcompare = dict_richcompare,
8893
    .tp_iter = dict_iter,
8894
    .tp_methods = frozendict_methods,
8895
    .tp_alloc = _PyType_AllocNoTrack,
8896
    .tp_new = frozendict_new,
8897
    .tp_free = PyObject_GC_Del,
8898
    .tp_vectorcall = frozendict_vectorcall,
8899
    .tp_version_tag = _Py_TYPE_VERSION_FROZENDICT,
8900
};