summaryrefslogtreecommitdiffstats
path: root/webkit/port/bindings/v8/v8_proxy.cpp
blob: d9152ed02353a3368c14eea8f0ddb6e7f1b4e5d1 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
// Copyright (c) 2008, Google Inc.
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// 
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "config.h"

#include <v8.h>

#include "v8_proxy.h"
#include "dom_wrapper_map.h"
#include "v8_index.h"
#include "v8_events.h"
#include "v8_binding.h"
#include "v8_custom.h"
#include "v8_collection.h"
#include "v8_nodefilter.h"
#include "V8Bridge.h"

#include "RefCounted.h"  // for Peerable

#include "DOMCoreException.h"
#include "EventException.h"
#include "ExceptionCode.h"
#include "Frame.h"
#include "HTMLNames.h"
#include "HTMLDocument.h"
#include "HTMLElement.h"
#include "HTMLImageElement.h"
#include "HTMLSelectElement.h"
#include "HTMLOptionsCollection.h"
#include "Page.h"
#include "DOMWindow.h"
#include "Navigator.h"  // for MimeTypeArray
#include "V8DOMWindow.h"
#include "V8HTMLElement.h"
#include "Entity.h"
#include "MediaList.h"
#include "NodeList.h"
#include "Notation.h"
#include "Text.h"
#include "ProcessingInstruction.h"
#include "CharacterData.h"
#include "DocumentType.h"
#include "DocumentFragment.h"
#include "EventListener.h"
#include "EventTargetNode.h"
#include "EventTarget.h"
#include "Event.h"
#include "HTMLInputElement.h"
#include "XMLHttpRequest.h"
#include "StyleSheet.h"
#include "StyleSheetList.h"
#include "CSSRule.h"
#include "CSSRuleList.h"
#include "CSSValueList.h"
#include "FrameLoader.h"
#include "FrameTree.h"
#include "RangeException.h"
#include "NodeFilter.h"
#include "SecurityOrigin.h"
#include "XMLHttpRequestException.h"
#include "XPathException.h"

#if ENABLE(SVG)
#include "SVGElement.h"
#include "SVGElementInstance.h"
#include "SVGException.h"
#endif

#if ENABLE(XPATH)
#include "XPathEvaluator.h"
#endif

#include "base/stats_table.h"
#include "base/trace_event.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webkit_glue.h"

namespace WebCore {

// DOM binding algorithm:
//
// There are two kinds of DOM objects:
// 1. DOM tree nodes, such as Document, HTMLElement, ...
//    there classes implements TreeShared<T> interface;
// 2. Non-node DOM objects, such as CSSRule, Location, etc.
//    these classes implements RefCounted<T> interface.
//
// A DOM object may have a JS wrapper object. If a tree node
// is alive, its JS wrapper must be kept alive even it is not
// reachable from JS roots.
// However, JS wrappers of non-node objects can go away if
// not reachable from other JS objects. It works like a cache.
//
// DOM objects are ref-counted, and JS objects are traced from
// a set of root objects. They can create a cycle. To break
// cycles, we do following:
//   Peer from DOM objects to JS wrappers are always weak,
// so JS wrappers of non-node object cannot create a cycle.
//   Before starting a global GC, we create a virtual connection
// between nodes in the same tree in the JS heap. If the wrapper
// of one node in a tree is alive, wrappers of all nodes in
// the same tree are considered alive. This is done by creating
// object groups in GC prologue callbacks. The mark-compact
// collector will remove these groups after each GC.


#ifndef NDEBUG
// Keeps track of global handles created (not JS wrappers
// of DOM objects). Often these global handles are source
// of leaks.
//
// If you want to let a C++ object hold a persistent handle
// to a JS object, you should register the handle here to
// keep track of leaks.
//
// When creating a persistent handle, call:
//
// #ifndef NDEBUG
//    V8Proxy::RegisterGlobalHandle(type, host, handle);
// #endif
//
// When releasing the handle, call:
//
// #ifndef NDEBUG
//    V8Proxy::UnregisterGlobalHandle(type, host, handle);
// #endif
//
typedef HashMap<v8::Value*, GlobalHandleInfo*> GlobalHandleMap;

static GlobalHandleMap& global_handle_map() {
  static GlobalHandleMap static_global_handle_map;
  return static_global_handle_map;
}


// The function is the place to set the break point to inspect
// live global handles. Leaks are often come from leaked global handles.
static void EnumerateGlobalHandles() {
  for (GlobalHandleMap::iterator it = global_handle_map().begin(),
    end = global_handle_map().end(); it != end; ++it) {
    GlobalHandleInfo* info = it->second;
    v8::Value* handle = it->first;
  }
}


void V8Proxy::RegisterGlobalHandle(GlobalHandleType type, void* host,
                                   v8::Persistent<v8::Value> handle) {
  ASSERT(!global_handle_map().contains(*handle));
  global_handle_map().set(*handle, new GlobalHandleInfo(host, type));
}


void V8Proxy::UnregisterGlobalHandle(void* host,
                                     v8::Persistent<v8::Value> handle) {
  ASSERT(global_handle_map().contains(*handle));
  GlobalHandleInfo* info = global_handle_map().take(*handle);
  ASSERT(info->host_ == host);
  delete info;
}
#endif  // ifndef NDEBUG

void BatchConfigureAttributes(v8::Handle<v8::ObjectTemplate> inst,
                              v8::Handle<v8::ObjectTemplate> proto,
                              const BatchedAttribute* attrs,
                              size_t num_attrs) {
  for (size_t i = 0; i < num_attrs; ++i) {
    const BatchedAttribute* a = &attrs[i];
    (a->on_proto ? proto : inst)->SetAccessor(
        v8::String::New(a->name),
        a->getter,
        a->setter,
        a->data == V8ClassIndex::INVALID_CLASS_INDEX
            ? v8::Handle<v8::Value>()
            : v8::Integer::New(V8ClassIndex::ToInt(a->data)),
        a->settings,
        a->attribute);
  }
}

void BatchConfigureConstants(v8::Handle<v8::FunctionTemplate> desc,
                             v8::Handle<v8::ObjectTemplate> proto,
                             const BatchedConstant* consts,
                             size_t num_consts) {
  for (size_t i = 0; i < num_consts; ++i) {
    const BatchedConstant* c = &consts[i];
    desc->Set(v8::String::New(c->name),
              v8::Integer::New(c->value),
              v8::ReadOnly);
    proto->Set(v8::String::New(c->name),
               v8::Integer::New(c->value),
               v8::ReadOnly);
  }
}


typedef HashMap<Node*, v8::Object*> NodeMap;
typedef HashMap<Peerable*, v8::Object*> PeerableMap;

// Type T must implement Peerable interface.
template<class T>
class DOMPeerableWrapperMap : public DOMWrapperMap<T> {
 public:
  explicit DOMPeerableWrapperMap(v8::WeakReferenceCallback callback) :
       DOMWrapperMap<T>(callback) { }

  // Get the JS wrapper object of an object.
  v8::Persistent<v8::Object> get(T* obj) {
    v8::Object* peer = static_cast<v8::Object*>(obj->peer());
    ASSERT(peer == this->map_.get(obj));
    return peer ? v8::Persistent<v8::Object>(peer)
      : v8::Persistent<v8::Object>();
  }

  void set(T* obj, v8::Persistent<v8::Object> peer_handle) {
    ASSERT(obj->peer() == 0);
    obj->setPeer(*peer_handle);
    DOMWrapperMap<T>::set(obj, peer_handle);
  }

  void forget(T* obj) {
    v8::Object* peer = static_cast<v8::Object*>(obj->peer());
    ASSERT(peer == this->map_.get(obj));
    if (peer)
      obj->setPeer(0);
    DOMWrapperMap<T>::forget(obj);
  }
};


static void WeakPeerableCallback(v8::Persistent<v8::Object> obj, void* para);
static void WeakNodeCallback(v8::Persistent<v8::Object> obj, void* para);
// A map from DOM node to its JS wrapper.
static DOMWrapperMap<Node>& dom_node_map() {
  static DOMPeerableWrapperMap<Node> static_dom_node_map(&WeakNodeCallback);
  return static_dom_node_map;
}


// A map from a non-DOM node (peerable) to its JS wrapper.
static DOMWrapperMap<Peerable>& dom_object_map() {
  static DOMPeerableWrapperMap<Peerable>
    static_dom_object_map(&WeakPeerableCallback);
  return static_dom_object_map;
}

#if ENABLE(SVG)
static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Object> obj,
                                           void* param);

// A map for SVGElementInstances, which are not peerable
static DOMWrapperMap<SVGElementInstance>& dom_svg_element_instance_map() {
  static DOMWrapperMap<SVGElementInstance>
      static_dom_svg_element_instance_map(&WeakSVGElementInstanceCallback);
  return static_dom_svg_element_instance_map;
}

static void WeakSVGElementInstanceCallback(v8::Persistent<v8::Object> obj,
                                           void* param) {
  SVGElementInstance* instance = static_cast<SVGElementInstance*>(param);
  ASSERT(dom_svg_element_instance_map().contains(instance));

  instance->deref();
  dom_svg_element_instance_map().forget(instance);
}

v8::Handle<v8::Object> V8Proxy::SVGElementInstanceToV8Object(
    SVGElementInstance* instance) {
  if (!instance) return v8::Handle<v8::Object>();

  v8::Handle<v8::Object> existing_instance =
      dom_svg_element_instance_map().get(instance);
  if (!existing_instance.IsEmpty()) {
    return existing_instance;
  }

  instance->ref();

  // Instantiate the V8 object and remember it
  v8::Handle<v8::Object> result =
      InstantiateV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
  if (!result.IsEmpty()) {
    // Only update the DOM SVG element map if the result is non-empty.
    dom_svg_element_instance_map().set(instance,
      v8::Persistent<v8::Object>::New(result));
  }
  return result;
}

// SVG non-node elements may have a reference to a context node which
// should be notified when the element is changed
static void WeakSVGObjectWithContext(v8::Persistent<v8::Object> obj,
                                     void* param);

// Map of SVG objects with contexts to V8 objects
static DOMWrapperMap<Peerable>& dom_svg_object_with_context_map() {
  static DOMPeerableWrapperMap<Peerable>
    static_dom_svg_object_with_context_map(&WeakSVGObjectWithContext);
  return static_dom_svg_object_with_context_map;
}

// Map of SVG objects with contexts to their contexts
static HashMap<void*, SVGElement*>& svg_object_to_context_map() {
  static HashMap<void*, SVGElement*> static_svg_object_to_context_map;
  return static_svg_object_to_context_map;
}

v8::Handle<v8::Object> V8Proxy::SVGObjectWithContextToV8Object(
  Peerable* object, V8ClassIndex::V8WrapperType type) {
  if (!object) return v8::Handle<v8::Object>();

  // Special case: SVGPathSegs need to be downcast to their real type
  if (type == V8ClassIndex::SVGPATHSEG) {
    type = V8Custom::DowncastSVGPathSeg(object);
  }

  v8::Persistent<v8::Object> result =
    dom_svg_object_with_context_map().get(object);
  if (result.IsEmpty()) {
    v8::Local<v8::Object> v8obj = InstantiateV8Object(type, object);
    if (!v8obj.IsEmpty()) {
      result = v8::Persistent<v8::Object>::New(v8obj);
      dom_svg_object_with_context_map().set(object, result);
    }
  }

  return result;
}

