-
Notifications
You must be signed in to change notification settings - Fork 4
/
repairES5.js
3467 lines (3296 loc) · 120 KB
/
repairES5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Monkey patch almost ES5 platforms into a closer
* emulation of full <a href=
* "http://code.google.com/p/es-lab/wiki/SecureableES5">Secureable
* ES5</a>.
*
* <p>Assumes only ES3, but only proceeds to do useful repairs when
* the platform is close enough to ES5 to be worth attempting
* repairs. Compatible with almost-ES5, ES5, ES5-strict, and
* anticipated ES6.
*
* <p>Ignore the "...requires ___global_test_function___" below. We
* create it, use it, and delete it all within this module. But we
* need to lie to the linter since it can't tell.
*
* //provides ses.statuses, ses.ok, ses.is, ses.makeDelayedTamperProof
* //provides ses.makeCallerHarmless, ses.makeArgumentsHarmless
* //provides ses.severities, ses.maxSeverity, ses.updateMaxSeverity
* //provides ses.maxAcceptableSeverityName, ses.maxAcceptableSeverity
*
* @author Mark S. Miller
* @requires ___global_test_function___, ___global_valueOf_function___
* @requires JSON, navigator, this, eval, document
* @overrides ses, RegExp, WeakMap, Object, parseInt, repairES5Module
*/
var RegExp;
var ses;
/**
* <p>Qualifying platforms generally include all JavaScript platforms
* shown on <a href="http://kangax.github.com/es5-compat-table/"
* >ECMAScript 5 compatibility table</a> that implement {@code
* Object.getOwnPropertyNames}. At the time of this writing,
* qualifying browsers already include the latest released versions of
* Internet Explorer (9), Firefox (4), Chrome (11), and Safari
* (5.0.5), their corresponding standalone (e.g., server-side) JavaScript
* engines, Rhino 1.73, and BESEN.
*
* <p>On such not-quite-ES5 platforms, some elements of these
* emulations may lose SES safety, as enumerated in the comment on
* each kludge record in the {@code kludges} array below. The platform
* must at least provide {@code Object.getOwnPropertyNames}, because
* it cannot reasonably be emulated.
*
* <p>This file is useful by itself, as it has no dependencies on the
* rest of SES. It creates no new global bindings, but merely repairs
* standard globals or standard elements reachable from standard
* globals. If the future-standard {@code WeakMap} global is present,
* as it is currently on FF7.0a1, then it will repair it in place. The
* one non-standard element that this file uses is {@code console} if
* present, in order to report the repairs it found necessary, in
* which case we use its {@code log, info, warn}, and {@code error}
* methods. If {@code console.log} is absent, then this file performs
* its repairs silently.
*
* <p>Generally, this file should be run as the first script in a
* JavaScript context (i.e. a browser frame), as it relies on other
* primordial objects and methods not yet being perturbed.
*
* <p>TODO(erights): This file tries to protect itself from some
* post-initialization perturbation by stashing some of the
* primordials it needs for later use, but this attempt is currently
* incomplete. We need to revisit this when we support Confined-ES5,
* as a variant of SES in which the primordials are not frozen. See
* previous failed attempt at <a
* href="http://codereview.appspot.com/5278046/" >Speeds up
* WeakMap. Preparing to support unfrozen primordials.</a>. From
* analysis of this failed attempt, it seems that the only practical
* way to support CES is by use of two frames, where most of initSES
* runs in a SES frame, and so can avoid worrying about most of these
* perturbations.
*/
(function repairES5Module(global) {
"use strict";
/**
* The severity levels.
*
* <dl>
* <dt>MAGICAL_UNICORN</dt><dd>Unachievable magical mode used for testing.
* <dt>SAFE</dt><dd>no problem.
* <dt>SAFE_SPEC_VIOLATION</dt>
* <dd>safe (in an integrity sense) even if unrepaired. May
* still lead to inappropriate failures.</dd>
* <dt>NO_KNOWN_EXPLOIT_SPEC_VIOLATION</dt>
* <dd>known to introduce an indirect safety issue which,
* however, is not known to be exploitable.</dd>
* <dt>UNSAFE_SPEC_VIOLATION</dt>
* <dd>a safety issue only indirectly, in that this spec
* violation may lead to the corruption of assumptions made
* by other security critical or defensive code.</dd>
* <dt>NOT_OCAP_SAFE</dt>
* <dd>a violation of object-capability rules among objects
* within a coarse-grained unit of isolation.</dd>
* <dt>NOT_ISOLATED</dt>
* <dd>an inability to reliably sandbox even coarse-grain units
* of isolation.</dd>
* <dt>NEW_SYMPTOM</dt>
* <dd>some test failed in a way we did not expect.</dd>
* <dt>NOT_SUPPORTED</dt>
* <dd>this platform cannot even support SES development in an
* unsafe manner.</dd>
* </dl>
*/
ses.severities = {
MAGICAL_UNICORN: { level: -1, description: 'Testing only' },
SAFE: { level: 0, description: 'Safe' },
SAFE_SPEC_VIOLATION: { level: 1, description: 'Safe spec violation' },
NO_KNOWN_EXPLOIT_SPEC_VIOLATION: {
level: 2, description: 'Unsafe spec violation but no known exploits' },
UNSAFE_SPEC_VIOLATION: { level: 3, description: 'Unsafe spec violation' },
NOT_OCAP_SAFE: { level: 4, description: 'Not ocap safe' },
NOT_ISOLATED: { level: 5, description: 'Not isolated' },
NEW_SYMPTOM: { level: 6, description: 'New symptom' },
NOT_SUPPORTED: { level: 7, description: 'Not supported' }
};
/**
* Statuses.
*
* <dl>
* <dt>ALL_FINE</dt>
* <dd>test passed before and after.</dd>
* <dt>REPAIR_FAILED</dt>
* <dd>test failed before and after repair attempt.</dd>
* <dt>NOT_REPAIRED</dt>
* <dd>test failed before and after, with no repair to attempt.</dd>
* <dt>REPAIRED_UNSAFELY</dt>
* <dd>test failed before and passed after repair attempt, but
* the repair is known to be inadequate for security, so the
* real problem remains.</dd>
* <dt>REPAIRED</dt>
* <dd>test failed before and passed after repair attempt,
* repairing the problem (canRepair was true).</dd>
* <dt>ACCIDENTALLY_REPAIRED</dt>
* <dd>test failed before and passed after, despite no repair
* to attempt. (Must have been fixed by some other
* attempted repair.)</dd>
* <dt>BROKEN_BY_OTHER_ATTEMPTED_REPAIRS</dt>
* <dd>test passed before and failed after, indicating that
* some other attempted repair created the problem.</dd>
* </dl>
*/
ses.statuses = {
ALL_FINE: 'All fine',
REPAIR_FAILED: 'Repair failed',
NOT_REPAIRED: 'Not repaired',
REPAIRED_UNSAFELY: 'Repaired unsafely',
REPAIRED: 'Repaired',
ACCIDENTALLY_REPAIRED: 'Accidentally repaired',
BROKEN_BY_OTHER_ATTEMPTED_REPAIRS: 'Broken by other attempted repairs'
};
var logger = ses.logger;
/**
* As we start to repair, this will track the worst post-repair
* severity seen so far.
*/
ses.maxSeverity = ses.severities.SAFE;
/**
* {@code ses.maxAcceptableSeverity} is the max post-repair severity
* that is considered acceptable for proceeding with the SES
* verification-only strategy.
*
* <p>Although <code>repairES5.js</code> can be used standalone for
* partial ES5 repairs, its primary purpose is to repair as a first
* stage of <code>initSES.js</code> for purposes of supporting SES
* security. In support of that purpose, we initialize
* {@code ses.maxAcceptableSeverity} to the post-repair severity
* level at which we should report that we are unable to adequately
* support SES security. By default, this is set to
* {@code ses.severities.SAFE_SPEC_VIOLATION}, which is the maximum
* severity that we believe results in no loss of SES security.
*
* <p>If {@code ses.maxAcceptableSeverityName} is already set (to a
* severity property name of a severity below {@code
* ses.NOT_SUPPORTED}), then we use that setting to initialize
* {@code ses.maxAcceptableSeverity} instead. For example, if we are
* using SES only for isolation, then we could set it to
* 'NOT_OCAP_SAFE', in which case repairs that are inadequate for
* object-capability (ocap) safety would still be judged safe for
* our purposes.
*
* <p>As repairs proceed, they update {@code ses.maxSeverity} to
* track the worst case post-repair severity seen so far. When
* {@code ses.ok()} is called, it return whether {@code
* ses.maxSeverity} is still less than or equal to
* {@code ses.maxAcceptableSeverity}, indicating that this platform
* still seems adequate for supporting SES. In the Caja context, we
* have the choice of using SES on those platforms which we judge to
* be adequately repairable, or otherwise falling back to Caja's
* ES5/3 translator.
*/
ses.maxAcceptableSeverityName =
validateSeverityName(ses.maxAcceptableSeverityName);
ses.maxAcceptableSeverity = ses.severities[ses.maxAcceptableSeverityName];
function validateSeverityName(severityName) {
if (severityName) {
var sev = ses.severities[severityName];
if (sev && typeof sev.level === 'number' &&
sev.level >= ses.severities.SAFE.level &&
sev.level < ses.severities.NOT_SUPPORTED.level) {
// do nothing
} else {
logger.error('Ignoring bad severityName: ' +
severityName + '.');
severityName = 'SAFE_SPEC_VIOLATION';
}
} else {
severityName = 'SAFE_SPEC_VIOLATION';
}
return severityName;
}
function severityNameToLevel(severityName) {
return ses.severities[validateSeverityName(severityName)];
}
/**
* Once this returns false, we can give up on the SES
* verification-only strategy and fall back to ES5/3 translation.
*/
ses.ok = function ok(maxSeverity) {
if ("string" === typeof maxSeverity) {
maxSeverity = ses.severities[maxSeverity];
}
if (!maxSeverity) {
maxSeverity = ses.maxAcceptableSeverity;
}
return ses.maxSeverity.level <= maxSeverity.level;
};
/**
* Update the max based on the provided severity.
*
* <p>If the provided severity exceeds the max so far, update the
* max to match.
*/
ses.updateMaxSeverity = function updateMaxSeverity(severity) {
if (severity.level > ses.maxSeverity.level) {
ses.maxSeverity = severity;
}
};
//////// Prepare for "caller" and "argument" testing and repair /////////
/**
* Needs to work on ES3, since repairES5.js may be run on an ES3
* platform.
*/
function strictForEachFn(list, callback) {
for (var i = 0, len = list.length; i < len; i++) {
callback(list[i], i);
}
}
/**
* Needs to work on ES3, since repairES5.js may be run on an ES3
* platform.
*
* <p>Also serves as our representative strict function, by contrast
* to builtInMapMethod below, for testing what the "caller" and
* "arguments" properties of a strict function reveals.
*/
function strictMapFn(list, callback) {
var result = [];
for (var i = 0, len = list.length; i < len; i++) {
result.push(callback(list[i], i));
}
return result;
}
var objToString = Object.prototype.toString;
/**
* Sample map early, to obtain a representative built-in for testing.
*
* <p>There is no reliable test for whether a function is a
* built-in, and it is possible some of the tests below might
* replace the built-in Array.prototype.map, though currently none
* do. Since we <i>assume</i> (but with no reliable way to check)
* that repairES5.js runs in its JavaScript context before anything
* which might have replaced map, we sample it now. The map method
* is a particularly nice one to sample, since it can easily be used
* to test what the "caller" and "arguments" properties on a
* in-progress built-in method reveals.
*/
var builtInMapMethod = Array.prototype.map;
var builtInForEach = Array.prototype.forEach;
/**
* http://wiki.ecmascript.org/doku.php?id=harmony:egal
*/
var is = ses.is = Object.is || function(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
};
/**
* By the time this module exits, either this is repaired to be a
* function that is adequate to make the "caller" property of a
* strict or built-in function harmess, or this module has reported
* a failure to repair.
*
* <p>Start off with the optimistic assumption that nothing is
* needed to make the "caller" property of a strict or built-in
* function harmless. We are not concerned with the "caller"
* property of non-strict functions. It is not the responsibility of
* this module to actually make these "caller" properties
* harmless. Rather, this module only provides this function so
* clients such as startSES.js can use it to do so on the functions
* they whitelist.
*
* <p>If the "caller" property of strict functions are not already
* harmless, then this platform cannot be repaired to be
* SES-safe. The only reason why {@code makeCallerHarmless} must
* work on strict functions in addition to built-in is that some of
* the other repairs below will replace some of the built-ins with
* strict functions, so startSES.js will apply {@code
* makeCallerHarmless} blindly to both strict and built-in
* functions. {@code makeCallerHarmless} simply need not to complete
* without breaking anything when given a strict function argument.
*/
ses.makeCallerHarmless = function assumeCallerHarmless(func, path) {
return 'Apparently fine';
};
/**
* By the time this module exits, either this is repaired to be a
* function that is adequate to make the "arguments" property of a
* strict or built-in function harmess, or this module has reported
* a failure to repair.
*
* Exactly analogous to {@code makeCallerHarmless}, but for
* "arguments" rather than "caller".
*/
ses.makeArgumentsHarmless = function assumeArgumentsHarmless(func, path) {
return 'Apparently fine';
};
/**
* "makeTamperProof()" returns a "tamperProof(obj)" function that
* acts like "Object.freeze(obj)", except that, if obj is a
* <i>prototypical</i> object (defined below), it ensures that the
* effect of freezing properties of obj does not suppress the
* ability to override these properties on derived objects by simple
* assignment.
*
* <p>Because of lack of sufficient foresight at the time, ES5
* unfortunately specified that a simple assignment to a
* non-existent property must fail if it would override a
* non-writable data property of the same name. (In retrospect, this
* was a mistake, but it is now too late and we must live with the
* consequences.) As a result, simply freezing an object to make it
* tamper proof has the unfortunate side effect of breaking
* previously correct code that is considered to have followed JS
* best practices, if this previous code used assignment to
* override.
*
* <p>To work around this mistake, tamperProof(obj) detects if obj
* is <i>prototypical</i>, i.e., is an object whose own
* "constructor" is a function whose "prototype" is this obj. For example,
* Object.prototype and Function.prototype are prototypical. If so,
* then when tamper proofing it, prior to freezing, replace all its
* configurable own data properties with accessor properties which
* simulate what we should have specified -- that assignments to
* derived objects succeed if otherwise possible.
*
* <p>Some platforms (Chrome and Safari as of this writing)
* implement the assignment semantics ES5 should have specified
* rather than what it did specify.
* "test_ASSIGN_CAN_OVERRIDE_FROZEN()" below tests whether we are on
* such a platform. If so, "repair_ASSIGN_CAN_OVERRIDE_FROZEN()"
* replaces "makeTamperProof" with a function that simply returns
* "Object.freeze", since the complex workaround here is not needed
* on those platforms.
*
* <p>"makeTamperProof" should only be called after the trusted
* initialization has done all the monkey patching that it is going
* to do on the Object.* methods, but before any untrusted code runs
* in this context.
*/
var makeTamperProof = function defaultMakeTamperProof() {
// Sample these after all trusted monkey patching initialization
// but before any untrusted code runs in this frame.
var gopd = Object.getOwnPropertyDescriptor;
var gopn = Object.getOwnPropertyNames;
var getProtoOf = Object.getPrototypeOf;
var freeze = Object.freeze;
var isFrozen = Object.isFrozen;
var defProp = Object.defineProperty;
function tamperProof(obj) {
if (obj !== Object(obj)) { return obj; }
var func;
if (typeof obj === 'object' &&
!!gopd(obj, 'constructor') &&
typeof (func = obj.constructor) === 'function' &&
func.prototype === obj &&
!isFrozen(obj)) {
strictForEachFn(gopn(obj), function(name) {
var value;
function getter() {
if (obj === this) { return value; }
if (this === void 0 || this === null) { return void 0; }
var thisObj = Object(this);
if (!!gopd(thisObj, name)) { return this[name]; }
// TODO(erights): If we can reliably uncurryThis() in
// repairES5.js, the next line should be:
// return callFn(getter, getProtoOf(thisObj));
return getter.call(getProtoOf(thisObj));
}
function setter(newValue) {
if (obj === this) {
throw new TypeError('Cannot set virtually frozen property: ' +
name);
}
if (!!gopd(this, name)) {
this[name] = newValue;
}
// TODO(erights): Do all the inherited property checks
defProp(this, name, {
value: newValue,
writable: true,
enumerable: true,
configurable: true
});
}
var desc = gopd(obj, name);
if (desc.configurable && 'value' in desc) {
value = desc.value;
getter.prototype = null;
setter.prototype = null;
defProp(obj, name, {
get: getter,
set: setter,
// We should be able to omit the enumerable line, since it
// should default to its existing setting.
enumerable: desc.enumerable,
configurable: false
});
}
});
}
return freeze(obj);
}
return tamperProof;
};
var needToTamperProof = [];
/**
* Various repairs may expose non-standard objects that are not
* reachable from startSES's root, and therefore not freezable by
* startSES's normal whitelist traversal. However, freezing these
* during repairES5.js may be too early, as it is before WeakMap.js
* has had a chance to monkey patch Object.freeze if necessary, in
* order to install hidden properties for its own use before the
* object becomes non-extensible.
*/
function rememberToTamperProof(obj) {
needToTamperProof.push(obj);
}
/**
* Makes and returns a tamperProof(obj) function, and uses it to
* tamper proof all objects whose tamper proofing had been delayed.
*
* <p>"makeDelayedTamperProof()" must only be called once.
*/
var makeDelayedTamperProofCalled = false;
ses.makeDelayedTamperProof = function makeDelayedTamperProof() {
if (makeDelayedTamperProofCalled) {
throw "makeDelayedTamperProof() must only be called once.";
}
var tamperProof = makeTamperProof();
strictForEachFn(needToTamperProof, tamperProof);
needToTamperProof = void 0;
makeDelayedTamperProofCalled = true;
return tamperProof;
};
/**
* Where the "that" parameter represents a "this" that should have
* been bound to "undefined" but may be bound to a global or
* globaloid object.
*
* <p>The "desc" parameter is a string to describe the "that" if it
* is something unexpected.
*/
function testGlobalLeak(desc, that) {
if (that === void 0) { return false; }
if (that === global) { return true; }
if (objToString.call(that) === '[object Window]') { return true; }
return desc + ' leaked as: ' + that;
}
////////////////////// Tests /////////////////////
//
// Each test is a function of no arguments that should not leave any
// significant side effects, which tests for the presence of a
// problem. It returns either
// <ul>
// <li>false, meaning that the problem does not seem to be present.
// <li>true, meaning that the problem is present in a form that we expect.
// <li>a non-empty string, meaning that there seems to be a related
// problem, but we're seeing a symptom different than what we
// expect. The string should describe the new symptom. It must
// be non-empty so that it is truthy.
// </ul>
// All the tests are run first to determine which corresponding
// repairs to attempt. Then these repairs are run. Then all the
// tests are rerun to see how they were effected by these repair
// attempts. Finally, we report what happened.
/**
* If {@code Object.getOwnPropertyNames} is missing, we consider
* this to be an ES3 browser which is unsuitable for attempting to
* run SES.
*
* <p>If {@code Object.getOwnPropertyNames} is missing, there is no
* way to emulate it.
*/
function test_MISSING_GETOWNPROPNAMES() {
return !('getOwnPropertyNames' in Object);
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=64250
*
* <p>No workaround attempted. Just reporting that this platform is
* not SES-safe.
*/
function test_GLOBAL_LEAKS_FROM_GLOBAL_FUNCTION_CALLS() {
global.___global_test_function___ = function() { return this; };
var that = ___global_test_function___();
delete global.___global_test_function___;
return testGlobalLeak('Global func "this"', that);
}
/**
* Detects whether the most painful ES3 leak is still with us.
*/
function test_GLOBAL_LEAKS_FROM_ANON_FUNCTION_CALLS() {
var that = (function(){ return this; })();
return testGlobalLeak('Anon func "this"', that);
}
var strictThis = this;
/**
*
*/
function test_GLOBAL_LEAKS_FROM_STRICT_THIS() {
return testGlobalLeak('Strict "this"', strictThis);
}
/**
* Detects
* https://bugs.webkit.org/show_bug.cgi?id=51097
* https://bugs.webkit.org/show_bug.cgi?id=58338
* http://code.google.com/p/v8/issues/detail?id=1437
*
* <p>No workaround attempted. Just reporting that this platform is
* not SES-safe.
*/
function test_GLOBAL_LEAKS_FROM_BUILTINS() {
var v = {}.valueOf;
var that = 'dummy';
try {
that = v();
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'valueOf() threw: ' + err;
}
if (that === void 0) {
// Should report as a safe spec violation
return false;
}
return testGlobalLeak('valueOf()', that);
}
/**
*
*/
function test_GLOBAL_LEAKS_FROM_GLOBALLY_CALLED_BUILTINS() {
global.___global_valueOf_function___ = {}.valueOf;
var that = 'dummy';
try {
that = ___global_valueOf_function___();
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'valueOf() threw: ' + err;
} finally {
delete global.___global_valueOf_function___;
}
if (that === void 0) {
// Should report as a safe spec violation
return false;
}
return testGlobalLeak('Global valueOf()', that);
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=55736
*
* <p>As of this writing, the only major browser that does implement
* Object.getOwnPropertyNames but not Object.freeze etc is the
* released Safari 5 (JavaScriptCore). The Safari beta 5.0.4
* (5533.20.27, r84622) already does implement freeze, which is why
* this WebKit bug is listed as closed. When the released Safari has
* this fix, we can retire this kludge.
*
* <p>This kludge is <b>not</b> safety preserving. The emulations it
* installs if needed do not actually provide the safety that the
* rest of SES relies on.
*/
function test_MISSING_FREEZE_ETC() {
return !('freeze' in Object);
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=1530
*
* <p>Detects whether the value of a function's "prototype" property
* as seen by normal object operations might deviate from the value
* as seem by the reflective {@code Object.getOwnPropertyDescriptor}
*/
function test_FUNCTION_PROTOTYPE_DESCRIPTOR_LIES() {
function foo() {}
Object.defineProperty(foo, 'prototype', { value: {} });
return foo.prototype !==
Object.getOwnPropertyDescriptor(foo, 'prototype').value;
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=55537
*
* This bug is fixed on the latest Safari beta 5.0.5 (5533.21.1,
* r88603). When the released Safari has this fix, we can retire
* this kludge.
*
* <p>This kludge is safety preserving.
*/
function test_MISSING_CALLEE_DESCRIPTOR() {
function foo(){}
if (Object.getOwnPropertyNames(foo).indexOf('callee') < 0) { return false; }
if (foo.hasOwnProperty('callee')) {
return 'Empty strict function has own callee';
}
return true;
}
/**
* A strict delete should either succeed, returning true, or it
* should fail by throwing a TypeError. Under no circumstances
* should a strict delete return false.
*
* <p>This case occurs on IE10preview2.
*/
function test_STRICT_DELETE_RETURNS_FALSE() {
if (!RegExp.hasOwnProperty('rightContext')) { return false; }
var deleted;
try {
deleted = delete RegExp.rightContext;
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'Deletion failed with: ' + err;
}
if (deleted) { return false; }
return true;
}
/**
* Detects https://bugzilla.mozilla.org/show_bug.cgi?id=591846
* as applied to the RegExp constructor.
*
* <p>Note that Mozilla lists this bug as closed. But reading that
* bug thread clarifies that is partially because the code in {@code
* repair_REGEXP_CANT_BE_NEUTERED} enables us to work around the
* non-configurability of the RegExp statics.
*/
function test_REGEXP_CANT_BE_NEUTERED() {
if (!RegExp.hasOwnProperty('leftContext')) { return false; }
var deleted;
try {
deleted = delete RegExp.leftContext;
} catch (err) {
if (err instanceof TypeError) { return true; }
return 'Deletion failed with: ' + err;
}
if (!RegExp.hasOwnProperty('leftContext')) { return false; }
if (deleted) {
return 'Deletion of RegExp.leftContext did not succeed.';
} else {
// This case happens on IE10preview2, as demonstrated by
// test_STRICT_DELETE_RETURNS_FALSE.
return true;
}
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=1393
*
* <p>This kludge is safety preserving.
*/
function test_REGEXP_TEST_EXEC_UNSAFE() {
(/foo/).test('xfoox');
var match = new RegExp('(.|\r|\n)*','').exec()[0];
if (match === 'undefined') { return false; }
if (match === 'xfoox') { return true; }
return 'regExp.exec() does not match against "undefined".';
}
/**
* Detects https://bugs.webkit.org/show_bug.cgi?id=26382
*
* <p>As of this writing, the only major browser that does implement
* Object.getOwnPropertyNames but not Function.prototype.bind is
* Safari 5 (JavaScriptCore), including the current Safari beta
* 5.0.4 (5533.20.27, r84622).
*
* <p>This kludge is safety preserving. But see
* https://bugs.webkit.org/show_bug.cgi?id=26382#c25 for why this
* kludge cannot faithfully implement the specified semantics.
*
* <p>See also https://bugs.webkit.org/show_bug.cgi?id=42371
*/
function test_MISSING_BIND() {
return !('bind' in Function.prototype);
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=892
*
* <p>This tests whether the built-in bind method violates the spec
* by calling the original using its current .apply method rather
* than the internal [[Call]] method. The workaround is the same as
* for test_MISSING_BIND -- to replace the built-in bind with one
* written in JavaScript. This introduces a different bug though: As
* https://bugs.webkit.org/show_bug.cgi?id=26382#c29 explains, a
* bind written in JavaScript cannot emulate the specified currying
* over the construct behavior, and so fails to enable a var-args
* {@code new} operation.
*/
function test_BIND_CALLS_APPLY() {
if (!('bind' in Function.prototype)) { return false; }
var applyCalled = false;
function foo() { return [].slice.call(arguments,0).join(','); }
foo.apply = function fakeApply(self, args) {
applyCalled = true;
return Function.prototype.apply.call(this, self, args);
};
var b = foo.bind(33,44);
var answer = b(55,66);
if (applyCalled) { return true; }
if (answer === '44,55,66') { return false; }
return 'Bind test returned "' + answer + '" instead of "44,55,66".';
}
/**
* Demonstrates the point made by comment 29
* https://bugs.webkit.org/show_bug.cgi?id=26382#c29
*
* <p>Tests whether Function.prototype.bind curries over
* construction ({@code new}) behavior. A built-in bind should. A
* bind emulation written in ES5 can't.
*/
function test_BIND_CANT_CURRY_NEW() {
function construct(f, args) {
var bound = Function.prototype.bind.apply(f, [null].concat(args));
return new bound();
}
var d;
try {
d = construct(Date, [1957, 4, 27]);
} catch (err) {
if (err instanceof TypeError) { return true; }
return 'Curries construction failed with: ' + err;
}
if (typeof d === 'string') { return true; } // Opera
var str = objToString.call(d);
if (str === '[object Date]') { return false; }
return 'Unexpected ' + str + ': ' + d;
}
/**
* Detects http://code.google.com/p/google-caja/issues/detail?id=1362
*
* <p>This is an unfortunate oversight in the ES5 spec: Even if
* Date.prototype is frozen, it is still defined to be a Date, and
* so has mutable state in internal properties that can be mutated
* by the primordial mutation methods on Date.prototype, such as
* {@code Date.prototype.setFullYear}.
*
* <p>This kludge is safety preserving.
*/
function test_MUTABLE_DATE_PROTO() {
try {
Date.prototype.setFullYear(1957);
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'Mutating Date.prototype failed with: ' + err;
}
var v = Date.prototype.getFullYear();
Date.prototype.setFullYear(NaN); // hopefully undoes the damage
if (v !== v && typeof v === 'number') {
// NaN indicates we're probably ok.
// TODO(erights) Should we report this as a symptom anyway, so
// that we get the repair which gives us a reliable TypeError?
return false;
}
if (v === 1957) { return true; }
return 'Mutating Date.prototype did not throw';
}
/**
* Detects https://bugzilla.mozilla.org/show_bug.cgi?id=656828
*
* <p>A bug in the current FF6.0a1 implementation: Even if
* WeakMap.prototype is frozen, it is still defined to be a WeakMap,
* and so has mutable state in internal properties that can be
* mutated by the primordial mutation methods on WeakMap.prototype,
* such as {@code WeakMap.prototype.set}.
*
* <p>This kludge is safety preserving.
*
* <p>TODO(erights): Update the ES spec page to reflect the current
* agreement with Mozilla.
*/
function test_MUTABLE_WEAKMAP_PROTO() {
if (typeof WeakMap !== 'function') { return false; }
var x = {};
try {
WeakMap.prototype.set(x, 86);
} catch (err) {
if (err instanceof TypeError) { return false; }
return 'Mutating WeakMap.prototype failed with: ' + err;
}
var v = WeakMap.prototype.get(x);
// Since x cannot escape, there's no observable damage to undo.
if (v === 86) { return true; }
return 'Mutating WeakMap.prototype did not throw';
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=1447
*
* <p>This bug is fixed as of V8 r8258 bleeding-edge, but is not yet
* available in the latest dev-channel Chrome (13.0.782.15 dev).
*
* <p>Unfortunately, an ES5 strict method wrapper cannot emulate
* absence of a [[Construct]] behavior, as specified for the Chapter
* 15 built-in methods. The installed wrapper relies on {@code
* Function.prototype.apply}, as inherited by original, obeying its
* contract.
*
* <p>This kludge is safety preserving but non-transparent, in that
* the real forEach is frozen even in the success case, since we
* have to freeze it in order to test for this failure. We could
* repair this non-transparency by replacing it with a transparent
* wrapper (as http://codereview.appspot.com/5278046/ does), but
* since the SES use of this will freeze it anyway and the
* indirection is costly, we choose not to for now.
*/
function test_NEED_TO_WRAP_FOREACH() {
if (!('freeze' in Object)) {
// Object.freeze is still absent on released Android and would
// cause a bogus bug detection in the following try/catch code.
return false;
}
if (Array.prototype.forEach !== builtInForEach) {
// If it is already wrapped, we are confident the problem does
// not occur, and we need to skip the test to avoid freezing the
// wrapper.
return false;
}
try {
['z'].forEach(function(){ Object.freeze(Array.prototype.forEach); });
return false;
} catch (err) {
if (err instanceof TypeError) { return true; }
return 'freezing forEach failed with ' + err;
}
}
/**
* Detects http://code.google.com/p/v8/issues/detail?id=2273
*
* A strict mode function should receive a non-coerced 'this'
* value. That is, in strict mode, if 'this' is a primitive, it
* should not be boxed
*/
function test_FOREACH_COERCES_THISOBJ() {
"use strict";
var needsWrapping = true;
[1].forEach(function(){ needsWrapping = ("string" != typeof this); }, "f");
return needsWrapping;
}
/**
* <p>Sometimes, when trying to freeze an object containing an
* accessor property with a getter but no setter, Chrome <= 17 fails
* with <blockquote>Uncaught TypeError: Cannot set property ident___
* of #<Object> which has only a getter</blockquote>. So if
* necessary, this kludge overrides {@code Object.defineProperty} to
* always install a dummy setter in lieu of the absent one.
*
* <p>Since this problem seems to have gone away as of Chrome 18, it
* is no longer as important to isolate and report it.
*
* <p>TODO(erights): We should also override {@code
* Object.getOwnPropertyDescriptor} to hide the presence of the
* dummy setter, and instead report an absent setter.
*/
function test_NEEDS_DUMMY_SETTER() {
if (NEEDS_DUMMY_SETTER_repaired) { return false; }
if (typeof navigator === 'undefined') { return false; }
var ChromeMajorVersionPattern = (/Chrome\/(\d*)\./);
var match = ChromeMajorVersionPattern.exec(navigator.userAgent);
if (!match) { return false; }
var ver = +match[1];
return ver <= 17;
}
/** we use this variable only because we haven't yet isolated a test
* for the problem. */
var NEEDS_DUMMY_SETTER_repaired = false;
/**
* Detects http://code.google.com/p/chromium/issues/detail?id=94666
*/
function test_FORM_GETTERS_DISAPPEAR() {
function getter() { return 'gotten'; }
if (typeof document === 'undefined' ||
typeof document.createElement !== 'function') {
// likely not a browser environment
return false;
}
var f = document.createElement("form");
try {
Object.defineProperty(f, 'foo', {
get: getter,
set: void 0
});
} catch (err) {
// Happens on Safari 5.0.2 on IPad2.
return 'defining accessor on form failed with: ' + err;
}
var desc = Object.getOwnPropertyDescriptor(f, 'foo');
if (desc.get === getter) { return false; }
if (desc.get === void 0) { return true; }
return 'Getter became ' + desc.get;
}
/**
* Detects https://bugzilla.mozilla.org/show_bug.cgi?id=637994
*
* <p>On Firefox 4 an inherited non-configurable accessor property
* appears to be an own property of all objects which inherit this
* accessor property. This is fixed as of Forefox Nightly 7.0a1
* (2011-06-21).
*
* <p>Our workaround wraps hasOwnProperty, getOwnPropertyNames, and
* getOwnPropertyDescriptor to heuristically decide when an accessor
* property looks like it is apparently own because of this bug, and
* suppress reporting its existence.
*
* <p>However, it is not feasible to likewise wrap JSON.stringify,
* and this bug will cause JSON.stringify to be misled by inherited
* enumerable non-configurable accessor properties. To prevent this,