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
|
// Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef INCLUDE_V8_ISOLATE_H_
#define INCLUDE_V8_ISOLATE_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <string>
#include <utility>
#include "cppgc/common.h"
#include "v8-array-buffer.h" // NOLINT(build/include_directory)
#include "v8-callbacks.h" // NOLINT(build/include_directory)
#include "v8-data.h" // NOLINT(build/include_directory)
#include "v8-debug.h" // NOLINT(build/include_directory)
#include "v8-embedder-heap.h" // NOLINT(build/include_directory)
#include "v8-exception.h" // NOLINT(build/include_directory)
#include "v8-function-callback.h" // NOLINT(build/include_directory)
#include "v8-internal.h" // NOLINT(build/include_directory)
#include "v8-local-handle.h" // NOLINT(build/include_directory)
#include "v8-microtask.h" // NOLINT(build/include_directory)
#include "v8-persistent-handle.h" // NOLINT(build/include_directory)
#include "v8-primitive.h" // NOLINT(build/include_directory)
#include "v8-statistics.h" // NOLINT(build/include_directory)
#include "v8-unwinder.h" // NOLINT(build/include_directory)
#include "v8config.h" // NOLINT(build/include_directory)
namespace v8 {
class CppHeap;
class HeapProfiler;
class MicrotaskQueue;
class StartupData;
class ScriptOrModule;
class SharedArrayBuffer;
namespace internal {
class MicrotaskQueue;
class ThreadLocalTop;
} // namespace internal
namespace metrics {
class Recorder;
} // namespace metrics
/**
* A set of constraints that specifies the limits of the runtime's memory use.
* You must set the heap size before initializing the VM - the size cannot be
* adjusted after the VM is initialized.
*
* If you are using threads then you should hold the V8::Locker lock while
* setting the stack limit and you must set a non-default stack limit separately
* for each thread.
*
* The arguments for set_max_semi_space_size, set_max_old_space_size,
* set_max_executable_size, set_code_range_size specify limits in MB.
*
* The argument for set_max_semi_space_size_in_kb is in KB.
*/
class V8_EXPORT ResourceConstraints {
public:
/**
* Configures the constraints with reasonable default values based on the
* provided heap size limit. The heap size includes both the young and
* the old generation.
*
* \param initial_heap_size_in_bytes The initial heap size or zero.
* By default V8 starts with a small heap and dynamically grows it to
* match the set of live objects. This may lead to ineffective
* garbage collections at startup if the live set is large.
* Setting the initial heap size avoids such garbage collections.
* Note that this does not affect young generation garbage collections.
*
* \param maximum_heap_size_in_bytes The hard limit for the heap size.
* When the heap size approaches this limit, V8 will perform series of
* garbage collections and invoke the NearHeapLimitCallback. If the garbage
* collections do not help and the callback does not increase the limit,
* then V8 will crash with V8::FatalProcessOutOfMemory.
*/
void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes,
size_t maximum_heap_size_in_bytes);
/**
* Configures the constraints with reasonable default values based on the
* capabilities of the current device the VM is running on.
*
* \param physical_memory The total amount of physical memory on the current
* device, in bytes.
* \param virtual_memory_limit The amount of virtual memory on the current
* device, in bytes, or zero, if there is no limit.
*/
void ConfigureDefaults(uint64_t physical_memory,
uint64_t virtual_memory_limit);
/**
* The address beyond which the VM's stack may not grow.
*/
uint32_t* stack_limit() const { return stack_limit_; }
void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
/**
* The amount of virtual memory reserved for generated code. This is relevant
* for 64-bit architectures that rely on code range for calls in code.
*
* When V8_COMPRESS_POINTERS_IN_SHARED_CAGE is defined, there is a shared
* process-wide code range that is lazily initialized. This value is used to
* configure that shared code range when the first Isolate is
* created. Subsequent Isolates ignore this value.
*/
size_t code_range_size_in_bytes() const { return code_range_size_; }
void set_code_range_size_in_bytes(size_t limit) { code_range_size_ = limit; }
/**
* The maximum size of the old generation.
* When the old generation approaches this limit, V8 will perform series of
* garbage collections and invoke the NearHeapLimitCallback.
* If the garbage collections do not help and the callback does not
* increase the limit, then V8 will crash with V8::FatalProcessOutOfMemory.
*/
size_t max_old_generation_size_in_bytes() const {
return max_old_generation_size_;
}
void set_max_old_generation_size_in_bytes(size_t limit) {
max_old_generation_size_ = limit;
}
/**
* The maximum size of the young generation, which consists of two semi-spaces
* and a large object space. This affects frequency of Scavenge garbage
* collections and should be typically much smaller that the old generation.
*/
size_t max_young_generation_size_in_bytes() const {
return max_young_generation_size_;
}
void set_max_young_generation_size_in_bytes(size_t limit) {
max_young_generation_size_ = limit;
}
size_t initial_old_generation_size_in_bytes() const {
return initial_old_generation_size_;
}
void set_initial_old_generation_size_in_bytes(size_t initial_size) {
initial_old_generation_size_ = initial_size;
}
size_t initial_young_generation_size_in_bytes() const {
return initial_young_generation_size_;
}
void set_initial_young_generation_size_in_bytes(size_t initial_size) {
initial_young_generation_size_ = initial_size;
}
uint64_t physical_memory_size_in_bytes() const {
return physical_memory_size_;
}
private:
static constexpr size_t kMB = 1048576u;
size_t code_range_size_ = 0;
size_t max_old_generation_size_ = 0;
size_t max_young_generation_size_ = 0;
size_t initial_old_generation_size_ = 0;
size_t initial_young_generation_size_ = 0;
uint64_t physical_memory_size_ = 0;
uint32_t* stack_limit_ = nullptr;
};
/**
* Memory pressure level for the MemoryPressureNotification.
* kNone hints V8 that there is no memory pressure.
* kModerate hints V8 to speed up incremental garbage collection at the cost of
* of higher latency due to garbage collection pauses.
* kCritical hints V8 to free memory as soon as possible. Garbage collection
* pauses at this level will be large.
*/
enum class MemoryPressureLevel { kNone, kModerate, kCritical };
/**
* Signal for dependants of contexts. Useful for
* `ContextDisposedNotification()` to implement different strategies.
*/
enum class ContextDependants {
/** Context has no dependants. These are usually top-level contexts. */
kNoDependants,
/** Context has some dependants, i.e., it may depend on other contexts. This
is usually the case for inner contexts. */
kSomeDependants
};
/**
* Indicator for the stack state.
*/
using StackState = cppgc::EmbedderStackState;
/**
* The set of V8 isolates in a process is partitioned into groups. Each group
* has its own sandbox (if V8 was configured with support for the sandbox) and
* pointer-compression cage (if configured with pointer compression).
*
* By default, all isolates are placed in the same group. This is the most
* efficient configuration in terms of speed and memory use. However, with
* pointer compression enabled, total heap usage of isolates in a group
* cannot exceed 4 GB, not counting array buffers and other off-heap storage.
* Using multiple isolate groups can allow embedders to allocate more than 4GB
* of objects with pointer compression enabled, if the embedder's use case can
* span multiple isolates.
*
* Creating an isolate group reserves a range of virtual memory addresses. A
* group's memory mapping will be released when the last isolate in the group is
* disposed, and there are no more live IsolateGroup objects that refer to it.
*
* Note that Isolate groups are reference counted, and
* the IsolateGroup type is a reference to one.
*
* Note that it's not going to be possible to pass shared JS objects
* across IsolateGroup boundary.
*
*/
class V8_EXPORT IsolateGroup {
public:
/**
* Get the default isolate group. If this V8's build configuration only
* supports a single group, this is a reference to that single group.
* Otherwise this is a group like any other, distinguished only
* in that it is the first group.
*/
static IsolateGroup GetDefault();
/**
* Return true if new isolate groups can be created at run-time, or false if
* all isolates must be in the same group.
*/
static bool CanCreateNewGroups();
/**
* Create a new isolate group. If this V8's build configuration only supports
* a single group, abort.
*/
static IsolateGroup Create();
IsolateGroup(IsolateGroup&& other);
IsolateGroup& operator=(IsolateGroup&& other);
IsolateGroup(const IsolateGroup&);
IsolateGroup& operator=(const IsolateGroup&);
~IsolateGroup();
bool operator==(const IsolateGroup& other) const {
return isolate_group_ == other.isolate_group_;
}
bool operator!=(const IsolateGroup& other) const {
return !operator==(other);
}
#ifdef V8_ENABLE_SANDBOX
/**
* Whether the sandbox of the isolate group contains a given pointer.
* Will always return true if the sandbox is not enabled.
*/
bool SandboxContains(void* pointer) const;
VirtualAddressSpace* GetSandboxAddressSpace();
#else
V8_INLINE bool SandboxContains(void* pointer) const { return true; }
#endif
private:
friend class Isolate;
friend class ArrayBuffer::Allocator;
// The isolate_group pointer should be already acquired.
explicit IsolateGroup(internal::IsolateGroup*&& isolate_group);
internal::IsolateGroup* isolate_group_;
};
/**
* Isolate represents an isolated instance of the V8 engine. V8 isolates have
* completely separate states. Objects from one isolate must not be used in
* other isolates. The embedder can create multiple isolates and use them in
* parallel in multiple threads. An isolate can be entered by at most one
* thread at any given time. The Locker/Unlocker API must be used to
* synchronize.
*/
class V8_EXPORT Isolate {
public:
/**
* Initial configuration parameters for a new Isolate.
*/
struct V8_EXPORT CreateParams {
CreateParams();
~CreateParams();
ALLOW_COPY_AND_MOVE_WITH_DEPRECATED_FIELDS(CreateParams)
/**
* Allows the host application to provide the address of a function that is
* notified each time code is added, moved or removed.
*/
JitCodeEventHandler code_event_handler = nullptr;
/**
* ResourceConstraints to use for the new Isolate.
*/
ResourceConstraints constraints;
/**
* Explicitly specify a startup snapshot blob. The embedder owns the blob.
* The embedder *must* ensure that the snapshot is from a trusted source.
*/
const StartupData* snapshot_blob = nullptr;
/**
* Enables the host application to provide a mechanism for recording
* statistics counters.
*/
CounterLookupCallback counter_lookup_callback = nullptr;
/**
* Enables the host application to provide a mechanism for recording
* histograms. The CreateHistogram function returns a
* histogram which will later be passed to the AddHistogramSample
* function.
*/
CreateHistogramCallback create_histogram_callback = nullptr;
AddHistogramSampleCallback add_histogram_sample_callback = nullptr;
/**
* The ArrayBuffer::Allocator to use for allocating and freeing the backing
* store of ArrayBuffers.
*
* If the shared_ptr version is used, the Isolate instance and every
* |BackingStore| allocated using this allocator hold a std::shared_ptr
* to the allocator, in order to facilitate lifetime
* management for the allocator instance.
*/
ArrayBuffer::Allocator* array_buffer_allocator = nullptr;
std::shared_ptr<ArrayBuffer::Allocator> array_buffer_allocator_shared;
/**
* Specifies an optional nullptr-terminated array of raw addresses in the
* embedder that V8 can match against during serialization and use for
* deserialization. This array and its content must stay valid for the
* entire lifetime of the isolate.
*/
const intptr_t* external_references = nullptr;
/**
* Whether calling Atomics.wait (a function that may block) is allowed in
* this isolate. This can also be configured via SetAllowAtomicsWait.
*/
bool allow_atomics_wait = true;
/**
* The following parameters describe the offsets for addressing type info
* for wrapped API objects and are used by the fast C API
* (for details see v8-fast-api-calls.h).
*/
int embedder_wrapper_type_index = -1;
int embedder_wrapper_object_index = -1;
/**
* Callbacks to invoke in case of fatal or OOM errors.
*/
FatalErrorCallback fatal_error_callback = nullptr;
OOMErrorCallback oom_error_callback = nullptr;
/**
* A CppHeap used to construct the Isolate. V8 takes ownership of the
* CppHeap passed this way.
*/
CppHeap* cpp_heap = nullptr;
};
/**
* Stack-allocated class which sets the isolate for all operations
* executed within a local scope.
*/
class V8_EXPORT V8_NODISCARD Scope {
public:
explicit Scope(Isolate* isolate) : v8_isolate_(isolate) {
v8_isolate_->Enter();
}
~Scope() { v8_isolate_->Exit(); }
// Prevent copying of Scope objects.
Scope(const Scope&) = delete;
Scope& operator=(const Scope&) = delete;
private:
Isolate* const v8_isolate_;
};
/**
* Assert that no Javascript code is invoked.
*/
class V8_EXPORT V8_NODISCARD DisallowJavascriptExecutionScope {
public:
enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE, DUMP_ON_FAILURE };
DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
~DisallowJavascriptExecutionScope();
// Prevent copying of Scope objects.
DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
delete;
DisallowJavascriptExecutionScope& operator=(
const DisallowJavascriptExecutionScope&) = delete;
private:
v8::Isolate* const v8_isolate_;
const OnFailure on_failure_;
bool was_execution_allowed_;
};
/**
* Introduce exception to DisallowJavascriptExecutionScope.
*/
class V8_EXPORT V8_NODISCARD AllowJavascriptExecutionScope {
public:
explicit AllowJavascriptExecutionScope(Isolate* isolate);
~AllowJavascriptExecutionScope();
// Prevent copying of Scope objects.
AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
delete;
AllowJavascriptExecutionScope& operator=(
const AllowJavascriptExecutionScope&) = delete;
private:
Isolate* const v8_isolate_;
bool was_execution_allowed_assert_;
bool was_execution_allowed_throws_;
bool was_execution_allowed_dump_;
};
/**
* Do not run microtasks while this scope is active, even if microtasks are
* automatically executed otherwise.
*/
class V8_EXPORT V8_NODISCARD SuppressMicrotaskExecutionScope {
public:
explicit SuppressMicrotaskExecutionScope(
Isolate* isolate, MicrotaskQueue* microtask_queue = nullptr);
~SuppressMicrotaskExecutionScope();
// Prevent copying of Scope objects.
SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
delete;
SuppressMicrotaskExecutionScope& operator=(
const SuppressMicrotaskExecutionScope&) = delete;
private:
internal::Isolate* const i_isolate_;
internal::MicrotaskQueue* const microtask_queue_;
internal::Address previous_stack_height_;
friend class internal::ThreadLocalTop;
};
/**
* Types of garbage collections that can be requested via
* RequestGarbageCollectionForTesting.
*/
enum GarbageCollectionType {
kFullGarbageCollection,
kMinorGarbageCollection
};
/**
* Features reported via the SetUseCounterCallback callback. Do not change
* assigned numbers of existing items; add new features to the end of this
* list.
* Dead features can be marked `V8_DEPRECATE_SOON`, then `V8_DEPRECATED`, and
* then finally be renamed to `kOBSOLETE_...` to stop embedders from using
* them.
*/
enum UseCounterFeature {
kUseAsm = 0,
kBreakIterator = 1,
kOBSOLETE_LegacyConst = 2,
kOBSOLETE_MarkDequeOverflow = 3,
kOBSOLETE_StoreBufferOverflow = 4,
kOBSOLETE_SlotsBufferOverflow = 5,
kOBSOLETE_ObjectObserve = 6,
kForcedGC = 7,
kSloppyMode = 8,
kStrictMode = 9,
kOBSOLETE_StrongMode = 10,
kRegExpPrototypeStickyGetter = 11,
kRegExpPrototypeToString = 12,
kRegExpPrototypeUnicodeGetter = 13,
kOBSOLETE_IntlV8Parse = 14,
kOBSOLETE_IntlPattern = 15,
kOBSOLETE_IntlResolved = 16,
kOBSOLETE_PromiseChain = 17,
kOBSOLETE_PromiseAccept = 18,
kOBSOLETE_PromiseDefer = 19,
kHtmlCommentInExternalScript = 20,
kHtmlComment = 21,
kSloppyModeBlockScopedFunctionRedefinition = 22,
kForInInitializer = 23,
kOBSOLETE_ArrayProtectorDirtied = 24,
kArraySpeciesModified = 25,
kArrayPrototypeConstructorModified = 26,
kOBSOLETE_ArrayInstanceProtoModified = 27,
kArrayInstanceConstructorModified = 28,
kOBSOLETE_LegacyFunctionDeclaration = 29,
kOBSOLETE_RegExpPrototypeSourceGetter = 30,
kOBSOLETE_RegExpPrototypeOldFlagGetter = 31,
kDecimalWithLeadingZeroInStrictMode = 32,
kLegacyDateParser = 33,
kDefineGetterOrSetterWouldThrow = 34,
kFunctionConstructorReturnedUndefined = 35,
kAssigmentExpressionLHSIsCallInSloppy = 36,
kAssigmentExpressionLHSIsCallInStrict = 37,
kPromiseConstructorReturnedUndefined = 38,
kOBSOLETE_ConstructorNonUndefinedPrimitiveReturn = 39,
kOBSOLETE_LabeledExpressionStatement = 40,
kOBSOLETE_LineOrParagraphSeparatorAsLineTerminator = 41,
kIndexAccessor = 42,
kErrorCaptureStackTrace = 43,
kErrorPrepareStackTrace = 44,
kErrorStackTraceLimit = 45,
kWebAssemblyInstantiation = 46,
kDeoptimizerDisableSpeculation = 47,
kOBSOLETE_ArrayPrototypeSortJSArrayModifiedPrototype = 48,
kFunctionTokenOffsetTooLongForToString = 49,
kWasmSharedMemory = 50,
kWasmThreadOpcodes = 51,
kOBSOLETE_AtomicsNotify = 52,
kOBSOLETE_AtomicsWake = 53,
kCollator = 54,
kNumberFormat = 55,
kDateTimeFormat = 56,
kPluralRules = 57,
kRelativeTimeFormat = 58,
kLocale = 59,
kListFormat = 60,
kSegmenter = 61,
kStringLocaleCompare = 62,
kOBSOLETE_StringToLocaleUpperCase = 63,
kStringToLocaleLowerCase = 64,
kNumberToLocaleString = 65,
kDateToLocaleString = 66,
kDateToLocaleDateString = 67,
kDateToLocaleTimeString = 68,
kAttemptOverrideReadOnlyOnPrototypeSloppy = 69,
kAttemptOverrideReadOnlyOnPrototypeStrict = 70,
kOBSOLETE_OptimizedFunctionWithOneShotBytecode = 71,
kRegExpMatchIsTrueishOnNonJSRegExp = 72,
kRegExpMatchIsFalseishOnJSRegExp = 73,
kOBSOLETE_DateGetTimezoneOffset = 74,
kStringNormalize = 75,
kCallSiteAPIGetFunctionSloppyCall = 76,
kCallSiteAPIGetThisSloppyCall = 77,
kOBSOLETE_RegExpMatchAllWithNonGlobalRegExp = 78,
kRegExpExecCalledOnSlowRegExp = 79,
kRegExpReplaceCalledOnSlowRegExp = 80,
kDisplayNames = 81,
kSharedArrayBufferConstructed = 82,
kArrayPrototypeHasElements = 83,
kObjectPrototypeHasElements = 84,
kNumberFormatStyleUnit = 85,
kDateTimeFormatRange = 86,
kDateTimeFormatDateTimeStyle = 87,
kBreakIteratorTypeWord = 88,
kBreakIteratorTypeLine = 89,
kInvalidatedArrayBufferDetachingProtector = 90,
kInvalidatedArrayConstructorProtector V8_DEPRECATE_SOON(
"The ArrayConstructorProtector has been removed") = 91,
kInvalidatedArrayIteratorLookupChainProtector = 92,
kInvalidatedArraySpeciesLookupChainProtector = 93,
kInvalidatedIsConcatSpreadableLookupChainProtector = 94,
kInvalidatedMapIteratorLookupChainProtector = 95,
kInvalidatedNoElementsProtector = 96,
kInvalidatedPromiseHookProtector = 97,
kInvalidatedPromiseResolveLookupChainProtector = 98,
kInvalidatedPromiseSpeciesLookupChainProtector = 99,
kInvalidatedPromiseThenLookupChainProtector = 100,
kInvalidatedRegExpSpeciesLookupChainProtector = 101,
kInvalidatedSetIteratorLookupChainProtector = 102,
kInvalidatedStringIteratorLookupChainProtector = 103,
kInvalidatedStringLengthOverflowLookupChainProtector = 104,
kInvalidatedTypedArraySpeciesLookupChainProtector = 105,
kWasmSimdOpcodes = 106,
kVarRedeclaredCatchBinding = 107,
kWasmRefTypes = 108,
kOBSOLETE_WasmBulkMemory = 109,
kOBSOLETE_WasmMultiValue = 110,
kWasmExceptionHandling = 111,
kInvalidatedMegaDOMProtector = 112,
kFunctionPrototypeArguments = 113,
kFunctionPrototypeCaller = 114,
kTurboFanOsrCompileStarted = 115,
kAsyncStackTaggingCreateTaskCall = 116,
kDurationFormat = 117,
kInvalidatedNumberStringNotRegexpLikeProtector = 118,
kOBSOLETE_RegExpUnicodeSetIncompatibilitiesWithUnicodeMode = 119,
kOBSOLETE_ImportAssertionDeprecatedSyntax = 120,
kLocaleInfoObsoletedGetters = 121,
kLocaleInfoFunctions = 122,
kCompileHintsMagicAll = 123,
kInvalidatedNoProfilingProtector = 124,
kWasmMemory64 = 125,
kWasmMultiMemory = 126,
kWasmGC = 127,
kWasmImportedStrings = 128,
kSourceMappingUrlMagicCommentAtSign = 129,
kTemporalObject = 130,
kWasmModuleCompilation = 131,
kInvalidatedNoUndetectableObjectsProtector = 132,
kWasmJavaScriptPromiseIntegration = 133,
kWasmReturnCall = 134,
kWasmExtendedConst = 135,
kWasmRelaxedSimd = 136,
kWasmTypeReflection = 137,
kWasmExnRef = 138,
kWasmTypedFuncRef = 139,
kInvalidatedStringWrapperToPrimitiveProtector = 140,
kDocumentAllLegacyCall = 141,
kDocumentAllLegacyConstruct = 142,
kConsoleContext = 143,
kWasmImportedStringsUtf8 = 144,
kResizableArrayBuffer = 145,
kGrowableSharedArrayBuffer = 146,
kArrayByCopy = 147,
kArrayFromAsync = 148,
kIteratorMethods = 149,
kPromiseAny = 150,
kSetMethods = 151,
kArrayFindLast = 152,
kArrayGroup = 153,
kArrayBufferTransfer = 154,
kPromiseWithResolvers = 155,
kAtomicsWaitAsync = 156,
kExtendingNonExtensibleWithPrivate = 157,
kPromiseTry = 158,
kStringReplaceAll = 159,
kStringWellFormed = 160,
kWeakReferences = 161,
kErrorIsError = 162,
kInvalidatedTypedArrayLengthLookupChainProtector = 163,
kRegExpEscape = 164,
kFloat16Array = 165,
kExplicitResourceManagement = 166,
kWasmBranchHinting = 167,
kWasmMultiValue = 168,
kUint8ArrayToFromBase64AndHex = 169,
kAtomicsPause = 170,
kTopLevelAwait = 171,
kLogicalAssignment = 172,
kNullishCoalescing = 173,
kInvalidatedNoDateTimeConfigurationChangeProtector = 174,
// If you add new values here, you'll also need to update Chromium's:
// web_feature.mojom, use_counter_callback.cc, and enums.xml. V8 changes to
// this list need to be landed first, then changes on the Chromium side.
kUseCounterFeatureCount // This enum value must be last.
};
enum MessageErrorLevel {
kMessageLog = (1 << 0),
kMessageDebug = (1 << 1),
kMessageInfo = (1 << 2),
kMessageError = (1 << 3),
kMessageWarning = (1 << 4),
kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
kMessageWarning,
};
// The different priorities that an isolate can have.
enum class Priority {
// The isolate does not relate to content that is currently important
// to the user. Lowest priority.
kBestEffort,
// The isolate contributes to content that is visible to the user, like a
// visible iframe that's not interacted directly with. High priority.
kUserVisible,
// The isolate contributes to content that is of the utmost importance to
// the user, like visible content in the focused window. Highest priority.
kUserBlocking,
};
using UseCounterCallback = void (*)(Isolate* isolate,
UseCounterFeature feature);
/**
* Allocates a new isolate but does not initialize it. Does not change the
* currently entered isolate.
*
* Only Isolate::GetData() and Isolate::SetData(), which access the
* embedder-controlled parts of the isolate, as well as Isolate::GetGroup(),
* are allowed to be called on the uninitialized isolate. To initialize the
* isolate, call `Isolate::Initialize()` or initialize a `SnapshotCreator`.
*
* When an isolate is no longer used its resources should be freed
* by calling Dispose(). Using the delete operator is not allowed.
*
* V8::Initialize() must have run prior to this.
*/
static Isolate* Allocate();
static Isolate* Allocate(const IsolateGroup& group);
/**
* Return the group for this isolate.
*/
IsolateGroup GetGroup() const;
/**
* Initialize an Isolate previously allocated by Isolate::Allocate().
*/
static void Initialize(Isolate* isolate, const CreateParams& params);
/**
* Creates a new isolate. Does not change the currently entered
* isolate.
*
* When an isolate is no longer used its resources should be freed
* by calling Dispose(). Using the delete operator is not allowed.
*
* V8::Initialize() must have run prior to this.
*/
static Isolate* New(const CreateParams& params);
static Isolate* New(const IsolateGroup& group, const CreateParams& params);
/**
* Returns the entered isolate for the current thread or NULL in
* case there is no current isolate.
*
* This method must not be invoked before V8::Initialize() was invoked.
*/
static Isolate* GetCurrent();
/**
* Returns the entered isolate for the current thread or NULL in
* case there is no current isolate.
*
* No checks are performed by this method.
*/
static Isolate* TryGetCurrent();
/**
* Return true if this isolate is currently active.
**/
bool IsCurrent() const;
/**
* Clears the set of objects held strongly by the heap. This set of
* objects are originally built when a WeakRef is created or
* successfully dereferenced.
*
* This is invoked automatically after microtasks are run. See
* MicrotasksPolicy for when microtasks are run.
*
* This needs to be manually invoked only if the embedder is manually running
* microtasks via a custom MicrotaskQueue class's PerformCheckpoint. In that
* case, it is the embedder's responsibility to make this call at a time which
* does not interrupt synchronous ECMAScript code execution.
*/
void ClearKeptObjects();
/**
* Custom callback used by embedders to help V8 determine if it should abort
* when it throws and no internal handler is predicted to catch the
* exception. If --abort-on-uncaught-exception is used on the command line,
* then V8 will abort if either:
* - no custom callback is set.
* - the custom callback set returns true.
* Otherwise, the custom callback will not be called and V8 will not abort.
*/
using AbortOnUncaughtExceptionCallback = bool (*)(Isolate*);
void SetAbortOnUncaughtExceptionCallback(
AbortOnUncaughtExceptionCallback callback);
/**
* This specifies the callback called by the upcoming dynamic
* import() language feature to load modules.
*/
void SetHostImportModuleDynamicallyCallback(
HostImportModuleDynamicallyCallback callback);
/**
* This specifies the callback called by the upcoming dynamic
* import() and import.source() language feature to load modules.
*
* This API is experimental and is expected to be changed or removed in the
* future. The callback is currently only called when for source-phase
* imports. Evaluation-phase imports use the existing
* HostImportModuleDynamicallyCallback callback.
*/
void SetHostImportModuleWithPhaseDynamicallyCallback(
HostImportModuleWithPhaseDynamicallyCallback callback);
/**
* This specifies the callback called by the upcoming import.meta
* language feature to retrieve host-defined meta data for a module.
*/
void SetHostInitializeImportMetaObjectCallback(
HostInitializeImportMetaObjectCallback callback);
/**
* This specifies the callback called by the upcoming ShadowRealm
* construction language feature to retrieve host created globals.
*/
void SetHostCreateShadowRealmContextCallback(
HostCreateShadowRealmContextCallback callback);
/**
* Set the callback that checks whether a Error.isError should return true for
* a JSApiWrapper object, i.e. whether it represents a native JS error. For
* example, in an HTML embedder, DOMExceptions are considered native errors.
*/
void SetIsJSApiWrapperNativeErrorCallback(
IsJSApiWrapperNativeErrorCallback callback);
/**
* This specifies the callback called when the stack property of Error
* is accessed.
*/
void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
/**
* Get the stackTraceLimit property of Error.
*/
int GetStackTraceLimit();
#if defined(V8_OS_WIN)
/**
* This specifies the callback called when an ETW tracing session starts.
*/
V8_DEPRECATE_SOON("Use SetFilterETWSessionByURL2Callback instead")
void SetFilterETWSessionByURLCallback(FilterETWSessionByURLCallback callback);
void SetFilterETWSessionByURL2Callback(
FilterETWSessionByURL2Callback callback);
#endif // V8_OS_WIN
/**
* Optional notification that the system is running low on memory.
* V8 uses these notifications to guide heuristics.
* It is allowed to call this function from another thread while
* the isolate is executing long running JavaScript code.
*/
void MemoryPressureNotification(MemoryPressureLevel level);
/**
* Optional request from the embedder to tune v8 towards energy efficiency
* rather than speed if `battery_saver_mode_enabled` is true, because the
* embedder is in battery saver mode. If false, the correct tuning is left
* to v8 to decide.
*/
void SetBatterySaverMode(bool battery_saver_mode_enabled);
/**
* Optional request from the embedder to tune v8 towards memory efficiency
* rather than speed if `memory_saver_mode_enabled` is true, because the
* embedder is in memory saver mode. If false, the correct tuning is left
* to v8 to decide.
*/
void SetMemorySaverMode(bool memory_saver_mode_enabled);
/**
* Drop non-essential caches. Should only be called from testing code.
* The method can potentially block for a long time and does not necessarily
* trigger GC.
*/
void ClearCachesForTesting();
/**
* Methods below this point require holding a lock (using Locker) in
* a multi-threaded environment.
*/
/**
* Sets this isolate as the entered one for the current thread.
* Saves the previously entered one (if any), so that it can be
* restored when exiting. Re-entering an isolate is allowed.
*/
void Enter();
/**
* Exits this isolate by restoring the previously entered one in the
* current thread. The isolate may still stay the same, if it was
* entered more than once.
*
* Requires: this == Isolate::GetCurrent().
*/
void Exit();
/**
* Deinitializes and frees the isolate. The isolate must not be entered by any
* thread to be disposable.
*/
void Dispose();
/**
* Deinitializes the isolate, but does not free the address. The isolate must
* not be entered by any thread to be deinitializable. Embedders must call
* Isolate::Free() to free the isolate afterwards.
*/
void Deinitialize();
/**
* Frees the memory allocated for the isolate. Can only be called after the
* Isolate has already been deinitialized with Isolate::Deinitialize(). After
* the isolate is freed, the next call to Isolate::New() or
* Isolate::Allocate() might return the same address that just get freed.
*/
static void Free(Isolate* isolate);
/**
* Dumps activated low-level V8 internal stats. This can be used instead
* of performing a full isolate disposal.
*/
void DumpAndResetStats();
/**
* Discards all V8 thread-specific data for the Isolate. Should be used
* if a thread is terminating and it has used an Isolate that will outlive
* the thread -- all thread-specific data for an Isolate is discarded when
* an Isolate is disposed so this call is pointless if an Isolate is about
* to be Disposed.
*/
void DiscardThreadSpecificMetadata();
/**
* Associate embedder-specific data with the isolate. |slot| has to be
* between 0 and GetNumberOfDataSlots() - 1.
*/
V8_INLINE void SetData(uint32_t slot, void* data);
/**
* Retrieve embedder-specific data from the isolate.
* Returns NULL if SetData has never been called for the given |slot|.
*/
V8_INLINE void* GetData(uint32_t slot);
/**
* Returns the maximum number of available embedder data slots. Valid slots
* are in the range of 0 - GetNumberOfDataSlots() - 1.
*/
V8_INLINE static uint32_t GetNumberOfDataSlots();
/**
* Return data that was previously attached to the isolate snapshot via
* SnapshotCreator, and removes the reference to it.
* Repeated call with the same index returns an empty MaybeLocal.
*/
template <class T>
V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
/**
* Returns the value that was set or restored by
* SetContinuationPreservedEmbedderData(), if any.
*/
V8_DEPRECATE_SOON("Use GetContinuationPreservedEmbedderDataV2 instead")
Local<Value> GetContinuationPreservedEmbedderData();
/**
* Sets a value that will be stored on continuations and reset while the
* continuation runs.
*/
V8_DEPRECATE_SOON("Use SetContinuationPreservedEmbedderDataV2 instead")
void SetContinuationPreservedEmbedderData(Local<Value> data);
/**
* Returns the value set by `SetContinuationPreservedEmbedderDataV2()` or
* restored during microtask execution for the currently running continuation,
* if any. Returns undefiend if no continuation preserved embedder data was
* set.
*/
Local<Data> GetContinuationPreservedEmbedderDataV2();
/**
* Sets a value that will be stored on continuations and restored while the
* continuation runs. If `data` is empty, the continuation preserved embedder
* data is set to undefined.
*/
void SetContinuationPreservedEmbedderDataV2(Local<Data> data);
/**
* Get statistics about the heap memory usage.
*/
void GetHeapStatistics(HeapStatistics* heap_statistics);
/**
* Returns the number of spaces in the heap.
*/
size_t NumberOfHeapSpaces();
/**
* Get the memory usage of a space in the heap.
*
* \param space_statistics The HeapSpaceStatistics object to fill in
* statistics.
* \param index The index of the space to get statistics from, which ranges
* from 0 to NumberOfHeapSpaces() - 1.
* \returns true on success.
*/
bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
size_t index);
/**
* Returns the number of types of objects tracked in the heap at GC.
*/
size_t NumberOfTrackedHeapObjectTypes();
/**
* Get statistics about objects in the heap.
*
* \param object_statistics The HeapObjectStatistics object to fill in
* statistics of objects of given type, which were live in the previous GC.
* \param type_index The index of the type of object to fill details about,
* which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
* \returns true on success.
*/
bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
size_t type_index);
/**
* Get statistics about code and its metadata in the heap.
*
* \param object_statistics The HeapCodeStatistics object to fill in
* statistics of code, bytecode and their metadata.
* \returns true on success.
*/
bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
/**
* This API is experimental and may change significantly.
*
* Enqueues a memory measurement request and invokes the delegate with the
* results.
*
* \param delegate the delegate that defines which contexts to measure and
* reports the results.
*
* \param execution promptness executing the memory measurement.
* The kEager value is expected to be used only in tests.
*/
bool MeasureMemory(
std::unique_ptr<MeasureMemoryDelegate> delegate,
MeasureMemoryExecution execution = MeasureMemoryExecution::kDefault);
/**
* Get a call stack sample from the isolate.
* \param state Execution state.
* \param frames Caller allocated buffer to store stack frames.
* \param frames_limit Maximum number of frames to capture. The buffer must
* be large enough to hold the number of frames.
* \param sample_info The sample info is filled up by the function
* provides number of actual captured stack frames and
* the current VM state.
* \note GetStackSample should only be called when the JS thread is paused or
* interrupted. Otherwise the behavior is undefined.
*/
void GetStackSample(const RegisterState& state, void** frames,
size_t frames_limit, SampleInfo* sample_info);
/**
* Adjusts the amount of registered external memory.
*
* \param change_in_bytes the change in externally allocated memory that is
* kept alive by JavaScript objects.
* \returns the adjusted value.
*/
V8_DEPRECATE_SOON("Use ExternalMemoryAccounter instead.")
int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
/**
* Returns heap profiler for this isolate. Will return NULL until the isolate
* is initialized.
*/
HeapProfiler* GetHeapProfiler();
/**
* Tells the VM whether the embedder is idle or not.
*/
void SetIdle(bool is_idle);
/** Returns the ArrayBuffer::Allocator used in this isolate. */
ArrayBuffer::Allocator* GetArrayBufferAllocator();
/** Returns true if this isolate has a current context. */
bool InContext();
/**
* Returns the context of the currently running JavaScript, or the context
* on the top of the stack if no JavaScript is running.
*/
Local<Context> GetCurrentContext();
/**
* Returns either the last context entered through V8's C++ API, or the
* context of the currently running microtask while processing microtasks.
* If a context is entered while executing a microtask, that context is
* returned.
*/
Local<Context> GetEnteredOrMicrotaskContext();
/**
* Returns the Context that corresponds to the Incumbent realm in HTML spec.
* https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
*/
Local<Context> GetIncumbentContext();
/**
* Returns the host defined options set for currently running script or
* module, if available.
*/
MaybeLocal<Data> GetCurrentHostDefinedOptions();
/**
* Schedules a v8::Exception::Error with the given message.
* See ThrowException for more details. Templatized to provide compile-time
* errors in case of too long strings (see v8::String::NewFromUtf8Literal).
*/
template <int N>
Local<Value> ThrowError(const char (&message)[N]) {
return ThrowError(String::NewFromUtf8Literal(this, message));
}
Local<Value> ThrowError(Local<String> message);
/**
* Schedules an exception to be thrown when returning to JavaScript. When an
* exception has been scheduled it is illegal to invoke any JavaScript
* operation; the caller must return immediately and only after the exception
* has been handled does it become legal to invoke JavaScript operations.
*/
Local<Value> ThrowException(Local<Value> exception);
/**
* Returns true if an exception was thrown but not processed yet by an
* exception handler on JavaScript side or by v8::TryCatch handler.
*
* This is an experimental feature and may still change significantly.
*/
bool HasPendingException();
using GCCallback = void (*)(Isolate* isolate, GCType type,
GCCallbackFlags flags);
using GCCallbackWithData = void (*)(Isolate* isolate, GCType type,
GCCallbackFlags flags, void* data);
/**
* Enables the host application to receive a notification before a
* garbage collection.
*
* \param callback The callback to be invoked. The callback is allowed to
* allocate but invocation is not re-entrant: a callback triggering
* garbage collection will not be called again. JS execution is prohibited
* from these callbacks. A single callback may only be registered once.
* \param gc_type_filter A filter in case it should be applied.
*/
void AddGCPrologueCallback(GCCallback callback,
GCType gc_type_filter = kGCTypeAll);
/**
* \copydoc AddGCPrologueCallback(GCCallback, GCType)
*
* \param data Additional data that should be passed to the callback.
*/
void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
GCType gc_type_filter = kGCTypeAll);
/**
* This function removes a callback which was added by
* `AddGCPrologueCallback`.
*
* \param callback the callback to remove.
*/
void RemoveGCPrologueCallback(GCCallback callback);
/**
* \copydoc AddGCPrologueCallback(GCCallback)
*
* \param data Additional data that was used to install the callback.
*/
void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
/**
* Enables the host application to receive a notification after a
* garbage collection.
*
* \copydetails AddGCPrologueCallback(GCCallback, GCType)
*/
void AddGCEpilogueCallback(GCCallback callback,
GCType gc_type_filter = kGCTypeAll);
/**
* \copydoc AddGCEpilogueCallback(GCCallback, GCType)
*
* \param data Additional data that should be passed to the callback.
*/
void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
GCType gc_type_filter = kGCTypeAll);
/**
* This function removes a callback which was added by
* `AddGCEpilogueCallback`.
*
* \param callback the callback to remove.
*/
void RemoveGCEpilogueCallback(GCCallback callback);
/**
* \copydoc RemoveGCEpilogueCallback(GCCallback)
*
* \param data Additional data that was used to install the callback.
*/
void RemoveGCEpilogueCallback(GCCallbackWithData callback,
void* data = nullptr);
/**
* Sets an embedder roots handle that V8 should consider when performing
* non-unified heap garbage collections. The intended use case is for setting
* a custom handler after invoking `AttachCppHeap()`.
*
* V8 does not take ownership of the handler.
*/
void SetEmbedderRootsHandler(EmbedderRootsHandler* handler);
using ReleaseCppHeapCallback = void (*)(std::unique_ptr<CppHeap>);
/**
* Sets a callback on the isolate that gets called when the CppHeap gets
* detached. The callback can then either take ownership of the CppHeap, or
* the CppHeap gets deallocated.
*/
void SetReleaseCppHeapCallbackForTesting(ReleaseCppHeapCallback callback);
/**
* \returns the C++ heap managed by V8. Only available if such a heap has been
* attached using `AttachCppHeap()`.
*/
CppHeap* GetCppHeap() const;
using GetExternallyAllocatedMemoryInBytesCallback = size_t (*)();
/**
* Set the callback that tells V8 how much memory is currently allocated
* externally of the V8 heap. Ideally this memory is somehow connected to V8
* objects and may get freed-up when the corresponding V8 objects get
* collected by a V8 garbage collection.
*/
void SetGetExternallyAllocatedMemoryInBytesCallback(
GetExternallyAllocatedMemoryInBytesCallback callback);
/**
* Forcefully terminate the current thread of JavaScript execution
* in the given isolate.
*
* This method can be used by any thread even if that thread has not
* acquired the V8 lock with a Locker object.
*/
void TerminateExecution();
/**
* Is V8 terminating JavaScript execution.
*
* Returns true if JavaScript execution is currently terminating
* because of a call to TerminateExecution. In that case there are
* still JavaScript frames on the stack and the termination
* exception is still active.
*/
bool IsExecutionTerminating();
/**
* Resume execution capability in the given isolate, whose execution
* was previously forcefully terminated using TerminateExecution().
*
* When execution is forcefully terminated using TerminateExecution(),
* the isolate can not resume execution until all JavaScript frames
* have propagated the uncatchable exception which is generated. This
* method allows the program embedding the engine to handle the
* termination event and resume execution capability, even if
* JavaScript frames remain on the stack.
*
* This method can be used by any thread even if that thread has not
* acquired the V8 lock with a Locker object.
*/
void CancelTerminateExecution();
/**
* Request V8 to interrupt long running JavaScript code and invoke
* the given |callback| passing the given |data| to it. After |callback|
* returns control will be returned to the JavaScript code.
* There may be a number of interrupt requests in flight.
* Can be called from another thread without acquiring a |Locker|.
* Registered |callback| must not reenter interrupted Isolate.
*/
void RequestInterrupt(InterruptCallback callback, void* data);
/**
* Returns true if there is ongoing background work within V8 that will
* eventually post a foreground task, like asynchronous WebAssembly
* compilation.
*/
bool HasPendingBackgroundTasks();
/**
* Request garbage collection in this Isolate. It is only valid to call this
* function if --expose_gc was specified.
*
* This should only be used for testing purposes and not to enforce a garbage
* collection schedule. It has strong negative impact on the garbage
* collection performance. Use MemoryPressureNotification() instead to
* influence the garbage collection schedule.
*/
void RequestGarbageCollectionForTesting(GarbageCollectionType type);
/**
* Request garbage collection with a specific embedderstack state in this
* Isolate. It is only valid to call this function if --expose_gc was
* specified.
*
* This should only be used for testing purposes and not to enforce a garbage
* collection schedule. It has strong negative impact on the garbage
* collection performance. Use MemoryPressureNotification() instead to
* influence the garbage collection schedule.
*/
void RequestGarbageCollectionForTesting(GarbageCollectionType type,
StackState stack_state);
/**
* Set the callback to invoke for logging event.
*/
void SetEventLogger(LogEventCallback that);
/**
* Adds a callback to notify the host application right before a script
* is about to run. If a script re-enters the runtime during executing, the
* BeforeCallEnteredCallback is invoked for each re-entrance.
* Executing scripts inside the callback will re-trigger the callback.
*/
void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
/**
* Removes callback that was installed by AddBeforeCallEnteredCallback.
*/
void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
/**
* Adds a callback to notify the host application when a script finished
* running. If a script re-enters the runtime during executing, the
* CallCompletedCallback is only invoked when the outer-most script
* execution ends. Executing scripts inside the callback do not trigger
* further callbacks.
*/
void AddCallCompletedCallback(CallCompletedCallback callback);
/**
* Removes callback that was installed by AddCallCompletedCallback.
*/
void RemoveCallCompletedCallback(CallCompletedCallback callback);
/**
* Set the PromiseHook callback for various promise lifecycle
* events.
*/
void SetPromiseHook(PromiseHook hook);
/**
* Set callback to notify about promise reject with no handler, or
* revocation of such a previous notification once the handler is added.
*/
void SetPromiseRejectCallback(PromiseRejectCallback callback);
/**
* This is a part of experimental Api and might be changed without further
* notice.
* Do not use it.
*
* Set callback to notify about a new exception being thrown.
*/
void SetExceptionPropagationCallback(ExceptionPropagationCallback callback);
/**
* Runs the default MicrotaskQueue until it gets empty and perform other
* microtask checkpoint steps, such as calling ClearKeptObjects. Asserts that
* the MicrotasksPolicy is not kScoped. Any exceptions thrown by microtask
* callbacks are swallowed.
*/
void PerformMicrotaskCheckpoint();
/**
* Enqueues the callback to the default MicrotaskQueue
*/
void EnqueueMicrotask(Local<Function> microtask);
/**
* Enqueues the callback to the default MicrotaskQueue
*/
void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
/**
* Controls how Microtasks are invoked. See MicrotasksPolicy for details.
*/
void SetMicrotasksPolicy(MicrotasksPolicy policy);
/**
* Returns the policy controlling how Microtasks are invoked.
*/
MicrotasksPolicy GetMicrotasksPolicy() const;
/**
* Adds a callback to notify the host application after
* microtasks were run on the default MicrotaskQueue. The callback is
* triggered by explicit RunMicrotasks call or automatic microtasks execution
* (see SetMicrotaskPolicy).
*
* Callback will trigger even if microtasks were attempted to run,
* but the microtasks queue was empty and no single microtask was actually
* executed.
*
* Executing scripts inside the callback will not re-trigger microtasks and
* the callback.
*/
void AddMicrotasksCompletedCallback(
MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
/**
* Removes callback that was installed by AddMicrotasksCompletedCallback.
*/
void RemoveMicrotasksCompletedCallback(
MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
/**
* Sets a callback for counting the number of times a feature of V8 is used.
*/
void SetUseCounterCallback(UseCounterCallback callback);
/**
* Enables the host application to provide a mechanism for recording
* statistics counters.
*/
void SetCounterFunction(CounterLookupCallback);
/**
* Enables the host application to provide a mechanism for recording
* histograms. The CreateHistogram function returns a
* histogram which will later be passed to the AddHistogramSample
* function.
*/
void SetCreateHistogramFunction(CreateHistogramCallback);
void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
/**
* Enables the host application to provide a mechanism for recording
* event based metrics. In order to use this interface
* include/v8-metrics.h
* needs to be included and the recorder needs to be derived from the
* Recorder base class defined there.
* This method can only be called once per isolate and must happen during
* isolate initialization before background threads are spawned.
*/
void SetMetricsRecorder(
const std::shared_ptr<metrics::Recorder>& metrics_recorder);
/**
* Enables the host application to provide a mechanism for recording a
* predefined set of data as crash keys to be used in postmortem debugging in
* case of a crash.
*/
void SetAddCrashKeyCallback(AddCrashKeyCallback);
/**
* Optional notification that the system is running low on memory.
* V8 uses these notifications to attempt to free memory.
*/
void LowMemoryNotification();
/**
* Optional notification that a context has been disposed. V8 uses these
* notifications to guide the GC heuristic and cancel FinalizationRegistry
* cleanup tasks. Returns the number of context disposals - including this one
* - since the last time V8 had a chance to clean up.
*
* The optional parameter |dependant_context| specifies whether the disposed
* context was depending on state from other contexts or not.
*/
V8_DEPRECATE_SOON("Use version that passes ContextDependants.")
int ContextDisposedNotification(bool dependant_context = true);
/**
* Optional notification that a context has been disposed. V8 uses these
* notifications to guide heuristics on e.g. GC or compilers.
*
* \param dependants A signal on whether this context possibly had any
* dependants.
*/
void ContextDisposedNotification(ContextDependants dependants);
/**
* Optional notification that the isolate switched to the foreground.
* V8 uses these notifications to guide heuristics.
*/
V8_DEPRECATE_SOON("Use SetPriority(Priority::kUserBlocking) instead")
void IsolateInForegroundNotification();
/**
* Optional notification that the isolate switched to the background.
* V8 uses these notifications to guide heuristics.
*/
V8_DEPRECATE_SOON("Use SetPriority(Priority::kBestEffort) instead")
void IsolateInBackgroundNotification();
/**
* Optional notification that the isolate changed `priority`.
* V8 uses the priority value to guide heuristics.
*/
void SetPriority(Priority priority);
/**
* Optional notification to tell V8 whether the embedder is currently loading
* resources. If the embedder uses this notification, it should call
* SetIsLoading(true) when loading starts and SetIsLoading(false) when it
* ends.
* It's valid to call SetIsLoading(true) again while loading, which will
* update the timestamp when V8 considers the load started. Calling
* SetIsLoading(false) while not loading does nothing.
* V8 uses these notifications to guide heuristics.
* This is an unfinished experimental feature. Semantics and implementation
* may change frequently.
*/
void SetIsLoading(bool is_loading);
/**
* Optional notification to tell V8 whether the embedder is currently frozen.
* V8 uses these notifications to guide heuristics.
* This is an unfinished experimental feature. Semantics and implementation
* may change frequently.
*/
void Freeze(bool is_frozen);
/**
* Optional notification to tell V8 the current isolate is used for debugging
* and requires higher heap limit.
*/
void IncreaseHeapLimitForDebugging();
/**
* Restores the original heap limit after IncreaseHeapLimitForDebugging().
*/
void RestoreOriginalHeapLimit();
/**
* Returns true if the heap limit was increased for debugging and the
* original heap limit was not restored yet.
*/
bool IsHeapLimitIncreasedForDebugging();
/**
* Allows the host application to provide the address of a function that is
* notified each time code is added, moved or removed.
*
* \param options options for the JIT code event handler.
* \param event_handler the JIT code event handler, which will be invoked
* each time code is added, moved or removed.
* \note \p event_handler won't get notified of existent code.
* \note since code removal notifications are not currently issued, the
* \p event_handler may get notifications of code that overlaps earlier
* code notifications. This happens when code areas are reused, and the
* earlier overlapping code areas should therefore be discarded.
* \note the events passed to \p event_handler and the strings they point to
* are not guaranteed to live past each call. The \p event_handler must
* copy strings and other parameters it needs to keep around.
* \note the set of events declared in JitCodeEvent::EventType is expected to
* grow over time, and the JitCodeEvent structure is expected to accrue
* new members. The \p event_handler function must ignore event codes
* it does not recognize to maintain future compatibility.
* \note Use Isolate::CreateParams to get events for code executed during
* Isolate setup.
*/
void SetJitCodeEventHandler(JitCodeEventOptions options,
JitCodeEventHandler event_handler);
/**
* Modifies the stack limit for this Isolate.
*
* \param stack_limit An address beyond which the Vm's stack may not grow.
*
* \note If you are using threads then you should hold the V8::Locker lock
* while setting the stack limit and you must set a non-default stack
* limit separately for each thread.
*/
void SetStackLimit(uintptr_t stack_limit);
/**
* Returns a memory range that can potentially contain jitted code. Code for
* V8's 'builtins' will not be in this range if embedded builtins is enabled.
*
* On Win64, embedders are advised to install function table callbacks for
* these ranges, as default SEH won't be able to unwind through jitted code.
* The first page of the code range is reserved for the embedder and is
* committed, writable, and executable, to be used to store unwind data, as
* documented in
* https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64.
*
* Might be empty on other platforms.
*
* https://code.google.com/p/v8/issues/detail?id=3598
*/
void GetCodeRange(void** start, size_t* length_in_bytes);
/**
* As GetCodeRange, but for embedded builtins (these live in a distinct
* memory region from other V8 Code objects).
*/
void GetEmbeddedCodeRange(const void** start, size_t* length_in_bytes);
/**
* Returns the JSEntryStubs necessary for use with the Unwinder API.
*/
JSEntryStubs GetJSEntryStubs();
static constexpr size_t kMinCodePagesBufferSize = 32;
/**
* Copies the code heap pages currently in use by V8 into |code_pages_out|.
* |code_pages_out| must have at least kMinCodePagesBufferSize capacity and
* must be empty.
*
* Signal-safe, does not allocate, does not access the V8 heap.
* No code on the stack can rely on pages that might be missing.
*
* Returns the number of pages available to be copied, which might be greater
* than |capacity|. In this case, only |capacity| pages will be copied into
* |code_pages_out|. The caller should provide a bigger buffer on the next
* call in order to get all available code pages, but this is not required.
*/
size_t CopyCodePages(size_t capacity, MemoryRange* code_pages_out);
/** Set the callback to invoke in case of fatal errors. */
void SetFatalErrorHandler(FatalErrorCallback that);
/** Set the callback to invoke in case of OOM errors. */
void SetOOMErrorHandler(OOMErrorCallback that);
/**
* Add a callback to invoke in case the heap size is close to the heap limit.
* If multiple callbacks are added, only the most recently added callback is
* invoked.
*/
void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
/**
* Remove the given callback and restore the heap limit to the
* given limit. If the given limit is zero, then it is ignored.
* If the current heap size is greater than the given limit,
* then the heap limit is restored to the minimal limit that
* is possible for the current heap size.
*/
void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
size_t heap_limit);
/**
* If the heap limit was changed by the NearHeapLimitCallback, then the
* initial heap limit will be restored once the heap size falls below the
* given threshold percentage of the initial heap limit.
* The threshold percentage is a number in (0.0, 1.0) range.
*/
void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5);
/**
* Set the callback to invoke to check if code generation from
* strings should be allowed.
*/
void SetModifyCodeGenerationFromStringsCallback(
ModifyCodeGenerationFromStringsCallback2 callback);
/**
* Set the callback to invoke to check if wasm code generation should
* be allowed.
*/
void SetAllowWasmCodeGenerationCallback(
AllowWasmCodeGenerationCallback callback);
/**
* Embedder over{ride|load} injection points for wasm APIs. The expectation
* is that the embedder sets them at most once.
*/
void SetWasmModuleCallback(ExtensionCallback callback);
void SetWasmInstanceCallback(ExtensionCallback callback);
void SetWasmStreamingCallback(WasmStreamingCallback callback);
void SetWasmAsyncResolvePromiseCallback(
WasmAsyncResolvePromiseCallback callback);
void SetWasmLoadSourceMapCallback(WasmLoadSourceMapCallback callback);
void SetWasmImportedStringsEnabledCallback(
WasmImportedStringsEnabledCallback callback);
void SetSharedArrayBufferConstructorEnabledCallback(
SharedArrayBufferConstructorEnabledCallback callback);
void SetWasmJSPIEnabledCallback(WasmJSPIEnabledCallback callback);
/**
* This function can be called by the embedder to signal V8 that the dynamic
* enabling of features has finished. V8 can now set up dynamically added
* features.
*/
void InstallConditionalFeatures(Local<Context> context);
/**
* Check if V8 is dead and therefore unusable. This is the case after
* fatal errors such as out-of-memory situations.
*/
bool IsDead();
/**
* Adds a message listener (errors only).
*
* The same message listener can be added more than once and in that
* case it will be called more than once for each message.
*
* If data is specified, it will be passed to the callback when it is called.
* Otherwise, the exception object will be passed to the callback instead.
*/
bool AddMessageListener(MessageCallback callback,
Local<Value> data = Local<Value>());
/**
* Adds a message listener.
*
* The same message listener can be added more than once and in that
* case it will be called more than once for each message.
*
* If data is specified, it will be passed to the callback when it is called.
* Otherwise, the exception object will be passed to the callback instead.
*
* A listener can listen for particular error levels by providing a mask.
*/
bool AddMessageListenerWithErrorLevel(MessageCallback callback,
int message_levels,
Local<Value> data = Local<Value>());
/**
* Remove all message listeners from the specified callback function.
*/
void RemoveMessageListeners(MessageCallback callback);
/** Callback function for reporting failed access checks.*/
void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
/**
* Tells V8 to capture current stack trace when uncaught exception occurs
* and report it to the message listeners. The option is off by default.
*/
void SetCaptureStackTraceForUncaughtExceptions(
bool capture, int frame_limit = 10,
StackTrace::StackTraceOptions options = StackTrace::kOverview);
/**
* Check if this isolate is in use.
* True if at least one thread Enter'ed this isolate.
*/
bool IsInUse();
/**
* Set whether calling Atomics.wait (a function that may block) is allowed in
* this isolate. This can also be configured via
* CreateParams::allow_atomics_wait.
*/
void SetAllowAtomicsWait(bool allow);
/**
* Time zone redetection indicator for
* DateTimeConfigurationChangeNotification.
*
* kSkip indicates V8 that the notification should not trigger redetecting
* host time zone. kRedetect indicates V8 that host time zone should be
* redetected, and used to set the default time zone.
*
* The host time zone detection may require file system access or similar
* operations unlikely to be available inside a sandbox. If v8 is run inside a
* sandbox, the host time zone has to be detected outside the sandbox before
* calling DateTimeConfigurationChangeNotification function.
*/
enum class TimeZoneDetection { kSkip, kRedetect };
/**
* Notification that the embedder has changed the time zone, daylight savings
* time or other date / time configuration parameters. V8 keeps a cache of
* various values used for date / time computation. This notification will
* reset those cached values for the current context so that date / time
* configuration changes would be reflected.
*
* This API should not be called more than needed as it will negatively impact
* the performance of date operations.
*/
void DateTimeConfigurationChangeNotification(
TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip);
/**
* Notification that the embedder has changed the locale. V8 keeps a cache of
* various values used for locale computation. This notification will reset
* those cached values for the current context so that locale configuration
* changes would be reflected.
*
* This API should not be called more than needed as it will negatively impact
* the performance of locale operations.
*/
void LocaleConfigurationChangeNotification();
/**
* Returns the default locale in a string if Intl support is enabled.
* Otherwise returns an empty string.
*/
std::string GetDefaultLocale();
/**
* Returns a canonical and case-regularized form of locale if Intl support is
* enabled. If the locale is not syntactically well-formed, throws a
* RangeError.
*
* If Intl support is not enabled, returns Nothing<std::string>().
*
* Corresponds to the combination of the abstract operations
* IsStructurallyValidLanguageTag and CanonicalizeUnicodeLocaleId. See:
* https://tc39.es/ecma402/#sec-isstructurallyvalidlanguagetag
* https://tc39.es/ecma402/#sec-canonicalizeunicodelocaleid
*/
V8_WARN_UNUSED_RESULT Maybe<std::string>
ValidateAndCanonicalizeUnicodeLocaleId(std::string_view locale);
/**
* Returns the hash seed for that isolate, for testing purposes.
*/
uint64_t GetHashSeed();
Isolate() = delete;
~Isolate() = delete;
Isolate(const Isolate&) = delete;
Isolate& operator=(const Isolate&) = delete;
// Deleting operator new and delete here is allowed as ctor and dtor is also
// deleted.
void* operator new(size_t size) = delete;
void* operator new[](size_t size) = delete;
void operator delete(void*, size_t) = delete;
void operator delete[](void*, size_t) = delete;
private:
template <class K, class V, class Traits>
friend class PersistentValueMapBase;
friend class ExternalMemoryAccounter;
internal::ValueHelper::InternalRepresentationType GetDataFromSnapshotOnce(
size_t index);
int64_t AdjustAmountOfExternalAllocatedMemoryImpl(int64_t change_in_bytes);
void HandleExternalMemoryInterrupt();
};
void Isolate::SetData(uint32_t slot, void* data) {
using I = internal::Internals;
I::SetEmbedderData(this, slot, data);
}
void* Isolate::GetData(uint32_t slot) {
using I = internal::Internals;
return I::GetEmbedderData(this, slot);
}
uint32_t Isolate::GetNumberOfDataSlots() {
using I = internal::Internals;
return I::kNumIsolateDataSlots;
}
template <class T>
MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
if (auto repr = GetDataFromSnapshotOnce(index);
repr != internal::ValueHelper::kEmpty) {
internal::PerformCastCheck(internal::ValueHelper::ReprAsValue<T>(repr));
return Local<T>::FromRepr(repr);
}
return {};
}
} // namespace v8
#endif // INCLUDE_V8_ISOLATE_H_
|