static void WeakSVGObjectWithContext(v8::Persistent<v8::Object> obj,
                                     void* param) {
  Peerable* dom_obj = static_cast<Peerable*>(param);
  ASSERT(dom_svg_object_with_context_map().contains(dom_obj));

  // Release the reference to the context if it exists
  if (svg_object_to_context_map().contains(dom_obj)) {
    svg_object_to_context_map().get(dom_obj)->deref();
    svg_object_to_context_map().remove(dom_obj);
  }

  // forget function removes object from the map,
  // disposes the wrapper and clears the peer.
  dom_svg_object_with_context_map().forget(dom_obj);
}

void V8Proxy::SetSVGContext(void* obj, SVGElement* context) {
  SVGElement* old_context = svg_object_to_context_map().get(obj);

  if (old_context == context) {
    return;
  }

  if (old_context) {
    old_context->deref();
  }

  if (context) {
    context->ref();
  }

  svg_object_to_context_map().set(obj, context);
}

SVGElement* V8Proxy::GetSVGContext(void* obj) {
  return svg_object_to_context_map().get(obj);
}

#endif


// Called when obj is near death (not reachable from JS roots)
// It is time to remove the entry from the table and dispose
// the handle.
static void WeakPeerableCallback(v8::Persistent<v8::Object> obj, void* para) {
  Peerable* dom_obj = static_cast<Peerable*>(para);
  ASSERT(dom_object_map().contains(dom_obj));

  // forget function removes object from the map,
  // disposes the wrapper and clears the peer.
  dom_object_map().forget(dom_obj);
}


static void WeakNodeCallback(v8::Persistent<v8::Object> obj, void* param) {
  Node* node = static_cast<Node*>(param);
  ASSERT(dom_node_map().contains(node));

  dom_node_map().forget(node);
}


// Create object groups for DOM tree nodes.
static void GCPrologue() {
#ifndef NDEBUG
  // Check that all references in the map are weak.
  PeerableMap peer_map = dom_object_map().impl();
  for (PeerableMap::iterator it = peer_map.begin(), end = peer_map.end();
    it != end; ++it) {
    Peerable* obj = it->first;
    ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
  }
#endif

  // Create object groups.
  NodeMap node_map = dom_node_map().impl();
  for (NodeMap::iterator it = node_map.begin(), end = node_map.end();
    it != end; ++it) {
    Node* node = it->first;

    // If the node is in document, put it in the ownerDocument's
    // object group.
    //
    // If an image element was created by JavaScript "new Image",
    // it is not in a document. However, if the load event has not
    // been fired (still onloading), it is treated as in the document.
    //
    if (node->inDocument() ||
        (node->hasTagName(HTMLNames::imgTag) &&
         !static_cast<HTMLImageElement*>(node)->haveFiredLoadEvent()) ) {
      Document* doc = node->document();
      v8::Persistent<v8::Object> wrapper = dom_node_map().get(node);
      if (!wrapper.IsEmpty()) {
        v8::V8::AddObjectToGroup(doc, wrapper);
      }
    }
  }
}


static void GCEpilogue() {
#ifndef NDEBUG
  // Check all survivals are weak.
  PeerableMap peer_map = dom_object_map().impl();
  for (PeerableMap::iterator it = peer_map.begin(), end = peer_map.end();
    it != end; ++it) {
    Peerable* obj = it->first;
    ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
  }

  NodeMap node_map = dom_node_map().impl();
  for (NodeMap::iterator it = node_map.begin(), end = node_map.end();
    it != end; ++it) {
    Node* node = it->first;
    ASSERT(v8::Persistent<v8::Object>(it->second).IsWeak());
  }

  EnumerateGlobalHandles();
#endif
}


// A map from a peerable node to its JS wrapper, the wrapper
// is kept as a strong reference to survive GCs.
static PeerableMap& gc_protected_map() {
  static PeerableMap static_gc_protected_map;
  return static_gc_protected_map;
}


// static
void V8Proxy::GCProtect(Peerable* dom_object) {
  if (!dom_object) return;
  if (gc_protected_map().contains(dom_object)) return;
  if (!dom_object->peer()) return;

  // Create a new (strong) persistent handle for the peer.
  v8::Persistent<v8::Object>
      wrapper(static_cast<v8::Object*>(dom_object->peer()));

  gc_protected_map().set(dom_object, *v8::Persistent<v8::Object>::New(wrapper));
}


// static
void V8Proxy::GCUnprotect(Peerable* dom_object) {
  if (!dom_object) return;
  if (!gc_protected_map().contains(dom_object)) return;

  // Dispose the strong reference.
  v8::Persistent<v8::Object> wrapper(gc_protected_map().take(dom_object));
  wrapper.Dispose();
}


typedef HashMap<int, v8::FunctionTemplate*> FunctionTemplateMap;

bool AllowAllocation::m_current = false;


// JavaScriptConsoleMessages encapsulate everything needed to
// log messages originating from JavaScript to the Chrome console.
class JavaScriptConsoleMessage {
 public:
  JavaScriptConsoleMessage(const String& str,
                           const String& sourceID,
                           unsigned lineNumber)
    : m_string(str)
    , m_sourceID(sourceID)
    , m_lineNumber(lineNumber) { }

  void AddToPage(Page* page) const;

 private:
  const String m_string;
  const String m_sourceID;
  const unsigned m_lineNumber;
};


void JavaScriptConsoleMessage::AddToPage(Page* page) const {
  ASSERT(page);
  Chrome* chrome = page->chrome();
  // Only messages with ErrorMessageLevel are logged when
  // calling Chrome::addMessageToConsole().
  chrome->addMessageToConsole(JSMessageSource, ErrorMessageLevel,
                              m_string, m_lineNumber, m_sourceID);
}


// The ConsoleMessageManager handles all console messages that stem
// from JavaScript. It keeps a list of messages that have been delayed but
// it makes sure to add all messages to the console in the right order.
class ConsoleMessageManager {
 public:
  // Add a message to the console. May end up calling JavaScript code
  // indirectly through the inspector so only call this function when
  // it is safe to do allocations.
  static void AddMessage(Page* page, const JavaScriptConsoleMessage& message);

  // Add a message to the console but delay the reporting until it
  // is safe to do so: Either when we leave JavaScript execution or
  // when adding other console messages. The primary purpose of this
  // method is to avoid calling into V8 to handle console messages
  // when the VM is in a state that does not support GCs or allocations.
  // Delayed messages are always reported in the page corresponding
  // to the active context.
  static void AddDelayedMessage(const JavaScriptConsoleMessage& message);

  // Process any delayed messages. May end up calling JavaScript code
  // indirectly through the inspector so only call this function when
  // it is safe to do allocations.
  static void ProcessDelayedMessages();

 private:
  // All delayed messages are stored in this vector. If the vector
  // is NULL, there are no delayed messages.
  static Vector<JavaScriptConsoleMessage>* m_delayed;
};


Vector<JavaScriptConsoleMessage>* ConsoleMessageManager::m_delayed = NULL;


void ConsoleMessageManager::AddMessage(
    Page* page,
    const JavaScriptConsoleMessage& message) {
  // Process any delayed messages to make sure that messages
  // appear in the right order in the console.
  ProcessDelayedMessages();
  message.AddToPage(page);
}


void ConsoleMessageManager::AddDelayedMessage(
    const JavaScriptConsoleMessage& message) {
  if (!m_delayed) {
    // Allocate a vector for the delayed messages. Will be
    // deallocated when the delayed messages are processed
    // in ProcessDelayedMessages().
    m_delayed = new Vector<JavaScriptConsoleMessage>();
  }
  m_delayed->append(message);
}


void ConsoleMessageManager::ProcessDelayedMessages() {
  // If we have a delayed vector it cannot be empty.
  if (!m_delayed) return;
  ASSERT(!m_delayed->isEmpty());

  // Add the delayed messages to the page of the active
  // context. If that for some bizarre reason does not
  // exist, we clear the list of delayed messages to avoid
  // posting messages. We still deallocate the vector.
  Frame* frame = V8Proxy::retrieveActiveFrame();
  Page* page = NULL;
  if (frame) page = frame->page();
  if (!page) m_delayed->clear();

  // Iterate through all the delayed messages and add them
  // to the console.
  const int size = m_delayed->size();
  for (int i = 0; i < size; i++) {
    m_delayed->at(i).AddToPage(page);
  }

  // Deallocate the delayed vector.
  delete m_delayed;
  m_delayed = NULL;
}


// Convenience class for ensuring that delayed messages in the
// ConsoleMessageManager are processed quickly.
class ConsoleMessageScope {
 public:
  ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
  ~ConsoleMessageScope() { ConsoleMessageManager::ProcessDelayedMessages(); }
};


void log_info(Frame* frame, const String& msg, const String& url) {
  Page* page = frame->page();
  if (!page) return;
  JavaScriptConsoleMessage message(msg, url, 0);
  ConsoleMessageManager::AddMessage(page, message);
}


static void HandleConsoleMessage(v8::Handle<v8::Message> message,
                                 v8::Handle<v8::Value> data) {
  // Use the frame where JavaScript is called from.
  Frame* frame = V8Proxy::retrieveActiveFrame();
  if (!frame) return;

  Page* page = frame->page();
  if (!page) return;

  v8::Handle<v8::String> errorMessageString = message->Get();
  ASSERT(!errorMessageString.IsEmpty());
  String errorMessage = ToWebCoreString(errorMessageString);

  v8::Handle<v8::String> resourceNameString = message->GetScriptResourceName();
  String resourceName = (resourceNameString.IsEmpty())
    ? frame->document()->url()
    : ToWebCoreString(resourceNameString);
  JavaScriptConsoleMessage consoleMessage(errorMessage,
                                          resourceName,
                                          message->GetLineNumber());
  ConsoleMessageManager::AddMessage(page, consoleMessage);
}


enum DelayReporting {
  REPORT_LATER,
  REPORT_NOW
};


static void ReportUnsafeAccessTo(Frame* target, DelayReporting delay) {
  ASSERT(target);
  Document* targetDocument = target->document();
  if (!targetDocument) return;

  Frame* source = V8Proxy::retrieveActiveFrame();
  Document* sourceDocument = source->document();
  ASSERT(sourceDocument);

  // FIXME: This error message should contain more specifics of why the same
  // origin check has failed.
  String str = String::format("Unsafe JavaScript attempt to access frame "
      "with URL %s from frame with URL %s. Domains, protocols and ports must "
      "match.\n",
      targetDocument->url().utf8().data(),
      sourceDocument->url().utf8().data());

  // Build a console message with fake source ID and line number.
  const String kSourceID = "";
  const int kLineNumber = 1;
  JavaScriptConsoleMessage message(str, kSourceID, kLineNumber);

  if (delay == REPORT_NOW) {
    // NOTE(tc): Apple prints the message in the target page, but it seems like
    // it should be in the source page. Even for delayed messages, we put it in
    // the source page; see ConsoleMessageManager::ProcessDelayedMessages().
    ConsoleMessageManager::AddMessage(source->page(), message);

  } else {
    ASSERT(delay == REPORT_LATER);
    // We cannot safely report the message eagerly, because this may cause
    // allocations and GCs internally in V8 and we cannot handle that at this
    // point. Therefore we delay the reporting.
    ConsoleMessageManager::AddDelayedMessage(message);
  }
}


