r/javascript • • Jun 20 '16

Javascript developers, be warned about this crazy JIT bug in V8!

Last week I've spent a full day to fix very strange behavior in a single page application for my customer that only happens on Chrome 51 (maybe 52, but not in Canary 53).

After a while our SPA started behaving incorrectly...

It turned out to be a nasty bug in the V8 JIT engine.

Try the following in Chrome's developer console:

function foo() {
  return typeof null === "undefined";
}

for(var i=0; i<10000; ++i) console.log(foo())

This should of course always print false, but in Chrome 51, it prints true after about about 100 iterations (it varies...)

I want to warn other web-developers for this bug, to avoid many $$$ being wasted (or becoming insane ;-))

 

EDIT: The following - more realistic case that we had in third-party library code - will also fail, but after about 10 thousand iterations:

function isUndefined(thing){
    return typeof thing === "undefined";
}

for(var i=0; i<100000; i++) console.log(isUndefined(null));

 

EDIT: The bug also manifests itself with the more common pattern

typeof x !== "undefined"

UPDATE: I just tried this with the latest stable Chrome (52.0.2743.82), and it now works correctly :)

482 Upvotes

117 comments sorted by

View all comments

14

u/Pyrise Jun 20 '16

Anyone have any insight into why this happens?(Newbie here)

28

u/RainHappens Jun 20 '16

I found the bugfix.

Suffice to say (and I am probably wrong here, having next-to-no knowledge of the codebase) that the optimizer keeps track of "special" strings (booleans, "undefined", some integers, etc). It also does some type propagation (as in what types a variable etc can be). There's a special "undetectable" type for when a variable is undefined or null. In this case the optimizer goes "null is undetectable, so it can be replaced with the "undefined" string for the comparison. Oh look, both strings are the same!"

If you notice, this:

for(let i=0; i<10000; ++i) console.log(typeof null === 'object')

exhibits the same incorrect behavior, albeit reversed. Same thing. The initial interpreter thinks 'typeof null' is 'object' for comparison purposes, but the optimizer thinks 'typeof null' is 'undefined' for comparison purposes.

7

u/[deleted] Jun 21 '16

So scoping out the string should fix this right?

var uu = "undefined"; for(let i=0; i<10000; ++i) console.log(typeof null === uu);

Works for me.

1

u/tunnckoCore node-formidable, regexhq, jest, standard-release Jun 22 '16

Yep, same here.