Skip to content

Commit a74902a

Browse files
authored
gh-106550: Fix sign conversion in pycore_code.h (#112613)
Fix sign conversion in pycore_code.h: use unsigned integers and cast explicitly when needed.
1 parent dee7bee commit a74902a

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
@@ -394,27 +394,29 @@ write_varint(uint8_t *ptr, unsigned int val)
394394
val >>= 6;
395395
written++;
396396
}
397-
*ptr = val;
397+
*ptr = (uint8_t)val;
398398
return written;
399399
}
400400

401401
static inline int
402402
write_signed_varint(uint8_t *ptr, int val)
403403
{
404+
unsigned int uval;
404405
if (val < 0) {
405-
val = ((-val)<<1) | 1;
406+
// (unsigned int)(-val) has an undefined behavior for INT_MIN
407+
uval = ((0 - (unsigned int)val) << 1) | 1;
406408
}
407409
else {
408-
val = val << 1;
410+
uval = (unsigned int)val << 1;
409411
}
410-
return write_varint(ptr, val);
412+
return write_varint(ptr, uval);
411413
}
412414

413415
static inline int
414416
write_location_entry_start(uint8_t *ptr, int code, int length)
415417
{
416418
assert((code & 15) == code);
417-
*ptr = 128 | (code << 3) | (length - 1);
419+
*ptr = 128 | (uint8_t)(code << 3) | (uint8_t)(length - 1);
418420
return 1;
419421
}
420422

@@ -454,9 +456,9 @@ write_location_entry_start(uint8_t *ptr, int code, int length)
454456

455457

456458
static inline uint16_t
457-
adaptive_counter_bits(int value, int backoff) {
458-
return (value << ADAPTIVE_BACKOFF_BITS) |
459-
(backoff & ((1<<ADAPTIVE_BACKOFF_BITS)-1));
459+
adaptive_counter_bits(uint16_t value, uint16_t backoff) {
460+
return ((value << ADAPTIVE_BACKOFF_BITS)
461+
| (backoff & ((1 << ADAPTIVE_BACKOFF_BITS) - 1)));
460462
}
461463

462464
static inline uint16_t
@@ -473,12 +475,12 @@ adaptive_counter_cooldown(void) {
473475

474476
static inline uint16_t
475477
adaptive_counter_backoff(uint16_t counter) {
476-
unsigned int backoff = counter & ((1<<ADAPTIVE_BACKOFF_BITS)-1);
478+
uint16_t backoff = counter & ((1 << ADAPTIVE_BACKOFF_BITS) - 1);
477479
backoff++;
478480
if (backoff > MAX_BACKOFF_VALUE) {
479481
backoff = MAX_BACKOFF_VALUE;
480482
}
481-
unsigned int value = (1 << backoff) - 1;
483+
uint16_t value = (uint16_t)(1 << backoff) - 1;
482484
return adaptive_counter_bits(value, backoff);
483485
}
484486

0 commit comments

Comments
 (0)