static void ReportUnsafeJavaScriptAccess(v8::Local<v8::Object> host,
                                         v8::AccessType type,
                                         v8::Local<v8::Value> data) {
  // Do not report error if the access type is HAS.
  if (type == v8::ACCESS_HAS) return;

  Frame* target = V8Custom::GetTargetFrame(host, data);
  if (target)
    ReportUnsafeAccessTo(target, REPORT_LATER);
}


static void ReportFatalErrorInV8(const char* location, const char* message) {
  // V8 is shutdown, we cannot use V8 api.
  // The only thing we can do is to disable JavaScript.
  // TODO: clean up V8Proxy and disable JavaScript.
  printf("V8 error: %s (%s)\n", message, location);
}


static void HandleFatalErrorInV8() {
  // TODO: We temporarily deal with V8 internal error situations
  // such as out-of-memory by crashing the renderer.
  CRASH();
}


V8Proxy::~V8Proxy() {
  clear();
  DestroyGlobal();
}


void V8Proxy::DestroyGlobal() {
  if (!m_global.IsEmpty()) {
#ifndef NDEBUG
    UnregisterGlobalHandle(this, m_global);
#endif
    m_global.Dispose();
    m_global.Clear();
  }
}


void V8Proxy::SetJSWrapperForDOMObject(Peerable* obj,
                                       v8::Persistent<v8::Object> wrapper) {
  dom_object_map().set(obj, wrapper);
}


void V8Proxy::SetJSWrapperForDOMNode(Node* node,
                                     v8::Persistent<v8::Object> wrapper) {
  dom_node_map().set(node, wrapper);
}


EventListener* V8Proxy::createHTMLEventHandler(const String& functionName,
                                               const String& code, Node* node) {
  return new V8LazyEventListener(m_frame, code, functionName);
}

#if ENABLE(SVG)
EventListener* V8Proxy::createSVGEventHandler(const String& functionName,
                                              const String& code, Node* node) {
  return new V8LazyEventListener(m_frame, code, functionName);
}
#endif


// Event listeners

static V8EventListener* FindEventListenerInList(V8EventListenerList& list,
                                                v8::Local<v8::Value> listener,
                                                bool html) {
  ASSERT(v8::Context::InContext());

  if (!listener->IsObject()) return 0;

  V8EventListenerList::iterator p = list.begin();
  while (p != list.end()) {
    V8EventListener* el = *p;
    v8::Local<v8::Object> wrapper = el->GetListenerObject();
    ASSERT(!wrapper.IsEmpty());
    // Since the listener is an object, it is safe to compare for 
    // strict equality (in the JS sense) by doing a simple equality
    // check using the == operator on the handles. This is much,
    // much faster than calling StrictEquals through the API in 
    // the negative case.
    if (el->isHTMLEventListener() == html && listener == wrapper) {
      return el;
    }
    ++p;
  }
  return 0;
}


// Find an existing wrapper for a JS event listener in the map.
V8EventListener* V8Proxy::FindV8EventListener(v8::Local<v8::Value> listener,
                                              bool html) {
  return FindEventListenerInList(m_event_listeners, listener, html);
}


V8EventListener* V8Proxy::FindOrCreateV8EventListener(v8::Local<v8::Value> obj,
                                                      bool html) {
  ASSERT(v8::Context::InContext());

  if (!obj->IsObject()) return 0;

  V8EventListener* wrapper =
      FindEventListenerInList(m_event_listeners, obj, html);
  if (wrapper) return wrapper;

  // Create a new one, and add to cache.
  V8EventListener* new_listener =
    new V8EventListener(m_frame, v8::Local<v8::Object>::Cast(obj), html);
  m_event_listeners.push_back(new_listener);

  return new_listener;
}


// XMLHttpRequest(XHR) event listeners are different from listeners
// on DOM nodes. A XHR event listener wrapper only hold a weak reference
// to the JS function. A strong reference can create a cycle.
//
// The lifetime of a XHR object is bounded by the life time of its JS_XHR
// object. So we can create a hidden reference from JS_XHR to JS function.
//
//                         (peer)
//              XHR      <----------  JS_XHR
//               |             (hidden) :  ^
//               V                      V  : (may reachable by closure)
//           V8_listener  --------> JS_function
//                         (weak)  <-- may create a cycle if it is strong
//
// The persistent reference is made weak in the constructor
// of V8XHREventListener.

V8EventListener* V8Proxy::FindXHREventListener(v8::Local<v8::Value> listener,
                                               bool html) {
  return FindEventListenerInList(m_xhr_listeners, listener, html);
}


V8EventListener*
V8Proxy::FindOrCreateXHREventListener(v8::Local<v8::Value> obj,
                                      bool html) {
  ASSERT(v8::Context::InContext());

  if (!obj->IsObject()) return 0;

  V8EventListener* wrapper =
      FindEventListenerInList(m_xhr_listeners, obj, html);
  if (wrapper) return wrapper;

  // Create a new one, and add to cache.
  V8EventListener* new_listener =
    new V8XHREventListener(m_frame, v8::Local<v8::Object>::Cast(obj), html);
  m_xhr_listeners.push_back(new_listener);

  return new_listener;
}


static void RemoveEventListenerFromList(V8EventListenerList& list,
                                        V8EventListener* listener) {
  V8EventListenerList::iterator p = list.begin();
  while (p != list.end()) {
    if (*p == listener) {
      list.erase(p);
      return;
    }
    ++p;
  }
}


void V8Proxy::RemoveV8EventListener(V8EventListener* listener) {
  RemoveEventListenerFromList(m_event_listeners, listener);
}


void V8Proxy::RemoveXHREventListener(V8XHREventListener* listener) {
  RemoveEventListenerFromList(m_xhr_listeners, listener);
}


static void DisconnectEventListenersInList(V8EventListenerList& list) {
  V8EventListenerList::iterator p = list.begin();
  while (p != list.end()) {
    (*p)->disconnectFrame();
    ++p;
  }
  list.clear();
}


void V8Proxy::DisconnectEventListeners() {
  DisconnectEventListenersInList(m_event_listeners);
  DisconnectEventListenersInList(m_xhr_listeners);
}


v8::Handle<v8::Script> V8Proxy::CompileScript(v8::Handle<v8::String> code,
                                              const String& fileName,
                                              int baseLine) {
  const uint16_t* fileNameString = FromWebCoreString(fileName);
  v8::Handle<v8::String> name =
      v8::String::New(fileNameString, fileName.length());
  v8::Handle<v8::Integer> line = v8::Integer::New(baseLine);
  v8::ScriptOrigin origin(name, line);
  v8::Handle<v8::Script> script = v8::Script::Compile(code, &origin);
  return script;
}


bool V8Proxy::HandleOutOfMemory() {
  v8::Local<v8::Context> context = v8::Context::GetCurrent();

  if (!context->HasOutOfMemoryException())
    return false;

  // Warning, error, disable JS for this frame?
  Frame* frame = V8Proxy::retrieveFrame(context);

  V8Proxy* proxy = V8Proxy::retrieve(frame);
  // Clean m_context, m_document, and event handlers.
  proxy->clear();
  // Destroy the global object.
  proxy->DestroyGlobal();

  webkit_glue::NotifyJSOutOfMemory(frame);

  // Disable JS.
  Settings* settings = frame->settings();
  ASSERT(settings);
  settings->setJavaScriptEnabled(false);

  return true;
}


v8::Local<v8::Value> V8Proxy::Evaluate(const String& fileName, int baseLine,
                                       const String& str, Node* n) {
  ASSERT(v8::Context::InContext());

  // Compile the script.
  v8::Local<v8::String> code = v8ExternalString(str);
  TRACE_EVENT_BEGIN("v8.compile", n, "");
  v8::Handle<v8::Script> script = CompileScript(code, fileName, baseLine);
  TRACE_EVENT_END("v8.compile", n, "");

  // Set inlineCode to true for <a href="javascript:doSomething()">
  // and false for <script>doSomething</script>. For some reason, fileName
  // gives us this information.
  TRACE_EVENT_BEGIN("v8.run", n, "");
  v8::Local<v8::Value> result = RunScript(script, fileName.isNull());
  TRACE_EVENT_END("v8.run", n, "");
  return result;
}


v8::Local<v8::Value> V8Proxy::RunScript(v8::Handle<v8::Script> script,
                                        bool inline_code) {
  if (script.IsEmpty())
    return v8::Local<v8::Value>();

  // Compute the source string and prevent against infinite recursion.
  if (m_recursion >= 20) {
    v8::Local<v8::String> code =
        v8ExternalString("throw RangeError('Recursion too deep')");
    // TODO(kasperl): Ideally, we should be able to re-use the origin of the
    // script passed to us as the argument instead of using an empty string
    // and 0 baseLine.
    script = CompileScript(code, "", 0);
  }

  if (HandleOutOfMemory())
    ASSERT(script.IsEmpty());

  if (script.IsEmpty())
    return v8::Local<v8::Value>();

  // Save the previous value of the inlineCode flag and update the flag for
  // the duration of the script invocation.
  bool previous_inline_code = inlineCode();
  setInlineCode(inline_code);

  // Run the script and keep track of the current recursion depth.
  v8::Local<v8::Value> result;
  { ConsoleMessageScope scope;
    m_recursion++;

    // Evaluating the JavaScript could cause the frame to be deallocated,
    // so we start the keep alive timer here.
    // Frame::keepAlive method adds the ref count of the frame and sets a
    // timer to decrease the ref count. It assumes that the current JavaScript
    // execution finishs before firing the timer.
    // See issue 1218756 and 914430.
    m_frame->keepAlive();

    result = script->Run();
    m_recursion--;
  }

  if (HandleOutOfMemory())
    ASSERT(result.IsEmpty());

  // Handle V8 internal error situation (Out-of-memory).
  if (result.IsEmpty())
    return v8::Local<v8::Value>();

  // Restore inlineCode flag.
  setInlineCode(previous_inline_code);

  if (v8::V8::IsDead())
    HandleFatalErrorInV8();

  return result;
}


v8::Local<v8::Value> V8Proxy::CallFunction(v8::Handle<v8::Function> function,
                                           v8::Handle<v8::Object> receiver,
                                           int argc,
                                           v8::Handle<v8::Value> args[]) {
  // For now, we don't put any artificial limitations on the depth
  // of recursion that stems from calling functions. This is in
  // contrast to the script evaluations.
  v8::Local<v8::Value> result;
  { ConsoleMessageScope scope;

    // Evaluating the JavaScript could cause the frame to be deallocated,
    // so we start the keep alive timer here.
    // Frame::keepAlive method adds the ref count of the frame and sets a
    // timer to decrease the ref count. It assumes that the current JavaScript
    // execution finishs before firing the timer.
    // See issue 1218756 and 914430.
    m_frame->keepAlive();

    result = function->Call(receiver, argc, args);
  }

  if (v8::V8::IsDead())
    HandleFatalErrorInV8();

  return result;
}


