arith: Detect error in bitwise shifting
@@ -443,9 +443,18 @@ | ||
443 | 443 | { |
444 | 444 | switch (ttype) { |
445 | 445 | case TT_LESSLESS: case TT_LESSLESSEQUAL: |
446 | + if (v1 < 0) | |
447 | + goto negative_left_shift; | |
448 | + if (v2 < 0 || v2 >= LONG_BIT) | |
449 | + goto invalid_shift_width; | |
450 | + unsigned long u1 = (unsigned long) v1; | |
451 | + if ((u1 << v2 & (unsigned long) LONG_MAX) >> v2 != u1) | |
452 | + goto overflow; | |
446 | 453 | *result = v1 << v2; |
447 | 454 | return true; |
448 | 455 | case TT_GREATERGREATER: case TT_GREATERGREATEREQUAL: |
456 | + if (v2 < 0 || v2 >= LONG_BIT) | |
457 | + goto invalid_shift_width; | |
449 | 458 | *result = v1 >> v2; |
450 | 459 | return true; |
451 | 460 | case TT_AMP: case TT_AMPEQUAL: |
@@ -460,6 +469,16 @@ | ||
460 | 469 | default: |
461 | 470 | assert(false); |
462 | 471 | } |
472 | + | |
473 | +overflow: | |
474 | + xerror(0, Ngt("arithmetic: overflow")); | |
475 | + return false; | |
476 | +negative_left_shift: | |
477 | + xerror(0, Ngt("arithmetic: negative value cannot be shifted to left")); | |
478 | + return false; | |
479 | +invalid_shift_width: | |
480 | + xerror(0, Ngt("arithmetic: invalid shift width")); | |
481 | + return false; | |
463 | 482 | } |
464 | 483 | |
465 | 484 | /* Applies binary operator `ttype' to the given operands `v1' and `v2'. */ |