Detecting Global Pollution with the JScript RuntimeObject Sunday, 11 April 2010
This article is about debugging with JScript's RuntimeObject
(msdn). All of the examples work in IE 5.5+, though most do not work in any other browser.
Leaked Global Identifiers
Say you accidentally created a global property, as in the following:
function playRugby(players) {
var items,
i;
len = items.length; // Global.
}
function kick() {
var x = 10
y = 11; // ASI makes y global.
}
When playRugby is called, a global property len is created, if it does not already exist,
and then assigned the value of items.length. Likewise, when kick is called, a global
property y is created.
These globals are unintentional. They break encapsulation and leak implementation details. This can result in conflict and awkward dependency issues.
To detect accidentally created global identifiers, we can loop over the global object using
for in. Firebug provides this convenient global inspection under the "DOM" tab.
Everybody's Favorite Browser
Unfortunately, in IE, the for in won't enumerate any global variables or function declarations,
as seen in the example below.
Example Enumerating the Global Object
// Property of global variable object.
var EX1_GLOBAL_VARIABLE = 10;
// Property of global object.
this.EX1_GLOBAL_PROPERTY = 11;
// Property of global variable object.
function EX1_GLOBAL_FUNCTION(){}
(function(){
var results = [];
for(var p in this) {
results.push(p);
}
alert("Leaked:\n" + results.join("\n"));
})();
The result in IE contains a mix of window properties and one the four user-defined properties:
EX1_GLOBAL_PROPERTY.
So what happened to the other three user-defined properties? Why didn't they show up in the for in loop?
It turns out that enumerating over the global object will enumerate properties assigned to the global object and will not enumerate global variables.
An educated guess as to why global properties are enumerated but global variables are not might be that JScript gives global variables (declared with var), the DontEnum flag. Since the global object is specified as being the global Variable object, this seems like a likely explanation. It would be nonstandard, but it would explain the behavior in IE. Eric Lippert, however, provided a different explanation: The global object and the global variable object are
two different objects in IE.
According to MS-ES3:
JScript 5.x variable instantiations creates properties of the global object that have the DontEnum attribute.
Enumeration Solution: The JScript RuntimeObject
To enumerate over global properties, use the JScript RuntimeObject method.
Instead of enumerating over the global object, as you would use in a normal implementation,
enumerate over an object returned by the global RuntimeObject method.
var GLOBAL_VAR1,
GLOBAL_VAR2,
GLOBAL_VAR3 = 1;
GLOBAL_PROP1 = 12;
function GLOBAL_FUNCTION(){}
if(this.RuntimeObject){
void function() {
var ro = RuntimeObject(),
results = [],
prop;
for(prop in ro) {
results.push(prop);
}
alert("leaked:\n" + results.join("\n"));
}();
}
IE Result
The result in IE 8 and below includes (among other things, including window) GLOBAL_FUNCTION, GLOBAL_VAR3,
and GLOBAL_PROP1, in that order, as they were evaluated in.
Notice that neither GLOBAL_VAR1 nor GLOBAL_VAR2 were included.
It appears that RuntimeObject does not accumulate any variables that were
unassigned to. According to Microsoft's documentation, this is not the specified behavior
(more on this below).
Microsoft RuntimeObject Documentation
The JScript RuntimeObject is a built-in extension to JScript. JScript
defines seven additional built-in global methods: ScriptEngine,
ScriptEngineBuildVersion, ScriptEngineMajorVersion,
ScriptEngineMinorVersion, CollectGarbage,
RuntimeObject, and GetObject. These objects are
all native JScript objects, not to be confused with
host objects.
For RuntimeObject, Microsoft JScript Extensions [MS-ES3EX] states:
TheRuntimeObjectfunction is used to search a global object for properties with names that match a specified pattern. The function only locates properties of the global object that were explicitly created byVariableStatementorFunctionDeclarationfunctions, or that were implicitly created by appearing as an identifier on the left side of an assignment operator. The function does not locate properties that were created by means of explicit property access on the global object.
Superficial testing indicates that Microsoft's documentation is wrong.
The returned object does not includes all identifiers that were added to the Variable object;
only those identifiers that have been assigned a value. Whether or not they were created from
VariableDeclaration, FunctionDeclaration, or assignment as global properties
does not matter.
Example of Finding Identifiers Created By FunctionBindingList
All identifiers in a FunctionBindingList of a JScriptFunction
will become properties of the containing Variable object, so, for example:
var foo = {}, undef, ro;
(function(){ function foo.bar, baz(){} })();
ro = RuntimeObject();
alert([ro.foo.bar, "undef" in ro].join("\n"));
IE elerts
function foo.bar(){}
false
Browsers other than IE running JScript can be expected to throw
SyntaxError upon parsing the FunctionBindingList of
JScriptFunction production. This is to be expected, as
it is a syntax extension.
Bookmarklet
As a bookmarklet:
javascript:(function() {var ro=RuntimeObject(),r=[],i=0,p;for(p in ro){r[i++]=p;}alert('leaked:\n'+r.join('\n'));})();
JScript Syntax Extension
The earlier example "Finding Identifiers Created By FunctionBindingList" mentioned
the JScript Extension JScriptFunction. In case the name is not a dead
giveaway, this is a JScript language extension. The production for JScriptFunction is:
JScriptFunction :
function FunctionBindingList ( FormalParameterListopt ) { FunctionBody }
RuntimeObject(filterString): The filterString Parameter
The RuntimeObject method accepts an optional filter string to match
identifiers. Unfortunately, filterString is not converted to a regular expression
but is used for substring matching with optional leftWild and rightWild, defaulting to *.
This means that, for example: filterString = "a*" would match
identifiers a and a1 but not ba.
Conclusion
Documentation bugs and shortcomings aside, the RuntimeObject
provides a useful alternative to the problem
of enumerating global properties in JScript. An advantage with
RuntimeObject is that it only includes user-defined
properties, with the exception of the global window property.
The aforementioned bookmarklet provides a convenient way to check a page to see the globals that have been accidentally created (it also shows that this site is not a shining example of keeping the global object clean).
Other Applications for RuntimeObject
Cross Browser Identifier Leak Bookmarklet
Writing a cross-browser identifier leak detector is the next logical step to an IE-only identifier leak detector.
Automated Identifier Leak Detection
Checking for accidental global identifiers should be automated.
The YUI Test unit test framework provides hooks for TEST_CASE_BEGIN_EVENT
and TEST_CASE_COMPLETE_EVENT . These events can be used to
inspect the RuntimeObject and catch global identifier leaks
that occur througout the runtime execution of program code.
In TEST_CASE_BEGIN_EVENT, inspect the RuntimeObject and save the result.
In TEST_CASE_COMPLETE_EVENT, inspect the RuntimeObject again and compare
the results with results saved during TEST_CASE_BEGIN_EVENT.
Next, for each property that appeared in TEST_CASE_COMPLETE_EVENT but was not present
in the result saved from TEST_CASE_BEGIN_EVENT , a global identifier has been
leaked and a test case warning can be logged.
References
- [MS-ES3EX]: Microsoft JScript Extensions to the ECMAScript Language Specification Third Edition.


AnimTree