v8::Persistent<v8::FunctionTemplate> V8Proxy::GetTemplate(
    V8ClassIndex::V8WrapperType type) {
  v8::Persistent<v8::FunctionTemplate>* cache_cell =
      V8ClassIndex::GetCache(type);
  if (!(*cache_cell).IsEmpty()) return *cache_cell;

  // not found
  FunctionTemplateFactory factory = V8ClassIndex::GetFactory(type);
  v8::Persistent<v8::FunctionTemplate> desc = factory();
  switch (type) {
    case V8ClassIndex::CSSSTYLEDECLARATION:
      // The named property handler for style declarations has a
      // setter.  Therefore, the interceptor has to be on the object
      // itself and not on the prototype object.
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(CSSStyleDeclaration),
          USE_NAMED_PROPERTY_SETTER(CSSStyleDeclaration));
      SetCollectionStringOrNullIndexedGetter<CSSStyleDeclaration>(desc);
      break;
    case V8ClassIndex::CSSRULELIST:
      SetCollectionIndexedGetter<CSSRuleList>(desc, V8ClassIndex::CSSRULE);
      break;
    case V8ClassIndex::CSSVALUELIST:
      SetCollectionIndexedGetter<CSSValueList>(desc, V8ClassIndex::CSSVALUE);
      break;
    case V8ClassIndex::UNDETECTABLEHTMLCOLLECTION:
      desc->InstanceTemplate()->MarkAsUndetectable();  // fall through
    case V8ClassIndex::HTMLCOLLECTION:
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(HTMLCollection));
      desc->InstanceTemplate()->SetCallAsFunctionHandler(
          USE_CALLBACK(HTMLCollectionCallAsFunction));
      SetCollectionIndexedGetter<HTMLCollection>(desc, V8ClassIndex::NODE);
      break;
    case V8ClassIndex::HTMLOPTIONSCOLLECTION:
      SetCollectionNamedGetter<HTMLOptionsCollection>(desc, V8ClassIndex::NODE);
      desc->InstanceTemplate()->SetIndexedPropertyHandler(
          USE_INDEXED_PROPERTY_GETTER(HTMLOptionsCollection),
          USE_INDEXED_PROPERTY_SETTER(HTMLOptionsCollection));
      desc->InstanceTemplate()->SetCallAsFunctionHandler(
          USE_CALLBACK(HTMLCollectionCallAsFunction));
      break;
    case V8ClassIndex::HTMLSELECTELEMENT:
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          CollectionNamedPropertyGetter<HTMLSelectElement>,
          0,
          0,
          0,
          0,
          v8::External::New(reinterpret_cast<void*>(V8ClassIndex::NODE)));
      desc->InstanceTemplate()->SetIndexedPropertyHandler(
          CollectionIndexedPropertyGetter<HTMLSelectElement>,
          USE_INDEXED_PROPERTY_SETTER(HTMLSelectElementCollection),
          0,
          0,
          CollectionIndexedPropertyEnumerator<HTMLSelectElement>,
          v8::External::New(reinterpret_cast<void*>(V8ClassIndex::NODE)));
      break;
    case V8ClassIndex::HTMLDOCUMENT: {
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(HTMLDocument),
          USE_NAMED_PROPERTY_SETTER(HTMLDocument),
          0,
          USE_NAMED_PROPERTY_DELETER(HTMLDocument));

      // We add an extra internal field to all Document wrappers for
      // storing a per document DOMImplementation wrapper.
      //
      // Additionally, we add two extra internal fields for
      // HTMLDocuments to implement temporary shadowing of
      // document.all.  One field holds an object that is used as a
      // marker.  The other field holds the marker object if
      // document.all is not shadowed and some other value if
      // document.all is shadowed.
      v8::Local<v8::ObjectTemplate> instance_template =
        desc->InstanceTemplate();
      ASSERT(instance_template->InternalFieldCount() ==
             V8Custom::kDefaultWrapperInternalFieldCount);
      instance_template->SetInternalFieldCount(
          V8Custom::kHTMLDocumentInternalFieldCount);
      break;
    }
    case V8ClassIndex::DOCUMENT:
    case V8ClassIndex::SVGDOCUMENT: {
      // We add an extra internal field to all Document wrappers for
      // storing a per document DOMImplementation wrapper.
      v8::Local<v8::ObjectTemplate> instance_template =
        desc->InstanceTemplate();
      ASSERT(instance_template->InternalFieldCount() ==
             V8Custom::kDefaultWrapperInternalFieldCount);
      instance_template->SetInternalFieldCount(
          V8Custom::kDocumentMinimumInternalFieldCount);
      break;
    }
    case V8ClassIndex::HTMLEMBEDELEMENT:
      // fall through
    case V8ClassIndex::HTMLOBJECTELEMENT:
      // Follow through. Both HTMLEmbedElement and HTMLObjectElement are
      // inherited from HTMLPlugInElement, and they share the same property
      // handling code.
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(HTMLPlugInElement),
          USE_NAMED_PROPERTY_SETTER(HTMLPlugInElement));
      desc->InstanceTemplate()->SetIndexedPropertyHandler(
          USE_INDEXED_PROPERTY_GETTER(HTMLPlugInElement),
          USE_INDEXED_PROPERTY_SETTER(HTMLPlugInElement));
      desc->InstanceTemplate()->SetCallAsFunctionHandler(
          USE_CALLBACK(HTMLPlugInElement));
      break;
    case V8ClassIndex::HTMLFRAMESETELEMENT:
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(HTMLFrameSetElement));
      break;
    case V8ClassIndex::HTMLFORMELEMENT:
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(HTMLFormElement));
      desc->InstanceTemplate()->SetIndexedPropertyHandler(
          USE_INDEXED_PROPERTY_GETTER(HTMLFormElement),
          0,
          0,
          0,
          CollectionIndexedPropertyEnumerator<HTMLFormElement>,
          v8::External::New(reinterpret_cast<void*>(V8ClassIndex::NODE)));
      break;
    case V8ClassIndex::MEDIALIST:
      SetCollectionStringOrNullIndexedGetter<MediaList>(desc);
      break;
    case V8ClassIndex::MIMETYPEARRAY:
      SetCollectionIndexedAndNamedGetters<MimeTypeArray>(
          desc,
          V8ClassIndex::MIMETYPE);
      break;
    case V8ClassIndex::NAMEDNODEMAP:
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(NamedNodeMap));
      desc->InstanceTemplate()->SetIndexedPropertyHandler(
          USE_INDEXED_PROPERTY_GETTER(NamedNodeMap),
          0,
          0,
          0,
          CollectionIndexedPropertyEnumerator<NamedNodeMap>,
          v8::External::New(reinterpret_cast<void*>(V8ClassIndex::NODE)));
      break;
    case V8ClassIndex::NODELIST:
      SetCollectionIndexedGetter<NodeList>(desc, V8ClassIndex::NODE);
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(NodeList));
      break;
    case V8ClassIndex::PLUGIN:
      SetCollectionIndexedAndNamedGetters<Plugin>(desc, V8ClassIndex::MIMETYPE);
      break;
    case V8ClassIndex::PLUGINARRAY:
      SetCollectionIndexedAndNamedGetters<PluginArray>(desc,
                                                       V8ClassIndex::PLUGIN);
      break;
    case V8ClassIndex::STYLESHEETLIST:
      desc->InstanceTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(StyleSheetList));
      SetCollectionIndexedGetter<StyleSheetList>(desc,
                                                 V8ClassIndex::STYLESHEET);
      break;
    case V8ClassIndex::DOMWINDOW: {
      v8::Local<v8::Signature> default_signature = v8::Signature::New(desc);

      desc->PrototypeTemplate()->SetNamedPropertyHandler(
          USE_NAMED_PROPERTY_GETTER(DOMWindow));
      desc->PrototypeTemplate()->SetIndexedPropertyHandler(
          USE_INDEXED_PROPERTY_GETTER(DOMWindow));

      desc->PrototypeTemplate()->Set(
          v8::String::New("addEventListener"),
          v8::FunctionTemplate::New(USE_CALLBACK(DOMWindowAddEventListener),
                                    v8::Handle<v8::Value>(),
                                    default_signature),
          v8::None);
      desc->PrototypeTemplate()->Set(
          v8::String::New("removeEventListener"),
          v8::FunctionTemplate::New(USE_CALLBACK(DOMWindowRemoveEventListener),
                                    v8::Handle<v8::Value>(),
                                    default_signature),
          v8::None);
      desc->SetHiddenPrototype(true);
      
      break;
    }
    case V8ClassIndex::LOCATION: {
      break;
    }
    case V8ClassIndex::HISTORY: {
      break;
    }

    // DOMParser, XMLSerializer, and XMLHttpRequest objects are created from
    // JS world, but we setup the constructor function lazily in
    // WindowNamedPropertyHandler::get.
    case V8ClassIndex::DOMPARSER:
      desc->SetCallHandler(USE_CALLBACK(DOMParserConstructor));
      break;
    case V8ClassIndex::XMLSERIALIZER:
      desc->SetCallHandler(USE_CALLBACK(XMLSerializerConstructor));
      break;
    case V8ClassIndex::XMLHTTPREQUEST: {
      // Reserve one more internal field for keeping event listeners.
      v8::Local<v8::ObjectTemplate> instance_template =
          desc->InstanceTemplate();
      instance_template->SetInternalFieldCount(
          V8Custom::kXMLHttpRequestInternalFieldCount);
      desc->SetCallHandler(USE_CALLBACK(XMLHttpRequestConstructor));
      break;
    }
    case V8ClassIndex::XPATHEVALUATOR:
      desc->SetCallHandler(USE_CALLBACK(XPathEvaluatorConstructor));
      break;
    case V8ClassIndex::XSLTPROCESSOR:
      desc->SetCallHandler(USE_CALLBACK(XSLTProcessorConstructor));
      break;
    default:
      break;
  }

  *cache_cell = desc;
  return desc;
}


bool V8Proxy::ContextInitialized() {
  return !m_context.IsEmpty();
}


DOMWindow* V8Proxy::retrieveWindow() {
  // TODO: This seems very fragile. How do we know that the global object
  // from the current context is something sensible? Do we need to use the
  // last entered here? Who calls this?
  v8::Handle<v8::Object> global = v8::Context::GetCurrent()->Global();
  if (global.IsEmpty()) return 0;
  v8::Handle<v8::Value> window = global->GetPrototype();
  return ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, window);
}


Frame* V8Proxy::retrieveFrame(v8::Handle<v8::Context> context) {
  v8::Handle<v8::Object> global = context->Global();
  v8::Handle<v8::Value> window_peer = global->GetPrototype();
  DOMWindow* window =
      ToNativeObject<DOMWindow>(V8ClassIndex::DOMWINDOW, window_peer);
  return window->frame();
}


Frame* V8Proxy::retrieveActiveFrame() {
  v8::Handle<v8::Context> context = v8::Context::GetEntered();
  if (context.IsEmpty()) 
    return 0;
  return retrieveFrame(context);
}


Frame* V8Proxy::retrieveFrame() {
  DOMWindow* window = retrieveWindow();
  return window ? window->frame() : 0;
}


V8Proxy* V8Proxy::retrieve() {
  DOMWindow* window = retrieveWindow();
  ASSERT(window);
  return retrieve(window->frame());
}


