Skip to content

Commit aad1caf

Browse files
authored
bpo-30242: resolve some undefined behaviours in struct (#1418) (#1586)
1 parent 0ce1f7e commit aad1caf

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

Modules/_struct.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,7 @@ np_ubyte(char *p, PyObject *v, const formatdef *f)
539539
"ubyte format requires 0 <= number <= 255");
540540
return -1;
541541
}
542-
*p = (char)x;
542+
*(unsigned char *)p = (unsigned char)x;
543543
return 0;
544544
}
545545

@@ -868,6 +868,7 @@ bp_int(char *p, PyObject *v, const formatdef *f)
868868
{
869869
long x;
870870
Py_ssize_t i;
871+
unsigned char *q = (unsigned char *)p;
871872
if (get_long(v, &x) < 0)
872873
return -1;
873874
i = f->size;
@@ -880,7 +881,7 @@ bp_int(char *p, PyObject *v, const formatdef *f)
880881
#endif
881882
}
882883
do {
883-
p[--i] = (char)x;
884+
q[--i] = (unsigned char)(x & 0xffL);
884885
x >>= 8;
885886
} while (i > 0);
886887
return 0;
@@ -891,6 +892,7 @@ bp_uint(char *p, PyObject *v, const formatdef *f)
891892
{
892893
unsigned long x;
893894
Py_ssize_t i;
895+
unsigned char *q = (unsigned char *)p;
894896
if (get_ulong(v, &x) < 0)
895897
return -1;
896898
i = f->size;
@@ -901,7 +903,7 @@ bp_uint(char *p, PyObject *v, const formatdef *f)
901903
RANGE_ERROR(x, f, 1, maxint - 1);
902904
}
903905
do {
904-
p[--i] = (char)x;
906+
q[--i] = (unsigned char)(x & 0xffUL);
905907
x >>= 8;
906908
} while (i > 0);
907909
return 0;
@@ -1087,6 +1089,7 @@ lp_int(char *p, PyObject *v, const formatdef *f)
10871089
{
10881090
long x;
10891091
Py_ssize_t i;
1092+
unsigned char *q = (unsigned char *)p;
10901093
if (get_long(v, &x) < 0)
10911094
return -1;
10921095
i = f->size;
@@ -1099,7 +1102,7 @@ lp_int(char *p, PyObject *v, const formatdef *f)
10991102
#endif
11001103
}
11011104
do {
1102-
*p++ = (char)x;
1105+
*q++ = (unsigned char)(x & 0xffL);
11031106
x >>= 8;
11041107
} while (--i > 0);
11051108
return 0;
@@ -1110,6 +1113,7 @@ lp_uint(char *p, PyObject *v, const formatdef *f)
11101113
{
11111114
unsigned long x;
11121115
Py_ssize_t i;
1116+
unsigned char *q = (unsigned char *)p;
11131117
if (get_ulong(v, &x) < 0)
11141118
return -1;
11151119
i = f->size;
@@ -1120,7 +1124,7 @@ lp_uint(char *p, PyObject *v, const formatdef *f)
11201124
RANGE_ERROR(x, f, 1, maxint - 1);
11211125
}
11221126
do {
1123-
*p++ = (char)x;
1127+
*q++ = (unsigned char)(x & 0xffUL);
11241128
x >>= 8;
11251129
} while (--i > 0);
11261130
return 0;

0 commit comments

Comments
 (0)