Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Lib/test/test_ctypes/test_bitfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ def test_ints(self):
setattr(b, name, i)
self.assertEqual(getattr(b, name), func(byref(b), name.encode('ascii')))

# bpo-46913: _ctypes/cfield.c h_get() has an undefined behavior
@support.skip_if_sanitizer(ub=True)
def test_shorts(self):
b = BITS()
name = "M"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix undefined behaviour in ``_ctypes/cfield.c``.
8 changes: 5 additions & 3 deletions Modules/_ctypes/cfield.c
Original file line number Diff line number Diff line change
Expand Up @@ -412,21 +412,23 @@ get_ulonglong(PyObject *v, unsigned long long *p)
#define NUM_BITS(x) ((x) >> 16)

/* Doesn't work if NUM_BITS(size) == 0, but it never happens in SET() call. */
#define BIT_MASK(type, size) (((((type)1 << (NUM_BITS(size) - 1)) - 1) << 1) + 1)
#define BIT_MASK(type, size) \
(assert(NUM_BITS(size) > 0), \
(((((type)1 << (NUM_BITS(size) - 1)) - 1) << 1) + 1))

/* This macro CHANGES the first parameter IN PLACE. For proper sign handling,
we must first shift left, then right.
*/
#define GET_BITFIELD(v, size) \
if (NUM_BITS(size)) { \
v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
v *= 1ULL << (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
v >>= (sizeof(v)*8 - NUM_BITS(size)); \
}

/* This macro RETURNS the first parameter with the bit field CHANGED. */
#define SET(type, x, v, size) \
(NUM_BITS(size) ? \
( ( (type)x & ~(BIT_MASK(type, size) << LOW_BIT(size)) ) | ( ((type)v & BIT_MASK(type, size)) << LOW_BIT(size) ) ) \
(type) ( ( (type)x & ~(BIT_MASK(type, size) * (1ULL << LOW_BIT(size))) ) | ( ((type)v & BIT_MASK(type, size)) * (1ULL << LOW_BIT(size) )) ) \
: (type)v)

#if SIZEOF_SHORT == 2
Expand Down