Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: PATCH: prevent SIGFPE on systems where LONG_MIN < -LONG_MAX



On Mon, 3 Sep 2012 18:26:02 +0200
Vincent Lefevre <vincent@xxxxxxxxxx> wrote:
> On 2012-09-03 17:08:18 +0200, Jérémie Roquet wrote:
> > I think we want a warning, as we have for division by zero.
> 
> I don't think so. The division by zero is mathematically undefined,
> so that a warning is fine. But a division by -1 could be replaced by
> a negate operation; then you have the usual modular arithmetic rules.
> They already occur for
> 
> $ echo $[ 2**63 ]
> -9223372036854775808
> 
> anyway.

Right, so we could just do this as a special case as below that gives
answers that are plausible as far as fixed precision integer arithmetic
goes even if they're not mathematically accurate, which they can't be
for the division (they can for the mod).  The result should now be
sane everywhere.
 
> > The shell should not crash, neither should it return incorrect
> > results.
> 
> Agreed.

Well, that depends what you mean by an incorrect result.  Mathematically
incorrect results are inevitable if you don't account of the precision,
but we don't warn for any other rounding error so I agree there's no
reason to here.

Index: Src/math.c
===================================================================
RCS file: /cvsroot/zsh/zsh/Src/math.c,v
retrieving revision 1.41
diff -p -u -r1.41 math.c
--- Src/math.c	19 Jun 2011 16:26:11 -0000	1.41
+++ Src/math.c	4 Sep 2012 18:23:36 -0000
@@ -1053,14 +1053,34 @@ op(int what)
 		    return;
 		if (c.type == MN_FLOAT)
 		    c.u.d = a.u.d / b.u.d;
-		else
-		    c.u.l = a.u.l / b.u.l;
+		else {
+		    /*
+		     * Avoid exception when dividing the smallest
+		     * negative integer by -1.  Always treat it the
+		     * same as multiplication.  This still doesn't give
+		     * numerically the right answer in two's complement,
+		     * but treating both these in the same way seems
+		     * reasonable.
+		     */
+		    if (b.u.l == -1)
+			c.u.l = - a.u.l;
+		    else
+			c.u.l = a.u.l / b.u.l;
+		}
 		break;
 	    case MOD:
 	    case MODEQ:
 		if (!notzero(b))
 		    return;
-		c.u.l = a.u.l % b.u.l;
+		/*
+		 * Avoid exception as above.
+		 * Any integer mod -1 is the same as any integer mod 1
+		 * i.e. zero.
+		 */
+		if (b.u.l == -1)
+		    c.u.l = 0;
+		else
+		    c.u.l = a.u.l % b.u.l;
 		break;
 	    case PLUS:
 	    case PLUSEQ:

-- 
Peter Stephenson <p.w.stephenson@xxxxxxxxxxxx>
Web page now at http://homepage.ntlworld.com/p.w.stephenson/



Messages sorted by: Reverse Date, Date, Thread, Author