V8Proxy* V8Proxy::retrieve(Frame* frame) {
  if (!frame) return 0;
  V8Bridge* bridge = static_cast<V8Bridge*>(frame->scriptBridge());
  return bridge->isEnabled() ? bridge->proxy() : 0;
}


void V8Proxy::disconnectFrame() {
  // disconnect all event listeners
  DisconnectEventListeners();

  // clear all timeouts.
  if (m_frame->domWindow())
    m_frame->domWindow()->clearAllTimeouts();
}

bool V8Proxy::isEnabled() {
  Settings* settings = m_frame->settings();
  if (!settings)
    return false;
  
  // In the common case, JavaScript is enabled and we're done.
  if (settings->isJavaScriptEnabled())
    return true;

  // If JavaScript has been disabled, we need to look at the frame to tell
  // whether this script came from the web or the embedder. Scripts from the 
  // embedder are safe to run, but scripts from the other sources are 
  // disallowed.
  Document* document = m_frame->document();
  if (!document)
    return false;

  SecurityOrigin* origin = document->securityOrigin();
  if (origin->protocol().isEmpty())
    return false;  // Uninitialized document

  if (origin->protocol() == "http" || origin->protocol() == "https")
    return false;  // Web site

  if (origin->protocol() == 
      webkit_glue::StdStringToString(webkit_glue::GetUIResourceProtocol()))
    return true;   // Embedder's scripts are ok to run

  // If the scheme is ftp: or file:, an empty file name indicates a directory
  // listing, which requires JavaScript to function properly.
  const char* kDirProtocols[] = { "ftp", "file" };
  GURL url(document->url().utf8().data());
  for (size_t i = 0; i < arraysize(kDirProtocols); ++i) {
    if (origin->protocol() == kDirProtocols[i]) {
      ASSERT(url.SchemeIs(kDirProtocols[i]));
      return url.ExtractFileName().empty();
    }
  }

  return false;  // Other protocols fall through to here
}


void V8Proxy::clearDocumentWrapper() {
  v8::HandleScope handle_scope;
  v8::Local<v8::Context> context = GetContext();
  if (context.IsEmpty()) return;  // not initialize yet

  if (!m_document.IsEmpty()) {
#ifndef NDEBUG
    UnregisterGlobalHandle(this, m_document);
#endif
    m_document.Dispose();
    m_document.Clear();
  }
}


// static
void V8Proxy::DomainChanged(Frame* frame) {
  V8Proxy* proxy = retrieve(frame);
  proxy->ClearSecurityToken();
}


void V8Proxy::ClearSecurityToken() {
  m_context->SetSecurityToken(m_global);
}


void V8Proxy::clear() {
  if (!m_context.IsEmpty()) {
    ClearSecurityToken();

    if (m_frame->domWindow())
      m_frame->domWindow()->clearAllTimeouts();

    clearDocumentWrapper();

    // Corresponds to the context creation in initContextIfNeeded().
    m_context.Dispose();
    m_context.Clear();
  }
}


// Check if two frames are from the same origin.
// This function is equivalent to
// KJS::Window::allowsAccessFrom(const JSGlobalObject*,
//      SecurityOrigin::Reason&, String& message) const.
static bool SameOrigin(Frame* source, Frame* target,
                       SecurityOrigin::Reason& reason, String& message) {
  if (!source) {
    reason = SecurityOrigin::GenericMismatch;
    return false;
  }

  if (!target) {
    reason = SecurityOrigin::GenericMismatch;
    return false;
  }

  // Allow access if the frames the windows represent are the same.
  if (source == target)
    return true;

  Document* target_document = target->document();

  // JS may be attempting to access the "window" object, which should be valid,
  // even if the document hasn't been constructed yet.  If the document doesn't
  // exist yet allow JS to access the window object.
  if (!target_document)
    return true;

  Document* act_document = source->document();

  const SecurityOrigin* active_security_origin = act_document->securityOrigin();
  const SecurityOrigin* target_security_origin = 
      target_document->securityOrigin();

  String ui_resource_protocol = 
      webkit_glue::StdStringToString(webkit_glue::GetUIResourceProtocol());
  if (active_security_origin->protocol() == ui_resource_protocol) {
    KURL inspector_url = 
        webkit_glue::GURLToKURL(webkit_glue::GetInspectorURL());
    ASSERT(inspector_url.protocol() == ui_resource_protocol);
    ASSERT(inspector_url.protocol().endsWith("-resource"));

    // The Inspector can access anything.
    if (active_security_origin->host() == inspector_url.host())
      return true;

    // To mitigate XSS vulnerabilities on the browser itself, UI resources
    // besides the Inspector can't access other documents.
    return false;
  }

  if (active_security_origin->canAccess(target_security_origin, reason))
    return true;

  return false;
}


// Check if the current execution context can access a target frame.
// First it checks same domain policy using the security context
// (where the script is invoked), if domain check failed due to
// setting document.domain, using the lexical context of the function
// to check domain policy.
//
// This is equivalent to KJS::Window::allowsAccessFrom(ExecState*, String&).
bool V8Proxy::CanAccess(Frame* target) {
  SecurityOrigin::Reason reason;
  String message;

  // Check dynamic (security) context first.
  Frame* source = 
      V8Proxy::retrieveFrame(v8::Context::GetCurrentSecurityContext());
  if (SameOrigin(source, target, reason, message)) {
    return true;
  }

  // Check lexical orgin if the reason is DomainSetInDOM mismatch.
  if (reason == SecurityOrigin::DomainSetInDOMMismatch) {
    source = V8Proxy::retrieveFrame(v8::Context::GetCurrent());
    if (SameOrigin(source, target, reason, message)) {
      return true;
    }
  }

  return false;
}


bool V8Proxy::IsFromSameOrigin(Frame* target, bool report_error) {
  // The subject is detached from a frame, deny accesses.
  if (!target) return false;

  if (!CanAccess(target)) {
    if (report_error) ReportUnsafeAccessTo(target, REPORT_NOW);
    return false;
  }
  return true;
}


bool V8Proxy::CheckNodeSecurity(Node* node) {
  if (!node)
    return false;

  Frame* target = node->document()->frame();

  if (!target)
    return false;

  return IsFromSameOrigin(target, true);
}


// Create a new environment and setup the global object.
//
// The global object corresponds to a DOMWindow instance.  However, to
// allow properties of the JS DOMWindow instance to be shadowed, we
// use a shadow object as the global object and use the JS DOMWindow
// instance as the prototype for that shadow object.  The JS DOMWindow
// instance is undetectable from javascript code because the __proto__
// accessors skip that object.
//
// The shadow object and the DOMWindow instance are seen as one object
// from javascript.  The javascript object that corresponds to a
// DOMWindow instance is the shadow object.  When mapping a DOMWindow
// instance to a V8 object, we return the shadow object.
void V8Proxy::initContextIfNeeded() {
  // Bail out if the context has already been initialized.
  if (!m_context.IsEmpty()) return;

  // Install counters handler with V8.
  static bool v8_counters_initialized = false;
  if (!v8_counters_initialized) {
    v8::V8::SetCounterFunction(StatsTable::FindLocation);
    v8_counters_initialized = true;
  }

  // Setup the security handlers and message listener.  This only has
  // to be done once.
  static bool v8_initialized = false;
  if (!v8_initialized) {
    v8_initialized = true;

    // Tells V8 not to call the default OOM handler, binding code
    // will handle it.
    v8::V8::IgnoreOutOfMemoryException();
    v8::V8::SetFatalErrorHandler(ReportFatalErrorInV8);

    v8::V8::SetGlobalGCPrologueCallback(&GCPrologue);
    v8::V8::SetGlobalGCEpilogueCallback(&GCEpilogue);

    v8::V8::AddMessageListener(HandleConsoleMessage);

    v8::V8::SetFailedAccessCheckCallbackFunction(ReportUnsafeJavaScriptAccess);
  }

  // Create a new environment using an empty template for the shadow
  // object.  Reuse the global object if one has been created earlier.
  v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
  if (global_template.IsEmpty())
    return;

  // Install a security handler with V8.
  { v8::Local<v8::External> external =
        v8::External::New(reinterpret_cast<void*>(V8ClassIndex::DOMWINDOW));
    if (external.IsEmpty())
      return;

    global_template->SetAccessCheckCallbacks(
        V8Custom::v8DOMWindowNamedSecurityCheck,
        V8Custom::v8DOMWindowIndexedSecurityCheck,
        external);
  }

  m_context = v8::Context::New(NULL, global_template, m_global);
  if (m_context.IsEmpty())
    return;

  // Starting from now, use local context only.
  v8::Local<v8::Context> context = GetContext();
  v8::Context::Scope scope(context);

  // Store the first global object created so we can reuse it.
  if (m_global.IsEmpty()) {
    m_global = v8::Persistent<v8::Object>::New(context->Global());
#ifndef NDEBUG
    RegisterGlobalHandle(PROXY, this, m_global);
#endif
  }

  // Create a new JS window object and use it as the prototype for the
  // shadow global object.
  v8::Persistent<v8::FunctionTemplate> window_descriptor =
      GetTemplate(V8ClassIndex::DOMWINDOW);
  v8::Local<v8::Object> window_peer =
      SafeAllocation::NewInstance(window_descriptor->GetFunction());
  if (window_peer.IsEmpty())
    return;

  DOMWindow* window = m_frame->domWindow();

  // Get rid of the old window peer object if one exists.
  dom_object_map().forget(window);

  // Setup the peer object for the DOM window.
  dom_object_map().set(window, v8::Persistent<v8::Object>::New(window_peer));
  // Wrap the window.
  SetDOMWrapper(window_peer,
                V8ClassIndex::ToInt(V8ClassIndex::DOMWINDOW),
                window);
  // Insert the window instance as the prototype of the shadow object.
  v8::Handle<v8::Object> v8_global = context->Global();
  v8_global->Set(v8::String::New("__proto__"), window_peer);

  context->SetSecurityToken(GenerateSecurityToken(context));

  V8Proxy::retrieveFrame(context)->loader()->dispatchWindowObjectAvailable();

  if (JSBridge::RecordPlaybackMode()) {
    // Inject code which overrides a few common JS functions for implementing
    // randomness.  In order to implement effective record & playback of
    // websites, it is important that the URLs not change.  Many popular web
    // based apps use randomness in URLs to unique-ify urls for proxies.
    // Unfortunately, this breaks playback.
    // To work around this, we take the two most common client-side randomness
    // generators and make them constant.  They really need to be constant
    // (rather than a constant seed followed by constant change)
    // because the playback mode wants flexibility in how it plays them back
    // and cannot always guarantee that requests for randomness are played back
    // in exactly the same order in which they were recorded.
    String script(
        "Math.random = function() { return 0.5; };"
        "__ORIGDATE__ = Date;"
        "Date.__proto__.now = function() { "
        "    return new __ORIGDATE__(1204251968254); };"
        "Date = function() { return Date.now(); };");
    this->Evaluate(String(), 0, script, 0);
  }
}


