Skip to content

Commit e005dab

Browse files
[3.12] gh-106550: Fix sign conversion in pycore_code.h (GH-112613) (#112696)
gh-106550: Fix sign conversion in pycore_code.h (GH-112613) Fix sign conversion in pycore_code.h: use unsigned integers and cast explicitly when needed. (cherry picked from commit a74902a) Co-authored-by: Victor Stinner <[email protected]>
1 parent 29a5ff0 commit e005dab

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

Include/internal/pycore_code.h

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -359,27 +359,29 @@ write_varint(uint8_t *ptr, unsigned int val)
359359
val >>= 6;
360360
written++;
361361
}
362-
*ptr = val;
362+
*ptr = (uint8_t)val;
363363
return written;
364364
}
365365

366366
static inline int
367367
write_signed_varint(uint8_t *ptr, int val)
368368
{
369+
unsigned int uval;
369370
if (val < 0) {
370-
val = ((-val)<<1) | 1;
371+
// (unsigned int)(-val) has an undefined behavior for INT_MIN
372+
uval = ((0 - (unsigned int)val) << 1) | 1;
371373
}
372374
else {
373-
val = val << 1;
375+
uval = (unsigned int)val << 1;
374376
}
375-
return write_varint(ptr, val);
377+
return write_varint(ptr, uval);
376378
}
377379

378380
static inline int
379381
write_location_entry_start(uint8_t *ptr, int code, int length)
380382
{
381383
assert((code & 15) == code);
382-
*ptr = 128 | (code << 3) | (length - 1);
384+
*ptr = 128 | (uint8_t)(code << 3) | (uint8_t)(length - 1);
383385
return 1;
384386
}
385387

@@ -419,9 +421,9 @@ write_location_entry_start(uint8_t *ptr, int code, int length)
419421

420422

421423
static inline uint16_t
422-
adaptive_counter_bits(int value, int backoff) {
423-
return (value << ADAPTIVE_BACKOFF_BITS) |
424-
(backoff & ((1<<ADAPTIVE_BACKOFF_BITS)-1));
424+
adaptive_counter_bits(uint16_t value, uint16_t backoff) {
425+
return ((value << ADAPTIVE_BACKOFF_BITS)
426+
| (backoff & ((1 << ADAPTIVE_BACKOFF_BITS) - 1)));
425427
}
426428

427429
static inline uint16_t
@@ -438,12 +440,12 @@ adaptive_counter_cooldown(void) {
438440

439441
static inline uint16_t
440442
adaptive_counter_backoff(uint16_t counter) {
441-
unsigned int backoff = counter & ((1<<ADAPTIVE_BACKOFF_BITS)-1);
443+
uint16_t backoff = counter & ((1 << ADAPTIVE_BACKOFF_BITS) - 1);
442444
backoff++;
443445
if (backoff > MAX_BACKOFF_VALUE) {
444446
backoff = MAX_BACKOFF_VALUE;
445447
}
446-
unsigned int value = (1 << backoff) - 1;
448+
uint16_t value = (uint16_t)(1 << backoff) - 1;
447449
return adaptive_counter_bits(value, backoff);
448450
}
449451

0 commit comments

Comments
 (0)