Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 02fe647

Browse files
committed
Insert an overflow check when the sequence repetition count is outside
the range of ints. The old code would pass random truncated bits to sq_repeat() on a 64-bit machine. Backport candidate.
1 parent f981a33 commit 02fe647

1 file changed

Lines changed: 30 additions & 3 deletions

File tree

Objects/intobject.c

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -358,14 +358,41 @@ int_mul(PyObject *v, PyObject *w)
358358
double doubleprod; /* (double)a * (double)b */
359359

360360
if (USE_SQ_REPEAT(v)) {
361+
repeat:
361362
/* sequence * int */
362363
a = PyInt_AsLong(w);
364+
#if LONG_MAX != INT_MAX
365+
if (a > INT_MAX) {
366+
PyErr_SetString(PyExc_ValueError,
367+
"sequence repeat count too large");
368+
return NULL;
369+
}
370+
else if (a < INT_MIN)
371+
a = INT_MIN;
372+
/* XXX Why don't I either
373+
374+
- set a to -1 whenever it's negative (after all,
375+
sequence repeat usually treats negative numbers
376+
as zero(); or
377+
378+
- raise an exception when it's less than INT_MIN?
379+
380+
I'm thinking about a hypothetical use case where some
381+
sequence type might use a negative value as a flag of
382+
some kind. In those cases I don't want to break the
383+
code by mapping all negative values to -1. But I also
384+
don't want to break e.g. []*(-sys.maxint), which is
385+
perfectly safe, returning []. As a compromise, I do
386+
map out-of-range negative values.
387+
*/
388+
#endif
363389
return (*v->ob_type->tp_as_sequence->sq_repeat)(v, a);
364390
}
365391
if (USE_SQ_REPEAT(w)) {
366-
/* int * sequence */
367-
a = PyInt_AsLong(v);
368-
return (*w->ob_type->tp_as_sequence->sq_repeat)(w, a);
392+
PyObject *tmp = v;
393+
v = w;
394+
w = tmp;
395+
goto repeat;
369396
}
370397

371398
CONVERT_TO_LONG(v, a);

0 commit comments

Comments
 (0)