v8::Handle<v8::Value> V8Proxy::GenerateSecurityToken(
    v8::Local<v8::Context> context) {
  Document* document = V8Proxy::retrieveFrame(context)->document();
  if (!document)
    return context->Global();

  // Ask the document's SecurityOrigin to generate a security token.
  // If two tokens are equal, then the SecurityOrigins canAccess each other.
  // If two tokens are not equal, then we have to call canAccess.
  String token = document->securityOrigin()->securityToken();

  // An empty token means we always have to call canAccess.  In this case, we
  // use the global object as the security token to avoid calling canAccess
  // when a script accesses its own objects.
  if (token.isEmpty())
    return context->Global();

  CString utf8_token = token.utf8();
  // NOTE: V8 does identity comparison in fast path, must use a symbol
  // as the security token.
  return v8::String::NewSymbol(utf8_token.data(), utf8_token.length());
}


void V8Proxy::SetDOMException(int exception_code) {
  if (exception_code <= 0) return;

  if (exception_code == XMLHttpRequestException::PERMISSION_DENIED) {
    ThrowError(GENERAL_ERROR, "Permission denied");
    return;
  }

  ExceptionCodeDescription description;
  getExceptionCodeDescription(exception_code, description);

  v8::Handle<v8::Value> exception;
  switch (description.type) {
    case DOMExceptionType:
      exception = ToV8Object(V8ClassIndex::DOMCOREEXCEPTION,
                             new DOMCoreException(description));
      break;
    case RangeExceptionType:
      exception = ToV8Object(V8ClassIndex::RANGEEXCEPTION,
                             new RangeException(description));
      break;
    case EventExceptionType:
      exception = ToV8Object(V8ClassIndex::EVENTEXCEPTION,
                             new EventException(description));
      break;
    case XMLHttpRequestExceptionType:
      exception = ToV8Object(V8ClassIndex::XMLHTTPREQUESTEXCEPTION,
                             new XMLHttpRequestException(description));
      break;
#if ENABLE(SVG)
    case SVGExceptionType:
      exception = ToV8Object(V8ClassIndex::SVGEXCEPTION,
                             new SVGException(description));
      break;
#endif
#if ENABLE(XPATH)
    case XPathExceptionType:
      exception = ToV8Object(V8ClassIndex::XPATHEXCEPTION,
                             new XPathException(description));
      break;
#endif
  }

  ASSERT(!exception.IsEmpty());
  v8::ThrowException(exception);
}


v8::Handle<v8::Value> V8Proxy::ThrowError(ErrorType type, const char* message) {
  switch (type) {
    case RANGE_ERROR:
      return v8::ThrowException(v8::Exception::RangeError(v8String(message)));
    case REFERENCE_ERROR:
      return v8::ThrowException(
          v8::Exception::ReferenceError(v8String(message)));
    case SYNTAX_ERROR:
      return v8::ThrowException(v8::Exception::SyntaxError(v8String(message)));
    case TYPE_ERROR:
      return v8::ThrowException(v8::Exception::TypeError(v8String(message)));
    case GENERAL_ERROR:
      return v8::ThrowException(v8::Exception::Error(v8String(message)));
    default:
      ASSERT(false);
      return v8::Handle<v8::Value>();
  }
}


v8::Local<v8::Context> V8Proxy::GetContext(Frame* frame) {
  V8Proxy* proxy = retrieve(frame);
  if (!proxy)
    return v8::Local<v8::Context>();

  proxy->initContextIfNeeded();
  return proxy->GetContext();
}


v8::Local<v8::Context> V8Proxy::GetCurrentContext() {
  return v8::Context::GetCurrent();
}


v8::Handle<v8::Value> V8Proxy::ToV8Object(V8ClassIndex::V8WrapperType type,
                                          void* imp) {
  ASSERT(type != V8ClassIndex::EVENTLISTENER);
  ASSERT(type != V8ClassIndex::EVENTTARGET);
  ASSERT(type != V8ClassIndex::EVENT);

  if (!imp) return v8::Null();

#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:

  switch (type) {
    NODE_WRAPPER_TYPES(MAKE_CASE)
    HTMLELEMENT_TYPES(MAKE_CASE)
#if ENABLE(SVG)
    SVGNODE_WRAPPER_TYPES(MAKE_CASE)
    SVGELEMENT_TYPES(MAKE_CASE)
#endif
      return NodeToV8Object(static_cast<Node*>(imp));
    case V8ClassIndex::CSSVALUE:
      return CSSValueToV8Object(static_cast<CSSValue*>(imp));
    case V8ClassIndex::CSSRULE:
      return CSSRuleToV8Object(static_cast<CSSRule*>(imp));
    case V8ClassIndex::STYLESHEET:
      return StyleSheetToV8Object(static_cast<StyleSheet*>(imp));
    case V8ClassIndex::DOMWINDOW:
      return WindowToV8Object(static_cast<DOMWindow*>(imp));
#if ENABLE(SVG)
    SVGNONNODE_WRAPPER_TYPES(MAKE_CASE)
      if (type == V8ClassIndex::SVGELEMENTINSTANCE) {
        return SVGElementInstanceToV8Object(
            static_cast<SVGElementInstance*>(imp));
      } else {
        return SVGObjectWithContextToV8Object(static_cast<Peerable*>(imp),
                                              type);
      }
#endif
    default:
      break;
  }

#undef MAKE_CASE

  // Non DOM node
  Peerable* obj = static_cast<Peerable*>(imp);
  v8::Persistent<v8::Object> result = dom_object_map().get(obj);
  if (result.IsEmpty()) {
    v8::Local<v8::Object> v8obj = InstantiateV8Object(type, imp);
    if (!v8obj.IsEmpty()) {
      result = v8::Persistent<v8::Object>::New(v8obj);
      dom_object_map().set(obj, result);
    }
  }
  return result;
}


V8ClassIndex::V8WrapperType V8Proxy::GetDOMWrapperType(
    v8::Handle<v8::Object> object) {
  if (!MaybeDOMWrapper(object)) {
    return V8ClassIndex::INVALID_CLASS_INDEX;
  }

  v8::Handle<v8::Value> type = object->GetInternalField(1);
  return V8ClassIndex::FromInt(type->Int32Value());
}


void* V8Proxy::FastToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
                                      v8::Handle<v8::Value> object) {
  // Native event listener is per frame, it cannot be handled
  // by this generic function.
  ASSERT(type != V8ClassIndex::EVENTLISTENER);
  ASSERT(type != V8ClassIndex::EVENTTARGET);

  ASSERT(MaybeDOMWrapper(object));

#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
  switch (type) {
    NODE_WRAPPER_TYPES(MAKE_CASE)
    HTMLELEMENT_TYPES(MAKE_CASE)
#if ENABLE(SVG)
    SVGNODE_WRAPPER_TYPES(MAKE_CASE)
    SVGELEMENT_TYPES(MAKE_CASE)
#endif
      return FastDOMWrapperToNative<Node>(object);
    case V8ClassIndex::XMLHTTPREQUEST:
      return FastDOMWrapperToNative<XMLHttpRequest>(object);
    case V8ClassIndex::EVENT:
      return FastDOMWrapperToNative<Event>(object);
    case V8ClassIndex::CSSRULE:
      return FastDOMWrapperToNative<CSSRule>(object);
    default:
      break;
  }
#undef MAKE_CASE

  return FastDOMWrapperToNative<Peerable>(object);
}


v8::Handle<v8::Object> V8Proxy::LookupDOMWrapper(
    V8ClassIndex::V8WrapperType type, v8::Handle<v8::Value> value) {
  if (value.IsEmpty()) return v8::Handle<v8::Object>();

  v8::Handle<v8::FunctionTemplate> desc = V8Proxy::GetTemplate(type);
  while (value->IsObject()) {
    v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(value);
    if (desc->HasInstance(object))
      return object;

    value = object->GetPrototype();
  }
  return v8::Handle<v8::Object>();
}


void* V8Proxy::ToNativeObjectImpl(V8ClassIndex::V8WrapperType type,
                                  v8::Handle<v8::Value> object) {
  // Native event listener is per frame, it cannot be handled
  // by this generic function.
  ASSERT(type != V8ClassIndex::EVENTLISTENER);
  ASSERT(type != V8ClassIndex::EVENTTARGET);

  // It could be null, undefined, etc.
  if (!MaybeDOMWrapper(object))
    return 0;

#define MAKE_CASE(TYPE, NAME) case V8ClassIndex::TYPE:
  switch (type) {
    NODE_WRAPPER_TYPES(MAKE_CASE)
    HTMLELEMENT_TYPES(MAKE_CASE)
#if ENABLE(SVG)
    SVGNODE_WRAPPER_TYPES(MAKE_CASE)
    SVGELEMENT_TYPES(MAKE_CASE)
#endif
      return DOMWrapperToNative<Node>(object);
    case V8ClassIndex::XMLHTTPREQUEST:
      return DOMWrapperToNative<XMLHttpRequest>(object);
    case V8ClassIndex::EVENT:
      return DOMWrapperToNative<Event>(object);
    case V8ClassIndex::CSSRULE:
      return DOMWrapperToNative<CSSRule>(object);
    default:
      break;
  }
#undef MAKE_CASE

  return DOMWrapperToNative<Peerable>(object);
}


NodeFilter* V8Proxy::ToNativeNodeFilter(v8::Handle<v8::Value> filter) {
  // A NodeFilter is used when walking through a DOM tree or iterating tree
  // nodes.
  // TODO: we may want to cache NodeFilterCondition and NodeFilter
  // object, but it is minor.
  // NodeFilter is passed to NodeIterator that has a ref counted pointer
  // to NodeFilter. NodeFilter has a ref counted pointer to NodeFilterCondition.
  // In NodeFilterCondition, filter object is persisted in its constructor,
  // and disposed in its destructor. No need to use peer field in this case.
  if (!filter->IsFunction()) return 0;

  NodeFilterCondition* cond = new V8NodeFilterCondition(filter);
  return new NodeFilter(cond);
}


v8::Local<v8::Object> V8Proxy::InstantiateV8Object(
    V8ClassIndex::V8WrapperType type, void* imp) {
  V8ClassIndex::V8WrapperType wrapper_type = type;
  // Make a special case for document.all
  if (type == V8ClassIndex::HTMLCOLLECTION &&
      static_cast<HTMLCollection*>(imp)->type() == HTMLCollection::DocAll) {
    wrapper_type = V8ClassIndex::UNDETECTABLEHTMLCOLLECTION;
  }

  // Special case for HTMLInputElements that support selection.
  if (type == V8ClassIndex::HTMLINPUTELEMENT) {
    HTMLInputElement* element = static_cast<HTMLInputElement*>(imp);
    if (element->canHaveSelection()) {
      wrapper_type = V8ClassIndex::HTMLSELECTIONINPUTELEMENT;
    }
  }

  v8::Persistent<v8::FunctionTemplate> desc = GetTemplate(wrapper_type);
  v8::Local<v8::Function> function = desc->GetFunction();
  v8::Local<v8::Object> instance = SafeAllocation::NewInstance(function);
  if (!instance.IsEmpty()) {
    // Avoid setting the DOM wrapper for failed allocations.
    SetDOMWrapper(instance, V8ClassIndex::ToInt(type), imp);
  }
  return instance;
}

