10

I accidentally ran into what appears to be a very strange bug in Safari's javascript engine on iPad.

The unsigned shift operator >>> is supposed to bitwise right-shift a number. I experienced some errors in a script that worked fine on other platforms, stripped it down and ended up with this:

<html><head><script type='text/javascript'>

var one = 1;

function Zero()
{
    return one*0;
}

function Strange()
{
     return one = (Zero()+1) >>> 0;
}

var s = 'A bunch of ones: '; // except on iPad :(
for (var i=0; i<200; i++) 
{
     s += Strange()+' ';
}
document.write(s);

</script></head><body></body></html>

Live demo

Strangely enough, it correctly generates a bunch of ones, but at a certain point, something breaks and it only outputs zeroes from then on.

Obviously the >>> 0 is meaningless here (a shift over zero places typically does nothing, although it could have forced an integer to become unsigned if javascript made that distinction). It's just to demonstrate the problem, if you omit the >>> 0 it doesn't show up. In my actual situation there were different numbers and more complex expressions involved, but the same thing happened: everything works until a number of iterations, then something 'breaks' and variables suddenly become and remain zero, even after subsequent calculations that really ought to make them non-zero.

Works fine on Android and PC browsers. Strange huh?

Rogier
  • 153
  • 5

2 Answers2

2

Not a "real" answer but perhaps a useful one, assuming (as seems VERY likely) that this is simply a bug in Apple's JIT compiler: This StackOverflow thread (Disabling JIT in Safari 6 to workaround severe Javascript JIT bugs) talks about how to disable the JIT on your code. Basically,

Wrap the offending statement in a do-nothing try-catch block.

I don't have an iOS device to test on, but does this make the problem go away? Can you apply the same kind of workaround to your original code?

function Strange()
{
    try
    {
        return one = (Zero()+1) >>> 0;
    }
    catch (e) { throw e }
}
Community
  • 1
  • 1
Quuxplusone
  • 23,928
  • 8
  • 94
  • 159
0

For the record, the described erroneous behaviour does not seem to occur on Mobile Safari 5.0.2 running on iOS 4.2.1

dig
  • 449
  • 5
  • 7