postgres.git / summary / log / commit / refs

commit    092401b14fa19d0ea28d57ba2f73b7aee64f960d
Author:   Tom Lane <tgl@sss.pgh.pa.us>
Date:     Sat Mar 17 19:38:15 2018 +0000
First released in: 11.0, 9.3.23, 9.4.18, 9.5.13, 9.6.9, 10.4

    Fix overflow handling in plpgsql's integer FOR loops.
    
    The test to exit the loop if the integer control value would overflow
    an int32 turns out not to work on some ICC versions, as it's dependent
    on the assumption that the compiler will execute the code as written
    rather than "optimize" it.  ICC lacks any equivalent of gcc's -fwrapv
    switch, so it was optimizing on the assumption of no integer overflow,
    and that breaks this.  Rewrite into a form that in fact does not
    do any overflowing computations.
    
    Per Tomas Vondra and buildfarm member fulmar.  It's been like this
    for a long time, although it was not till we added a regression test
    case covering the behavior (in commit dd2243f2a) that the problem
    became apparent.  Back-patch to all supported versions.
    
    Discussion: https://postgr.es/m/50562fdc-0876-9843-c883-15b8566c7511@2ndquadrant.com


src/pl/plpgsql/src/pl_exec.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c index b7f44ca1d1a..e63b4185d74 100644 --- a/src/pl/plpgsql/src/pl_exec.c +++ b/src/pl/plpgsql/src/pl_exec.c @@ -38,6 +38,9 @@ #include "utils/snapmgr.h" #include "utils/typcache.h" +#define PG_INT32_MIN (-0x7FFFFFFF-1) +#define PG_INT32_MAX (0x7FFFFFFF) + static const char *const raise_skip_msg = "RAISE"; @@ -2030,13 +2033,13 @@ exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt) */ if (stmt->reverse) { - if ((int32) (loop_value - step_value) > loop_value) + if (loop_value < (PG_INT32_MIN + step_value)) break; loop_value -= step_value; } else { - if ((int32) (loop_value + step_value) < loop_value) + if (loop_value > (PG_INT32_MAX - step_value)) break; loop_value += step_value; } [parent: 0a0721f84c40]