v8::Handle<v8::Value> V8Proxy::CheckNewLegal(const v8::Arguments& args) {
  if (!AllowAllocation::m_current) {
    return ThrowError(TYPE_ERROR, "Illegal constructor");
  } else {
    return args.This();
  }
}


v8::Handle<v8::Value> V8Proxy::WrapCPointer(void* cptr) {
  // Represent void* as int
  int addr = reinterpret_cast<int>(cptr);
  if ((addr & 0x01) == 0) {
    return v8::Number::New(addr >> 1);
  } else {
    return v8::External::New(cptr);
  }
}


void* V8Proxy::ExtractCPointerImpl(v8::Handle<v8::Value> obj) {
  if (obj->IsNumber()) {
    int addr = obj->Int32Value();
    return reinterpret_cast<void*>(addr << 1);
  } else if (obj->IsExternal()) {
    return v8::Handle<v8::External>::Cast(obj)->Value();
  }
  ASSERT(false);
  return 0;
}


bool V8Proxy::SetDOMWrapper(v8::Handle<v8::Object> obj, int type, void* cptr) {
  ASSERT(obj->InternalFieldCount() >= 2);
  obj->SetInternalField(V8Custom::kDOMWrapperObjectIndex, WrapCPointer(cptr));
  obj->SetInternalField(V8Custom::kDOMWrapperTypeIndex, v8::Integer::New(type));
  return true;
}


bool V8Proxy::MaybeDOMWrapper(v8::Handle<v8::Value> value) {
  if (value.IsEmpty() || !value->IsObject()) return false;

  v8::Handle<v8::Object> obj = v8::Handle<v8::Object>::Cast(value);
  if (obj->InternalFieldCount() < V8Custom::kDefaultWrapperInternalFieldCount)
    return false;

  v8::Handle<v8::Value> wrapper =
      obj->GetInternalField(V8Custom::kDOMWrapperObjectIndex);
  if (!wrapper->IsNumber() && !wrapper->IsExternal()) return false;

  v8::Handle<v8::Value> type =
      obj->GetInternalField(V8Custom::kDOMWrapperTypeIndex);
  if (!type->IsNumber()) return false;

  return true;
}


#define FOR_EACH_TAG(macro)                      \
  macro(a, ANCHOR)                               \
  macro(applet, APPLET)                          \
  macro(area, AREA)                              \
  macro(base, BASE)                              \
  macro(basefont, BASEFONT)                      \
  macro(blockquote, BLOCKQUOTE)                  \
  macro(body, BODY)                              \
  macro(br, BR)                                  \
  macro(button, BUTTON)                          \
  macro(caption, TABLECAPTION)                   \
  macro(col, TABLECOL)                           \
  macro(colgroup, TABLECOL)                      \
  macro(del, MOD)                                \
  macro(canvas, CANVAS)                          \
  macro(dir, DIRECTORY)                          \
  macro(div, DIV)                                \
  macro(dl, DLIST)                               \
  macro(embed, EMBED)                            \
  macro(fieldset, FIELDSET)                      \
  macro(font, FONT)                              \
  macro(form, FORM)                              \
  macro(frame, FRAME)                            \
  macro(frameset, FRAMESET)                      \
  macro(h1, HEADING)                             \
  macro(h2, HEADING)                             \
  macro(h3, HEADING)                             \
  macro(h4, HEADING)                             \
  macro(h5, HEADING)                             \
  macro(h6, HEADING)                             \
  macro(head, HEAD)                              \
  macro(hr, HR)                                  \
  macro(html, HTML)                              \
  macro(img, IMAGE)                              \
  macro(iframe, IFRAME)                          \
  macro(image, IMAGE)                            \
  macro(input, INPUT)                            \
  macro(ins, MOD)                                \
  macro(isindex, ISINDEX)                        \
  macro(keygen, SELECT)                          \
  macro(label, LABEL)                            \
  macro(legend, LEGEND)                          \
  macro(li, LI)                                  \
  macro(link, LINK)                              \
  macro(listing, PRE)                            \
  macro(map, MAP)                                \
  macro(marquee, MARQUEE)                        \
  macro(menu, MENU)                              \
  macro(meta, META)                              \
  macro(object, OBJECT)                          \
  macro(ol, OLIST)                               \
  macro(optgroup, OPTGROUP)                      \
  macro(option, OPTION)                          \
  macro(p, PARAGRAPH)                            \
  macro(param, PARAM)                            \
  macro(pre, PRE)                                \
  macro(q, QUOTE)                                \
  macro(script, SCRIPT)                          \
  macro(select, SELECT)                          \
  macro(style, STYLE)                            \
  macro(table, TABLE)                            \
  macro(thead, TABLESECTION)                     \
  macro(tbody, TABLESECTION)                     \
  macro(tfoot, TABLESECTION)                     \
  macro(td, TABLECELL)                           \
  macro(th, TABLECELL)                           \
  macro(tr, TABLEROW)                            \
  macro(textarea, TEXTAREA)                      \
  macro(title, TITLE)                            \
  macro(ul, ULIST)                               \
  macro(xmp, PRE)

V8ClassIndex::V8WrapperType V8Proxy::GetHTMLElementType(HTMLElement* element) {
  static HashMap<String, V8ClassIndex::V8WrapperType> map;
  if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
    map.set(#tag, V8ClassIndex::HTML##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
  }

  V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
  if (t == 0) return V8ClassIndex::HTMLELEMENT;
  return t;
}
#undef FOR_EACH_TAG

#if ENABLE(SVG)

#if ENABLE(SVG_ANIMATION)
#define FOR_EACH_ANIMATION_TAG(macro) \
    macro(animateColor, ANIMATECOLOR) \
    macro(animate, ANIMATE) \
    macro(animateTransform, ANIMATETRANSFORM) \
    macro(set, SET)
#else
#define FOR_EACH_ANIMATION_TAG(macro)
#endif

#if ENABLE(SVG_FILTERS)
#define FOR_EACH_FILTERS_TAG(macro) \
    macro(feBlend, FEBLEND) \
    macro(feColorMatrix, FECOLORMATRIX) \
    macro(feComponentTransfer, FECOMPONENTTRANSFER) \
    macro(feComposite, FECOMPOSITE) \
    macro(feDiffuseLighting, FEDIFFUSELIGHTING) \
    macro(feDisplacementMap, FEDISPLACEMENTMAP) \
    macro(feDistantLight, FEDISTANTLIGHT) \
    macro(feFlood, FEFLOOD) \
    macro(feFuncA, FEFUNCA) \
    macro(feFuncB, FEFUNCB) \
    macro(feFuncG, FEFUNCG) \
    macro(feFuncR, FEFUNCR) \
    macro(feGaussianBlur, FEGAUSSIANBLUR) \
    macro(feImage, FEIMAGE) \
    macro(feMerge, FEMERGE) \
    macro(feMergeNode, FEMERGENODE) \
    macro(feOffset, FEOFFSET) \
    macro(fePointLight, FEPOINTLIGHT) \
    macro(feSpecularLighting, FESPECULARLIGHTING) \
    macro(feSpotLight, FESPOTLIGHT) \
    macro(feTile, FETILE) \
    macro(feTurbulence, FETURBULENCE) \
    macro(filter, FILTER)
#else
#define FOR_EACH_FILTERS_TAG(macro)
#endif

#if ENABLE(SVG_FONTS)
#define FOR_EACH_FONTS_TAG(macro) \
    macro(definition-src, DEFINITIONSRC) \
    macro(font-face, FONTFACE) \
    macro(font-face-format, FONTFACEFORMAT) \
    macro(font-face-name, FONTFACENAME) \
    macro(font-face-src, FONTFACESRC) \
    macro(font-face-uri, FONTFACEURI)
#else
#define FOR_EACH_FONTS_TAG(marco)
#endif

#if ENABLE(SVG_FOREIGN_OBJECT)
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
    macro(foreignObject, FOREIGNOBJECT)
#else
#define FOR_EACH_FOREIGN_OBJECT_TAG(macro)
#endif

#if ENABLE(SVG_USE)
#define FOR_EACH_USE_TAG(macro) \
    macro(use, USE)
#else
#define FOR_EACH_USE_TAG(macro)
#endif

#define FOR_EACH_TAG(macro) \
    FOR_EACH_ANIMATION_TAG(macro) \
    FOR_EACH_FILTERS_TAG(macro) \
    FOR_EACH_FONTS_TAG(macro) \
    FOR_EACH_FOREIGN_OBJECT_TAG(macro) \
    FOR_EACH_USE_TAG(macro) \
    macro(a, A) \
    macro(circle, CIRCLE) \
    macro(clipPath, CLIPPATH) \
    macro(cursor, CURSOR) \
    macro(defs, DEFS) \
    macro(desc, DESC) \
    macro(ellipse, ELLIPSE) \
    macro(g, G) \
    macro(image, IMAGE) \
    macro(linearGradient, LINEARGRADIENT) \
    macro(line, LINE) \
    macro(marker, MARKER) \
    macro(mask, MASK) \
    macro(metadata, METADATA) \
    macro(path, PATH) \
    macro(pattern, PATTERN) \
    macro(polyline, POLYLINE) \
    macro(polygon, POLYGON) \
    macro(radialGradient, RADIALGRADIENT) \
    macro(rect, RECT) \
    macro(script, SCRIPT) \
    macro(stop, STOP) \
    macro(style, STYLE) \
    macro(svg, SVG) \
    macro(switch, SWITCH) \
    macro(symbol, SYMBOL) \
    macro(text, TEXT) \
    macro(textPath, TEXTPATH) \
    macro(title, TITLE) \
    macro(tref, TREF) \
    macro(tspan, TSPAN) \
    macro(view, VIEW) \
    // end of macro

