-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsfunswarm.js
2173 lines (1690 loc) · 74.5 KB
/
jsfunswarm.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
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is jsfunfuzz.
*
* The Initial Developer of the Original Code is
* Jesse Ruderman.
* Portions created by the Initial Developer are Copyright (C) 2006-2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/********************
* ENGINE DETECTION *
********************/
// jsfunfuzz is best run in a command-line shell. It can also run in
// a web browser, but you might have trouble reproducing bugs that way.
var ENGINE_UNKNOWN = 0;
var ENGINE_SPIDERMONKEY = 1;
var ENGINE_JAVASCRIPTCORE = 2;
var engine = ENGINE_UNKNOWN;
var jsshell = (typeof window == "undefined");
if (jsshell) {
dump = print;
dumpln = print;
printImportant = function(s) { dumpln("***"); dumpln(s); }
if (typeof line2pc == "function") {
engine = ENGINE_SPIDERMONKEY;
version(180); // 170: make "yield" and "let" work. 180: sane for..in.
options("anonfunfix");
} else if (typeof debug == "function") {
engine = ENGINE_JAVASCRIPTCORE;
}
} else {
if (navigator.userAgent.indexOf("WebKit") != -1) {
engine = ENGINE_JAVASCRIPTCORE;
// This worked in Safari 3.0, but it might not work in Safari 3.1.
dump = function(s) { console.log(s); }
} else if (navigator.userAgent.indexOf("Gecko") != -1) {
engine = ENGINE_SPIDERMONKEY;
} else if (typeof dump != "function") {
// In other browsers, jsfunfuzz does not know how to log anything.
dump = function() { };
}
dumpln = function(s) { dump(s + "\n"); }
printImportant = function(s) {
dumpln(s);
var p = document.createElement("pre");
p.appendChild(document.createTextNode(s));
document.body.appendChild(p);
}
}
if (typeof gc == "undefined")
gc = function(){};
function simpleSource(s)
{
function hexify(c)
{
var code = c.charCodeAt(0);
var hex = code.toString(16);
while (hex.length < 4)
hex = "0" + hex;
return "\\u" + hex;
}
if (typeof s == "string")
return "\"" + s.replace(/\\/g, "\\\\")
.replace(/\"/g, "\\\"")
.replace(/\0/g, "\\0")
.replace(/\n/g, "\\n")
.replace(/[^ -~]/g, hexify) // not space (32) through tilde (126)
+ "\"";
else
return "" + s; // hope this is right ;) should work for numbers.
}
var haveRealUneval = (typeof uneval == "function");
if (!haveRealUneval)
uneval = simpleSource;
/*
if (engine == ENGINE_UNKNOWN)
printImportant("Targeting an unknown JavaScript engine!");
else if (engine == ENGINE_SPIDERMONKEY)
printImportant("Targeting SpiderMonkey / Gecko.");
else if (engine == ENGINE_JAVASCRIPTCORE)
printImportant("Targeting JavaScriptCore / WebKit.");
*/
function printAndStop(s)
{
printImportant(s)
if (jsshell)
quit();
}
/***********************
* AVOIDING KNOWN BUGS *
***********************/
function whatToTestSpidermonkey(code)
{
return {
// Exclude things here if decompiling the function causes a crash.
allowDecompile: true
&& !(code.match( /for.*for.*in.*in/ )), // avoid bug 376370
// Exclude things here if decompiling returns something bogus that won't compile.
checkRecompiling: true
&& (code.indexOf("#") == -1) // avoid bug 367731
&& !( code.match( /for.*\(.*in.*const/ )) // avoid bug 352083, with for loops or array comprehensions
&& !( code.match( /arguments.*\:\:/ )) // avoid bug 355506
&& !( code.match( /\:.*for.*\(.*var.*\)/ )) // avoid bug 352921
&& !( code.match( /\:.*for.*\(.*let.*\)/ )) // avoid bug 352921
&& !( code.match( /do.*let.*while/ )) // avoid bug 352421
&& !( code.match( /for.*let.*\).*function/ )) // avoid bug 352735 (more rebracing stuff)
&& !( code.match( /for.*\(.*\(.*in.*;.*;.*\)/ )) // avoid bug 353255
&& !( code.match( /new.*\.\./ )) // avoid bug 382339
&& !( code.match( /new.*\.\(/ )) // avoid bug 377059 most of the time
&& !( code.match( /while.*for.*in/ )) // avoid bug 381963
,
// Exclude things here if decompiling returns something incorrect or non-canonical, but that will compile.
checkForMismatch: true
&& !( code.match( /const.*if/ )) // avoid bug 352985
&& !( code.match( /if.*const/ )) // avoid bug 352985
&& !( code.match( /const.*arguments/ )) // avoid bug 355480
&& !( code.match( /var.*arguments/ )) // avoid bug 355480
&& !( code.match( /let.*,/ )) // avoid bug 382400
&& !( code.match( /for.*;.*;/ )) // avoid bug 381195 :(
&& !( code.match( /\[.*\].*=.*\[.*=.*\]/ )) // avoid bug 376558
&& !( code.match( /with.*try.*function/ )) // avoid bug 418285
&& !( code.match( /if.*try.*function/ )) // avoid bug 418285
&& (code.indexOf("-0") == -1) // constant folding isn't perfect
&& (code.indexOf("-1") == -1) // constant folding isn't perfect
&& (code.indexOf("default") == -1) // avoid bug 355509 harder
&& (code.indexOf("delete") == -1) // avoid bug 352027, which won't be fixed for a while :(
&& (code.indexOf("const") == -1) // avoid bug 352985, bug 353020, and bug 355480 :(
&& (code.indexOf("import") == -1) // avoid bug 350681
&& (code.indexOf("export") == -1) // avoid bug 350681
&& (code.indexOf("?") == -1) // avoid bug 355203
&& (code.indexOf("p.z") == -1) // avoid bug 355672 (this is the most common trigger)
// avoid bug 352085: keep operators that coerce to number (or integer)
// at constant-folding time (?) away from strings
&&
(
(code.indexOf("\"") == -1 && code.indexOf("\'") == -1)
||
(
(code.indexOf("%") == -1)
&& (code.indexOf("/") == -1)
&& (code.indexOf("*") == -1)
&& (code.indexOf("-") == -1)
&& (code.indexOf(">>") == -1)
&& (code.indexOf("<<") == -1)
)
)
,
allowExec: true
&& code.indexOf("for..in") == -1 // for (x.y in x) causes infinite loops :(
&& code.indexOf("finally") == -1 // avoid bug 380018 and bug 381107 :(
&& code.indexOf("valueOf") == -1 // avoid bug 355829
&& code.indexOf("<>") == -1 // avoid bug 334628, hopefully
&& (jsshell || code.indexOf("nogeckoex") == -1)
&& !( code.match( /delete.*Function/ )) // avoid bug 352604 (exclusion needed despite the realFunction stuff?!)
&& !( code.match( /function.*::.*=/ )) // avoid ????
,
allowIter: true,
checkUneval: true
// exclusions won't be perfect, since functions can return things they don't
// appear to contain, e.g. with "return x;"
&& (code.indexOf("<") == -1 || code.indexOf(".") == -1) // avoid bug 379525
&& (code.indexOf("<>") == -1) // avoid bug 334628
&& code.indexOf("RegExp") == -1 // avoid bug 362582
};
}
function whatToTestJavaScriptCore(code)
{
return {
// Exclude things here if decompiling the function causes a crash.
allowDecompile: true,
checkRecompiling: true,
checkForMismatch: true
&& !code.match( /new.*\(.*\).*\./ ) // avoid bug 17931
&& !code.match( /new.*\(.*\).*\[/ ) // avoid bug 17931
,
allowExec: true
&& !code.match(/with.*const/) // avoid bug 17924
&& !code.match(/catch.*const/) // avoid bug 17924
&& !code.match(/break.*finally/) // avoid bug 17932
&& !code.match(/continue.*finally/) // avoid bug 17932
,
allowIter: false, // JavaScriptCore does not support |yield| and |Iterator|
checkUneval: false // JavaScriptCore does not support |uneval|
};
}
function whatToTestGeneric(code)
{
return {
allowDecompile: true,
checkRecompiling: true,
checkForMismatch: true,
allowExec: true,
allowIter: ("Iterator" in this),
checkUneval: haveRealUneval
};
}
if (engine == ENGINE_SPIDERMONKEY)
whatToTest = whatToTestSpidermonkey;
else if (engine == ENGINE_JAVASCRIPTCORE)
whatToTest = whatToTestJavaScriptCore;
else
whatToTest = whatToTestGeneric;
/*******************
* DRIVING & TESTS *
*******************/
var allMakers = [];
function totallyRandom(depth) {
var dr = depth + (rnd(5) - 2); // !
return (rndElt(allMakers))(dr);
}
function init()
{
for (var f in this)
if (f.indexOf("make") == 0 && typeof this[f] == "function")
allMakers.push(this[f]);
}
function start()
{
init();
// dumpln(uneval([f.name for each (f in allMakers)]));
count = 0;
if (jsshell) {
// Number of iterations: 1000 is good for use with multi_timed_run.py. (~40 seconds on a PowerBook G4; reduction isn't bad.)
// Raise for use without multi_timed_run.py (perhaps to Infinity).
// Lower for use with WAY_TOO_MUCH_GC, to 70 or so.
for (var i = 0; i < 200; ++i)
testOne();
// dumpln("It's looking good!"); // Magic string that multi_timed_run.py looks for
} else {
setTimeout(testStuffForAWhile, 200);
}
}
function testStuffForAWhile()
{
for (var j = 0; j < 100; ++j)
testOne();
if (count % 10000 < 100)
printImportant("Iterations: " + count);
setTimeout(testStuffForAWhile, 30);
}
function testOne()
{
++count;
var code = makeStatement(8);
// if (rnd(10) == 1) {
// var dp = "/*infloop-deParen*/" + rndElt(deParen(code));
// if (dp)
// code = dp;
// }
// dumpln("dumpln(\"tryItOut\" + " + uneval(code) + ");");
// dumpln("dumpln(\"tryItOut "+count+"\")")
dumpln("tryItOut(" + uneval(code) + ");");
// tryItOut(code);
}
function tryItOut(code)
{
// regexps can't match across lines, so strip line breaks.
var wtt = whatToTest(code.replace(/\n/g, " ").replace(/\r/g, " "));
// This section applies to all engines, so it should only be used for avoiding hangs.
wtt.allowExec = wtt.allowExec
&& code.indexOf("infloop") == -1
&& !( code.match( /const.*for/ )) // can be an infinite loop: function() { const x = 1; for each(x in ({a1:1})) dumpln(3); }
&& !( code.match( /for.*const/ )) // can be an infinite loop: for each(x in ...); const x;
&& !( code.match( /for.*in.*uneval/ )) // can be slow to loop through the huge string uneval(this), for example
&& !( code.match( /for.*for.*for.*for.*for/ )) // nested for loops (array comprehensions, etc) can take a while
;
if(verbose) {
dumpln("Verbose, count: " + count);
dumpln("allowExec=" + wtt.allowExec + ", allowDecompile=" + wtt.allowDecompile + ", checkRecompiling=" + wtt.checkRecompiling + ", checkForMismatch=" + wtt.checkForMismatch + ", allowIter=" + wtt.allowIter + ", checkUneval=" + wtt.checkUneval);
}
// tryHalves(code);
var f = tryCompiling(code, wtt.allowExec);
if (0) {
if (wtt.allowExec && ('sandbox' in this)) {
f = null;
if (trySandboxEval(code, false)) {
dumpln("Trying it again to see if it's a 'real leak' (???)")
trySandboxEval(code, true);
}
}
return;
}
if (f && wtt.allowDecompile) {
tryRoundTripStuff(f, code, wtt.checkRecompiling, wtt.checkForMismatch);
}
var rv = null;
if (wtt.allowExec && f) {
rv = tryRunning(f);
tryEnsureSanity();
if (0 && engine == ENGINE_SPIDERMONKEY) {
tryTestDVG(code);
tryEnsureSanity();
}
}
if (wtt.allowIter && rv && typeof rv == "object") {
tryIteration(rv);
tryEnsureSanity();
}
// "checkRecompiling && checkForMismatch" here to catch returned functions
if (wtt.checkRecompiling && wtt.checkForMismatch && wtt.checkUneval && rv && typeof rv == "object") {
testUneval(rv);
}
if (count % 1000 == 0) {
dumpln("Paranoid GC!")
dumpln(count);
realGC();
}
if(verbose)
dumpln("Done trying out that function!");
dumpln("");
}
function tryTestDVG(code)
{
var fullCode = "(function() { try { \n" + code + "\n; throw 1; } catch(exx) { this.nnn.nnn } })()";
try {
eval(fullCode);
} catch(e) {
if (e.message != "this.nnn is undefined") {
printAndStop("Wrong error message: " + e);
}
}
}
function tryCompiling(code, allowExec)
{
try {
// Try two methods of creating functions, just in case there are differences.
if (count % 2 == 0 && allowExec) {
if (verbose)
dumpln("About to compile, using eval hack.")
return eval("(function(){" + code + "});"); // Disadvantage: "}" can "escape", allowing code to *execute* that we only intended to compile. Hence the allowExec check.
}
else {
if (verbose)
dumpln("About to compile, using new Function.")
return new Function(code);
}
} catch(compileError) {
dumpln("Compiling threw: " + errorToString(compileError));
return null;
}
}
function trySandboxEval(code, isRetry)
{
// (function(){})() wrapping allows "return" when it's allowed outside.
// The line breaks are to allow single-line comments within code ("//" and "<!--").
if (!sandbox) {
sandbox = evalcx("");
}
var rv = null;
try {
rv = evalcx("(function(){\n" + code + "\n})();", sandbox);
} catch(e) {
rv = "Error from sandbox: " + errorToString(e);
}
try {
if (typeof rv != "undefined")
dumpln(rv);
} catch(e) {
dumpln("Sandbox error printing: " + errorToString(e));
}
rv = null;
if (1 || count % 100 == 0) { // count % 100 *here* is sketchy.
dumpln("Done with this sandbox.");
sandbox = null;
gc();
var currentHeapCount = countHeap()
dumpln("countHeap: " + currentHeapCount);
if (currentHeapCount > maxHeapCount) {
if (maxHeapCount != 0)
dumpln("A new record by " + (currentHeapCount - maxHeapCount) + "!");
if (isRetry)
throw new Error("Found a leak!");
maxHeapCount = currentHeapCount;
return true;
}
}
return false;
}
function tryRoundTripStuff(f, code, checkRecompiling, checkForMismatch)
{
if (verbose)
dumpln("About to do the 'toString' round-trip test");
// Functions are prettier with line breaks, so test toString before uneval.
checkRoundTripToString(f, code, checkRecompiling, checkForMismatch);
if (checkRecompiling && checkForMismatch && engine == ENGINE_SPIDERMONKEY) {
try {
checkForExtraParens(f, code);
} catch(e) { /* bug 355667 is annoying here too */ }
}
if (haveRealUneval) {
if (verbose)
dumpln("About to do the 'uneval' round-trip test");
checkRoundTripUneval(f, code, checkRecompiling, checkForMismatch);
}
}
function tryRunning(f)
{
try {
if (verbose)
dumpln("About to run it!");
rv = f();
if (verbose)
dumpln("It ran!");
return rv;
} catch(runError) {
if(verbose)
dumpln("Running threw! About to toString to error.");
dumpln("Running threw: " + errorToString(runError));
return null;
}
}
// Store things now so we can restore sanity later.
var realEval = eval;
var realFunction = Function;
var realGC = gc;
function tryEnsureSanity()
{
// At least one bug in the past has put exceptions in strange places. This also catches "eval getter" issues.
try { eval("") } catch(e) { dumpln("That really shouldn't have thrown: " + errorToString(e)); }
// Restore important stuff that might have been broken as soon as possible :)
if ('unwatch' in this) {
this.unwatch("eval")
this.unwatch("Function")
this.unwatch("gc")
}
if ('__defineSetter__' in this) {
// The only way to get rid of getters/setters is to delete the property.
delete eval;
// delete Function; // doh, this triggers bug 352604!
delete gc;
}
eval = realEval;
Function = realFunction;
gc = realGC;
// These can fail if the page creates a getter for "eval", for example.
if (!eval)
printImportant("WTF did my |eval| go?");
if (eval != realEval)
printImportant("WTF did my |eval| get replaced by?")
if (Function != realFunction)
printImportant("WTF did my |Function| get replaced by?")
}
function tryIteration(rv)
{
try {
if (!(Iterator(rv) === rv))
return; // not an iterator
}
catch(e) {
// Is it a bug that it's possible to end up here? Probably not!
dumpln("Error while trying to determine whether it's an iterator!");
dumpln("The error was: " + e);
return;
}
dumpln("It's an iterator!");
try {
var iterCount = 0;
var iterValue;
// To keep Safari-compatibility, don't use "let", "each", etc.
for /* each */ ( /* let */ iterValue in rv)
++iterCount;
dumpln("Iterating succeeded, iterCount == " + iterCount);
} catch (iterError) {
dumpln("Iterating threw!");
dumpln("Iterating threw: " + errorToString(iterError));
}
}
function testUneval(o)
{
// If it happens to return an object, especially an array or hash,
// let's test uneval. Note that this is a different code path than decompiling
// an array literal within a function, although the two code paths often have
// similar bugs!
var uo, euo, ueuo;
try {
uo = uneval(o);
} catch(e) {
if (errorToString(e).indexOf("called on incompatible") != -1) {
dumpln("Ignoring bug 379528!".toUpperCase());
return;
}
else
throw e;
}
if (uo == "({})") {
// ?
return;
}
var uowlb = uo.replace(/\n/g, " ").replace(/\r/g, " ");
dumpln("uneval returned the string: " + uo);
if ( true
&& uo.indexOf("[native code]") == -1 // ignore bug 384756
&& uo.indexOf(":<") == -1 // ignore the combination of bug 334628 with bug 379519(a)
&& (uo.indexOf("#") == -1 || uo.indexOf("<") == -1) // ignore bug 379519(b)
&& (uo.indexOf("#") == -1) // ignore bug 328745 (ugh)
&& (uo.indexOf("{") == -1 || uo.indexOf(":") == -1) // ignore bug 379525 hard (ugh!)
&& uo.indexOf("NaN") == -1 // ignore bug 379521
&& uo.indexOf("Infinity") == -1 // ignore bug 379521
&& uo.indexOf("[,") == -1 // avoid bug 379551
&& uo.indexOf(", ,") == -1 // avoid bug 379551
&& uo.indexOf(",]") == -1 // avoid bug 334628 / bug 379525?
&& uo.indexOf("[function") == -1 // avoid bug 380379?
&& uo.indexOf("[(function") == -1 // avoid bug 380379?
&& uo.indexOf("new Error") == -1 // ignore bug 380578
&& !uowlb.match(/<.*\/.*>.*<.*\/.*>/) // ignore bug 334628
&& !(uo == "{}" && !jsshell) // ignore bug 380959
)
{
// count=946; tryItOut("return (({ set x x (x) { yield /x/g } , x setter: ({}).hasOwnProperty }));");
uo = uo.replace(/\[native code\]/g, "");
try {
euo = eval(uo); // if this throws, something's wrong with uneval, probably
} catch(e) {
dumpln("The string returned by uneval failed to eval!");
printAndStop(e);
return;
}
ueuo = uneval(euo);
if (ueuo != uo) {
printAndStop("Mismatch with uneval/eval on the function's return value! " + "\n" + uo + "\n" + ueuo);
}
} else {
dumpln("Skipping re-eval test");
}
}
function tryHalves(code)
{
// See if there are any especially horrible bugs that appear when the parser has to start/stop in the middle of something. this is kinda evil.
// Stray "}"s are likely in secondHalf, so use new Function rather than eval. "}" can't escape from new Function :)
var f, firstHalf, secondHalf;
try {
firstHalf = code.substr(0, code.length / 2);
if (verbose)
dumpln("First half: " + firstHalf);
f = new Function(firstHalf);
"" + f;
}
catch(e) {
if (verbose)
dumpln("First half compilation error: " + e);
}
try {
secondHalf = code.substr(code.length / 2, code.length);
if (verbose)
dumpln("Second half: " + secondHalf);
f = new Function(secondHalf);
"" + f;
}
catch(e) {
if (verbose)
dumpln("Second half compilation error: " + e);
}
}
function errorToString(e)
{
try {
return ("" + e);
} catch (e2) {
return "Can't toString the error!!";
}
}
// Function round-trip with implicit toString
function checkRoundTripToString(f, code, checkRecompiling, checkForMismatch)
{
var uf, g;
try {
uf = "" + f;
} catch(e) { reportRoundTripIssue("Round-trip with implicit toString: can't toString", code, null, null, errorToString(e)); return; }
checkForCookies(uf);
if (checkRecompiling) {
try {
g = eval("(" + uf + ")");
if (checkForMismatch && (""+g) != (""+f) ) {
reportRoundTripIssue("Round-trip with implicit toString", code, f, g, "mismatch");
}
} catch(e) {
reportRoundTripIssue("Round-trip with implicit toString: error", code, f, g, errorToString(e));
}
}
}
// Function round-trip with uneval
function checkRoundTripUneval(f, code, checkRecompiling, checkForMismatch)
{
var g, uf, ug;
try {
uf = uneval(f);
} catch(e) { reportRoundTripIssue("Round-trip with uneval: can't uneval", code, null, null, errorToString(e)); return; }
checkForCookies(uf)
if (checkRecompiling) {
try {
g = eval("(" + uf + ")");
ug = uneval(g);
if (checkForMismatch && ug != uf) {
reportRoundTripIssue("Round-trip with uneval: mismatch", code, uf, ug, "mismatch");
}
} catch(e) { reportRoundTripIssue("Round-trip with uneval: error", code, uf, ug, errorToString(e)); }
}
}
function checkForCookies(code)
{
// http://lxr.mozilla.org/seamonkey/source/js/src/jsopcode.c#1613
// These are things that shouldn't appear in decompilations.
if (code.indexOf("/*EXCEPTION") != -1
|| code.indexOf("/*RETSUB") != -1
|| code.indexOf("/*FORELEM") != -1
|| code.indexOf("/*WITH") != -1)
printAndStop(code)
}
function reportRoundTripIssue(issue, code, fs, gs, e)
{
if (e.indexOf("missing variable name") != -1) {
dumpln("Bug 355667 sure is annoying!");
return;
}
var message = issue + "\n\n" +
"Code: " + uneval(code) + "\n\n" +
"fs: " + fs + "\n\n" +
"gs: " + gs + "\n\n" +
"error: " + e;
printAndStop(message);
}
function extractCode(f)
{
// throw away the first and last lines of the function's string representation
// (this happens to work on spidermonkey trunk, dunno about anywhere else)
var uf = "" + f;
var lines = uf.split("\n");
var innerLines = lines.slice(1, -1);
return innerLines.join("\n");
}
function compiles(code)
{
try {
new Function(code);
return true;
} catch(e) {
return false;
}
}
// Returns an array of strings of length (code.length-2),
// each having one pair of matching parens removed.
// Assumes all parens in code are significant. This assumption fails
// for strings or regexps, but whatever.
function deParen(code)
{
// Get a list of locations of parens.
var parenPairs = []; // array of { left : int, right : int } (indices into code string)
var unmatched = []; // stack of indices into parenPairs
var i, c;
for (i = 0; i < code.length; ++i) {
c = code.charCodeAt(i);
if (c == 40) {
// left paren
unmatched.push(parenPairs.length);
parenPairs.push({ left: i });
} else if (c == 41) {
// right paren
if (unmatched.length == 0)
return []; // eep! unmatched rparen!
parenPairs[unmatched.pop()].right = i;
}
}
if (unmatched.length > 0)
return []; // eep! unmatched lparen!
var rs = [];
// Don't add spaces in place of the parens, because we don't
// want to detect things like (5).x as being unnecessary use
// of parens.
for (i = 0; i < parenPairs.length; ++i) {
var left = parenPairs[i].left, right = parenPairs[i].right;
rs.push(
code.substr(0, left)
+ code.substr(left + 1, right - (left + 1))
+ code.substr(right + 1)
);
}
return rs;
}
// print(uneval(deParen("for (i = 0; (false); ++i) { x(); }")));
// print(uneval(deParen("[]")));
function checkForExtraParens(f, code)
{
var code = code.replace(/\n/g, " ").replace(/\r/g, " "); // regexps can't match across lines
var uf = "" + f;
// numbers get more parens than they need
if (uf.match(/\(\d/)) return;
if (uf.indexOf("(<") != -1) return; // bug 381204
if (uf.indexOf(".(") != -1) return; // bug 381207
if (uf.indexOf("else if") != -1) return; // bug 381742
if (code.indexOf("new") != -1) return; // "new" is weird. what can i say?
if (code.indexOf("let") != -1) return; // reasonable to overparenthesize "let" (see expclo#c33)
if (code.match(/for.*in.*=/)) return; // bug 381213
if (code.match(/\:.*function/)) return; // why?
if (uf.indexOf("(function") != -1) return; // expression closures over-parenthesize
if (code.match(/for.*yield/)) return; // why?
if (uf.indexOf("= (yield") != -1) return;
if (uf.indexOf(":(yield") != -1) return;
if (uf.indexOf(": (yield") != -1) return;
if (uf.indexOf(", (yield") != -1) return;
if (uf.indexOf("[(yield") != -1) return;
if (uf.indexOf("yield") != -1) return; // i give up on yield
// Sanity check
var euf = eval("(" + uf + ")");
var ueuf = "" + euf;
if (ueuf != uf)
printAndStop("Shouldn't the earlier round-trip test have caught this?");
var dps = deParen(uf);
// skip the first, which is the function's formal params.
for (i = 1; i < dps.length; ++i) {
var uf2 = dps[i];
try {
var euf2 = eval("(" + uf2 + ")");
} catch(e) { /* print("The latter did not compile. That's fine."); */ continue; }
var ueuf2 = "" + euf2
if (ueuf2 == ueuf) {
print(uf);
print(" vs ");
print(uf2);
print("Both decompile as:");
print(ueuf);
printAndStop("Unexpected match!!! Extra parens!?");
}
}
}
/**************
* RANDOMNESS *
**************/
function rnd(n)
{
return Math.floor(Math.random() * n);
}
function rndElt(a)
{
return a[rnd(a.length)];
}
/**************************
* TOKEN-LEVEL GENERATION *
**************************/
// Each input to |cat| should be a token or so, OR a bigger logical piece (such as a call to makeExpr). Smaller than a token is ok too ;)
// When "torture" is true, it may do any of the following:
// * skip a token
// * skip all the tokens to the left
// * skip all the tokens to the right
// * insert unterminated comments
// * insert line breaks
// * insert entire expressions
// * insert any token
// Even when not in "torture" mode, it may sneak in extra line breaks.
// Why did I decide to toString at every step, instead of making larger and larger arrays (or more and more deeply nested arrays?). no particular reason...
function cat(toks)
{
if (rnd(170) == 0)
return totallyRandom(2);
var torture = (rnd(170) == 57);
/* (if (torture)
dumpln("Torture!!!");
*/
var s = maybeLineBreak();
for (var i = 0; i < toks.length; ++i) {
// Catch bugs in the fuzzer. An easy mistake is
// return /*foo*/ + ...
// instead of
// return "/*foo*/" + ...
// Unary plus in the first one coerces the string that follows to number!
if(typeof(toks[i]) != "string") {
dumpln("Strange item in the array passed to Tmean: toks[" + i + "] == " + toks[i]);
dumpln(Tmean.caller)
dumpln(Tmean.caller.caller)
printAndStop('yarr')
}
if (!(torture && rnd(12) == 0))
s += toks[i];
s += maybeLineBreak();
if (torture) switch(rnd(120)) {
case 0: case 1: case 2: case 3: case 4: s += maybeSpace() + totallyRandom(2) + maybeSpace(); break;
case 5: s = "(" + s + ")"; break;
case 6: s = ""; break;
case 7: return s;
case 8: s += UNTERMINATED_COMMENT; break;
case 9: s += UNTERMINATED_STRING_LITERAL; break;
case 10:
if (rnd(2))
s += "(";
s += UNTERMINATED_REGEXP_LITERAL;
break;
default:
}
}
return s;
}
// For reference and debugging.
/*