Skip to content

Commit dd2a09c

Browse files
authored
bpo-30242: resolve some undefined behaviours in struct (#1418) (#1587)
1 parent 51ab4ad commit dd2a09c

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
@@ -519,7 +519,7 @@ np_ubyte(char *p, PyObject *v, const formatdef *f)
519519
"ubyte format requires 0 <= number <= 255");
520520
return -1;
521521
}
522-
*p = (char)x;
522+
*(unsigned char *)p = (unsigned char)x;
523523
return 0;
524524
}
525525

@@ -850,6 +850,7 @@ bp_int(char *p, PyObject *v, const formatdef *f)
850850
{
851851
long x;
852852
Py_ssize_t i;
853+
unsigned char *q = (unsigned char *)p;
853854
if (get_long(v, &x) < 0)
854855
return -1;
855856
i = f->size;
@@ -862,7 +863,7 @@ bp_int(char *p, PyObject *v, const formatdef *f)
862863
#endif
863864
}
864865
do {
865-
p[--i] = (char)x;
866+
q[--i] = (unsigned char)(x & 0xffL);
866867
x >>= 8;
867868
} while (i > 0);
868869
return 0;
@@ -873,6 +874,7 @@ bp_uint(char *p, PyObject *v, const formatdef *f)
873874
{
874875
unsigned long x;
875876
Py_ssize_t i;
877+
unsigned char *q = (unsigned char *)p;
876878
if (get_ulong(v, &x) < 0)
877879
return -1;
878880
i = f->size;
@@ -883,7 +885,7 @@ bp_uint(char *p, PyObject *v, const formatdef *f)
883885
RANGE_ERROR(x, f, 1, maxint - 1);
884886
}
885887
do {
886-
p[--i] = (char)x;
888+
q[--i] = (unsigned char)(x & 0xffUL);
887889
x >>= 8;
888890
} while (i > 0);
889891
return 0;
@@ -1070,6 +1072,7 @@ lp_int(char *p, PyObject *v, const formatdef *f)
10701072
{
10711073
long x;
10721074
Py_ssize_t i;
1075+
unsigned char *q = (unsigned char *)p;
10731076
if (get_long(v, &x) < 0)
10741077
return -1;
10751078
i = f->size;
@@ -1082,7 +1085,7 @@ lp_int(char *p, PyObject *v, const formatdef *f)
10821085
#endif
10831086
}
10841087
do {
1085-
*p++ = (char)x;
1088+
*q++ = (unsigned char)(x & 0xffL);
10861089
x >>= 8;
10871090
} while (--i > 0);
10881091
return 0;
@@ -1093,6 +1096,7 @@ lp_uint(char *p, PyObject *v, const formatdef *f)
10931096
{
10941097
unsigned long x;
10951098
Py_ssize_t i;
1099+
unsigned char *q = (unsigned char *)p;
10961100
if (get_ulong(v, &x) < 0)
10971101
return -1;
10981102
i = f->size;
@@ -1103,7 +1107,7 @@ lp_uint(char *p, PyObject *v, const formatdef *f)
11031107
RANGE_ERROR(x, f, 1, maxint - 1);
11041108
}
11051109
do {
1106-
*p++ = (char)x;
1110+
*q++ = (unsigned char)(x & 0xffUL);
11071111
x >>= 8;
11081112
} while (--i > 0);
11091113
return 0;

0 commit comments

Comments
 (0)