V8ClassIndex::V8WrapperType V8Proxy::GetSVGElementType(SVGElement* element) {
  static HashMap<String, V8ClassIndex::V8WrapperType> map;
  if (map.isEmpty()) {
#define ADD_TO_HASH_MAP(tag, name) \
    map.set(#tag, V8ClassIndex::SVG##name##ELEMENT);
FOR_EACH_TAG(ADD_TO_HASH_MAP)
#undef ADD_TO_HASH_MAP
  }

  V8ClassIndex::V8WrapperType t = map.get(element->localName().impl());
  if (t == 0) return V8ClassIndex::SVGELEMENT;
  return t;
}
#undef FOR_EACH_TAG

#endif  // ENABLE(SVG)


v8::Handle<v8::Value> V8Proxy::EventToV8Object(Event* event) {
  if (!event) return v8::Null();

  v8::Handle<v8::Object> peer = dom_object_map().get(event);
  if (!peer.IsEmpty()) {
    return peer;
  }

  V8ClassIndex::V8WrapperType type = V8ClassIndex::EVENT;

  if (event->isKeyboardEvent())
    type = V8ClassIndex::KEYBOARDEVENT;
  else if (event->isMouseEvent())
    type = V8ClassIndex::MOUSEEVENT;
  else if (event->isMessageEvent())
    type = V8ClassIndex::MESSAGEEVENT;
  else if (event->isWheelEvent())
    type = V8ClassIndex::WHEELEVENT;
  else if (event->isTextEvent())
    type = V8ClassIndex::TEXTEVENT;
  else if (event->isUIEvent())
    type = V8ClassIndex::UIEVENT;
  else if (event->isMutationEvent())
    type = V8ClassIndex::MUTATIONEVENT;
  else if (event->isOverflowEvent())
    type = V8ClassIndex::OVERFLOWEVENT;
  else if (event->isProgressEvent())
    type = V8ClassIndex::PROGRESSEVENT;

  // Set the peer object for future access.
  v8::Handle<v8::Object> result = InstantiateV8Object(type, event);
  if (result.IsEmpty()) {
    // Instantiation failed. Avoid updating the DOM object map and
    // return null which is already handled by callers of this function
    // in case the event is NULL.
    return v8::Null();
  }

  dom_object_map().set(event, v8::Persistent<v8::Object>::New(result));

  return result;
}


v8::Handle<v8::Object> V8Proxy::NodeToV8Object(Node* node) {
  if (!node) return v8::Handle<v8::Object>();

  v8::Handle<v8::Object> peer = dom_node_map().get(node);
  if (!peer.IsEmpty()) {
    return peer;
  }

  bool is_document = false;  // document type node has special handling
  V8ClassIndex::V8WrapperType type;

  switch (node->nodeType()) {
    case Node::ELEMENT_NODE:
      if (node->isHTMLElement()) {
        type = GetHTMLElementType(static_cast<HTMLElement*>(node));
#if ENABLE(SVG)
      } else if (node->isSVGElement()) {
        type = GetSVGElementType(static_cast<SVGElement*>(node));
#endif
      } else {
        type = V8ClassIndex::ELEMENT;
      }
      break;
    case Node::ATTRIBUTE_NODE:
      type = V8ClassIndex::ATTR;
      break;
    case Node::TEXT_NODE:
      type = V8ClassIndex::TEXT;
      break;
    case Node::CDATA_SECTION_NODE:
      type = V8ClassIndex::CDATASECTION;
      break;
    case Node::ENTITY_NODE:
      type = V8ClassIndex::ENTITY;
      break;
    case Node::PROCESSING_INSTRUCTION_NODE:
      type = V8ClassIndex::PROCESSINGINSTRUCTION;
      break;
    case Node::COMMENT_NODE:
      type = V8ClassIndex::COMMENT;
      break;
    case Node::DOCUMENT_NODE: {
      is_document = true;
      Document* doc = static_cast<Document*>(node);
      if (doc->isHTMLDocument()) {
        type = V8ClassIndex::HTMLDOCUMENT;
#if ENABLE(SVG)
      } else if (doc->isSVGDocument()) {
        type = V8ClassIndex::SVGDOCUMENT;
#endif
      } else {
        type = V8ClassIndex::DOCUMENT;
      }
      break;
    }
    case Node::DOCUMENT_TYPE_NODE:
      type = V8ClassIndex::DOCUMENTTYPE;
      break;
    case Node::NOTATION_NODE:
      type = V8ClassIndex::NOTATION;
      break;
    case Node::DOCUMENT_FRAGMENT_NODE:
      type = V8ClassIndex::DOCUMENTFRAGMENT;
      break;
    case Node::ENTITY_REFERENCE_NODE:
      type = V8ClassIndex::ENTITYREFERENCE;
      break;
    default:
      type = V8ClassIndex::NODE;
  }

  // Set the peer object for future access.
  // InstantiateV8Object automatically casts node to Peerable*.
  v8::Local<v8::Object> result = InstantiateV8Object(type, node);
  if (result.IsEmpty()) {
    // If instantiation failed it's important not to add the result
    // to the DOM node map. Instead we return an empty handle, which
    // should already be handled by callers of this function in case
    // the node is NULL.
    return result;
  }

  dom_node_map().set(node, v8::Persistent<v8::Object>::New(result));

  if (is_document) {
    Document* doc = static_cast<Document*>(node);
    V8Proxy* proxy = V8Proxy::retrieve(doc->frame());
    if (proxy) {
      proxy->UpdateDocumentHandle(result);
    }

    if (type == V8ClassIndex::HTMLDOCUMENT) {
      // Create marker object and insert it in two internal fields.
      // This is used to implement temporary shadowing of
      // document.all.
      ASSERT(result->InternalFieldCount() ==
             V8Custom::kHTMLDocumentInternalFieldCount);
      v8::Local<v8::Object> marker = v8::Object::New();
      result->SetInternalField(V8Custom::kHTMLDocumentMarkerIndex, marker);
      result->SetInternalField(V8Custom::kHTMLDocumentShadowIndex, marker);
    }
  }

  return result;
}


void V8Proxy::UpdateDocumentHandle(v8::Local<v8::Object> handle) {
  // If the old handle is not empty, release it.
  if (!m_document.IsEmpty()) {
#ifndef NDEBUG
    UnregisterGlobalHandle(this, m_document);
#endif
    m_document.Dispose();
    m_document.Clear();
  }

  m_document = v8::Persistent<v8::Object>::New(handle);
#ifndef NDEBUG
  RegisterGlobalHandle(PROXY, this, m_document);
#endif
}


// A JS object of type EventTarget can only be two possible types:
// 1) EventTargetNode; 2) XMLHttpRequest;
v8::Handle<v8::Value> V8Proxy::EventTargetToV8Object(EventTarget* target) {
  if (!target) return v8::Null();

#if ENABLE(SVG)
  SVGElementInstance* instance = target->toSVGElementInstance();
  if (instance) return ToV8Object(V8ClassIndex::SVGELEMENTINSTANCE, instance);
#endif

  Node* node = target->toNode();
  if (node) return NodeToV8Object(node);

  // XMLHttpRequest is created within its JS counterpart.
  XMLHttpRequest* xhr = target->toXMLHttpRequest();
  if (xhr) {
    v8::Handle<v8::Object> peer = dom_object_map().get(xhr);
    ASSERT(!peer.IsEmpty());
    return peer;
  }

  ASSERT(0);
  return v8::Handle<v8::Value>();
}


v8::Handle<v8::Value> V8Proxy::EventListenerToV8Object(
    EventListener* listener) {
  if (listener == 0) return v8::Null();

  // TODO(fqian): can a user take a lazy event listener and set to other places?
  V8AbstractEventListener* v8listener =
      static_cast<V8AbstractEventListener*>(listener);
  return v8listener->GetListenerObject();
}


v8::Handle<v8::Value> V8Proxy::DOMImplementationToV8Object(
    DOMImplementation* impl) {
  v8::Handle<v8::Object> result =
    InstantiateV8Object(V8ClassIndex::DOMIMPLEMENTATION, impl);
  if (result.IsEmpty()) {
    // If the instantiation failed, we ignore it and return null instead
    // of returning an empty handle.
    return v8::Null();
  }
  return result;
}


v8::Handle<v8::Object> V8Proxy::StyleSheetToV8Object(StyleSheet* sheet) {
  if (!sheet) return v8::Handle<v8::Object>();

  v8::Handle<v8::Object> peer = dom_object_map().get(sheet);
  if (!peer.IsEmpty()) {
    return peer;
  }

  V8ClassIndex::V8WrapperType type = V8ClassIndex::STYLESHEET;
  if (sheet->isCSSStyleSheet()) type = V8ClassIndex::CSSSTYLESHEET;

  v8::Handle<v8::Object> result = InstantiateV8Object(type, sheet);
  if (!result.IsEmpty()) {
    // Only update the DOM object map if the result is non-empty.
    dom_object_map().set(sheet, v8::Persistent<v8::Object>::New(result));
  }
  return result;
}


v8::Handle<v8::Object> V8Proxy::CSSValueToV8Object(CSSValue* value) {
  if (!value) return v8::Handle<v8::Object>();

  v8::Handle<v8::Object> peer = dom_object_map().get(value);
  if (!peer.IsEmpty()) {
    return peer;
  }

  V8ClassIndex::V8WrapperType type;

  if (value->isValueList())
    type = V8ClassIndex::CSSVALUELIST;
  else if (value->isPrimitiveValue())
    type = V8ClassIndex::CSSPRIMITIVEVALUE;
#if ENABLE(SVG)
  else if (value->isSVGPaint())
    type = V8ClassIndex::SVGPAINT;
  else if (value->isSVGColor())
    type = V8ClassIndex::SVGCOLOR;
#endif
  else
    type = V8ClassIndex::CSSVALUE;

  v8::Handle<v8::Object> result = InstantiateV8Object(type, value);
  if (!result.IsEmpty()) {
    // Only update the DOM object map if the result is non-empty.
    dom_object_map().set(value, v8::Persistent<v8::Object>::New(result));
  }
  return result;
}


v8::Handle<v8::Object> V8Proxy::CSSRuleToV8Object(CSSRule* rule) {
  if (!rule) return v8::Handle<v8::Object>();

  v8::Handle<v8::Object> peer = dom_object_map().get(rule);
  if (!peer.IsEmpty()) {
    return peer;
  }

  V8ClassIndex::V8WrapperType type;

  switch (rule->type()) {
  case CSSRule::STYLE_RULE:
    type = V8ClassIndex::CSSSTYLERULE;
    break;
  case CSSRule::CHARSET_RULE:
    type = V8ClassIndex::CSSCHARSETRULE;
    break;
  case CSSRule::IMPORT_RULE:
    type = V8ClassIndex::CSSIMPORTRULE;
    break;
  case CSSRule::MEDIA_RULE:
    type = V8ClassIndex::CSSMEDIARULE;
    break;
  case CSSRule::FONT_FACE_RULE:
    type = V8ClassIndex::CSSFONTFACERULE;
    break;
  case CSSRule::PAGE_RULE:
    type = V8ClassIndex::CSSPAGERULE;
    break;
  default:  // CSSRule::UNKNOWN_RULE
    type = V8ClassIndex::CSSRULE;
  }

  // Set the peer object for future access.
  v8::Handle<v8::Object> result = InstantiateV8Object(type, rule);
  if (!result.IsEmpty()) {
    // Only update the DOM object map if the result is non-empty.
    dom_object_map().set(rule, v8::Persistent<v8::Object>::New(result));
  }
  return result;
}

v8::Handle<v8::Object> V8Proxy::WindowToV8Object(DOMWindow* window) {
  // Initializes environment of a frame, and return the global object
  // of the frame.
  Frame* frame = window->frame();
  if (!frame) return v8::Handle<v8::Object>();

  v8::Handle<v8::Context> context = GetContext(frame);
  if (context.IsEmpty()) return v8::Handle<v8::Object>();

  v8::Handle<v8::Object> global = context->Global();
  ASSERT(!global.IsEmpty());
  return global;
}


void V8Proxy::BindJSObjectToWindow(Frame* frame,
                                   const char* name,
                                   int type,
                                   v8::Handle<v8::FunctionTemplate> desc,
                                   void* imp) {
  // Get environment.
  v8::Handle<v8::Context> context = V8Proxy::GetContext(frame);
  if (context.IsEmpty()) return;  // JS not enabled.

  v8::Context::Scope scope(context);
  v8::Handle<v8::Object> instance = desc->GetFunction();
  SetDOMWrapper(instance, type, imp);

  v8::Handle<v8::Object> global = context->Global();
  global->Set(v8::String::New(name), instance);
}


void V8Proxy::ProcessConsoleMessages() {
  ConsoleMessageManager::ProcessDelayedMessages();
}


}  // namespace WebCore