deps: update V8 to 7.5.288.22

Backport-PR-URL: https://github.com/nodejs/node/pull/28005
PR-URL: https://github.com/nodejs/node/pull/27375
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Ujjwal Sharma <usharma1998@gmail.com>
Reviewed-By: Refael Ackermann <refack@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
Refael Ackermann authored and Michaël Zasso committed 2019-06-04 18:44:21 +02:00
1 parent fee23beec2
commit 86a8bb7612
1302 files changed
+53473 -26769

No files matched your search

+2
View File
@@ -140,6 +140,7 @@ Peter Rybin <peter.rybin@gmail.com>
Peter Varga <pvarga@inf.u-szeged.hu>
Peter Wong <peter.wm.wong@gmail.com>
Paul Lind <plind44@gmail.com>
Pavel Medvedev <pmedvedev@gmail.com>
PhistucK <phistuck@gmail.com>
Qingyan Li <qingyan.liqy@alibaba-inc.com>
Qiuyi Zhang <qiuyi.zqy@alibaba-inc.com>
@@ -158,6 +159,7 @@ Sander Mathijs van Veen <sander@leaningtech.com>
Sandro Santilli <strk@keybit.net>
Sanjoy Das <sanjoy@playingwithpointers.com>
Seo Sanghyeon <sanxiyn@gmail.com>
Shawn Anastasio <shawnanastasio@gmail.com>
Stefan Penner <stefan.penner@gmail.com>
Sylvestre Ledru <sledru@mozilla.com>
Taketoshi Aono <brn@b6n.ch>
+772 -304
View File
File diff suppressed because it is too large. Load diff
+1505
View File
File diff suppressed because it is too large. Load diff
+142 -52
View File
@@ -5,46 +5,160 @@
vars = {
'checkout_instrumented_libraries': False,
'chromium_url': 'https://chromium.googlesource.com',
'android_url': 'https://android.googlesource.com',
'download_gcmole': False,
'download_jsfunfuzz': False,
'download_mips_toolchain': False,
'check_v8_header_includes': False,
# GN CIPD package version.
'gn_version': 'git_revision:64b846c96daeb3eaf08e26d8a84d8451c6cb712b',
# luci-go CIPD package version.
'luci_go': 'git_revision:25958d48e89e980e2a97daeddc977fb5e2e1fb8c',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_build-tools_version
# and whatever else without interference from each other.
'android_sdk_build-tools_version': 'DLK621q5_Bga5EsOr7cp6bHWWxFKx6UHLu_Ix_m3AckC',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_emulator_version
# and whatever else without interference from each other.
'android_sdk_emulator_version': 'ki7EDQRAiZAUYlnTWR1XmI6cJTk65fJ-DNZUU1zrtS8C',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_extras_version
# and whatever else without interference from each other.
'android_sdk_extras_version': 'iIwhhDox5E-mHgwUhCz8JACWQCpUjdqt5KTY9VLugKQC',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_patcher_version
# and whatever else without interference from each other.
'android_sdk_patcher_version': 'I6FNMhrXlpB-E1lOhMlvld7xt9lBVNOO83KIluXDyA0C',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_platform-tools_version
# and whatever else without interference from each other.
'android_sdk_platform-tools_version': '4Y2Cb2LGzoc-qt-oIUIlhySotJaKeE3ELFedSVe6Uk8C',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_platforms_version
# and whatever else without interference from each other.
'android_sdk_platforms_version': 'Kg2t9p0YnQk8bldUv4VA3o156uPXLUfIFAmVZ-Gm5ewC',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_sources_version
# and whatever else without interference from each other.
'android_sdk_sources_version': 'K9uEn3JvNELEVjjVK_GQD3ZQD3rqAnJSxCWxjmUmRkgC',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_tools_version
# and whatever else without interference from each other.
'android_sdk_tools_version': 'wYcRQC2WHsw2dKWs4EA7fw9Qsyzu1ds1_fRjKmGxe5QC',
# Three lines of non-changing comments so that
# the commit queue can handle CLs rolling android_sdk_tools-lint_version
# and whatever else without interference from each other.
'android_sdk_tools-lint_version': '89hXqZYzCum3delB5RV7J_QyWkaRodqdtQS0s3LMh3wC',
}
deps = {
'v8/build':
Var('chromium_url') + '/chromium/src/build.git' + '@' + '80892bfe019dc854c6acdbfbb7304cca63986d4f',
Var('chromium_url') + '/chromium/src/build.git' + '@' + 'a0b2e3b2708bcf81ec00ac1738b586bcc5e04eea',
'v8/third_party/depot_tools':
Var('chromium_url') + '/chromium/tools/depot_tools.git' + '@' + 'cf661acb705fccc302901a1f8a251ad43ce2dd62',
Var('chromium_url') + '/chromium/tools/depot_tools.git' + '@' + '7e7523be4e21b0841ae815ef37521a5476f68549',
'v8/third_party/icu':
Var('chromium_url') + '/chromium/deps/icu.git' + '@' + '8c67416ccb4da42d817e7081ff83a2193b1aabe7',
Var('chromium_url') + '/chromium/deps/icu.git' + '@' + '35f7e139f33f1ddbfdb68b65dda29aff430c3f6f',
'v8/third_party/instrumented_libraries':
Var('chromium_url') + '/chromium/src/third_party/instrumented_libraries.git' + '@' + 'a959e4f0cb643003f2d75d179cede449979e3e77',
'v8/buildtools':
Var('chromium_url') + '/chromium/src/buildtools.git' + '@' + '3e50219fc4503f461b2176a9976891b28d80f9ab',
Var('chromium_url') + '/chromium/src/buildtools.git' + '@' + 'd5c58b84d50d256968271db459cd29b22bff1ba2',
'v8/buildtools/clang_format/script':
Var('chromium_url') + '/chromium/llvm-project/cfe/tools/clang-format.git' + '@' + '96636aa0e9f047f17447f2d45a094d0b59ed7917',
'v8/buildtools/linux64': {
'packages': [
{
'package': 'gn/gn/linux-amd64',
'version': Var('gn_version'),
}
],
'dep_type': 'cipd',
'condition': 'host_os == "linux"',
},
'v8/buildtools/mac': {
'packages': [
{
'package': 'gn/gn/mac-amd64',
'version': Var('gn_version'),
}
],
'dep_type': 'cipd',
'condition': 'host_os == "mac"',
},
'v8/buildtools/third_party/libc++/trunk':
Var('chromium_url') + '/chromium/llvm-project/libcxx.git' + '@' + '22d3f6dd25e5efc59124ba1c00b8f98b14be4201',
Var('chromium_url') + '/chromium/llvm-project/libcxx.git' + '@' + '9b96c3dbd4e89c10d9fd8364da4b65f93c6f4276',
'v8/buildtools/third_party/libc++abi/trunk':
Var('chromium_url') + '/chromium/llvm-project/libcxxabi.git' + '@' + '0d529660e32d77d9111912d73f2c74fc5fa2a858',
'v8/buildtools/third_party/libunwind/trunk':
Var('chromium_url') + '/external/llvm.org/libunwind.git' + '@' + '69d9b84cca8354117b9fe9705a4430d789ee599b',
'v8/buildtools/win': {
'packages': [
{
'package': 'gn/gn/windows-amd64',
'version': Var('gn_version'),
}
],
'dep_type': 'cipd',
'condition': 'host_os == "win"',
},
'v8/base/trace_event/common':
Var('chromium_url') + '/chromium/src/base/trace_event/common.git' + '@' + '936ba8a963284a6b3737cf2f0474a7131073abee',
Var('chromium_url') + '/chromium/src/base/trace_event/common.git' + '@' + 'ebb658ab38d1b23183458ed0430f5b11853a25a3',
'v8/third_party/android_ndk': {
'url': Var('chromium_url') + '/android_ndk.git' + '@' + '4e2cea441bfd43f0863d14f57b1e1844260b9884',
'condition': 'checkout_android',
},
# This is deprecated.
'v8/third_party/android_tools': {
'url': Var('chromium_url') + '/android_tools.git' + '@' + '347a7c8078a009e98995985b7ab6ec6b35696dea',
'condition': 'checkout_android',
},
'v8/third_party/android_sdk/public': {
'packages': [
{
'package': 'chromium/third_party/android_sdk/public/build-tools',
'version': Var('android_sdk_build-tools_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/emulator',
'version': Var('android_sdk_emulator_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/extras',
'version': Var('android_sdk_extras_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/patcher',
'version': Var('android_sdk_patcher_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/platform-tools',
'version': Var('android_sdk_platform-tools_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/platforms',
'version': Var('android_sdk_platforms_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/sources',
'version': Var('android_sdk_sources_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/tools',
'version': Var('android_sdk_tools_version'),
},
{
'package': 'chromium/third_party/android_sdk/public/tools-lint',
'version': Var('android_sdk_tools-lint_version'),
},
],
'condition': 'checkout_android',
'dep_type': 'cipd',
},
'v8/third_party/catapult': {
'url': Var('chromium_url') + '/catapult.git' + '@' + 'ccc29087522abefc852d1294595ae6db7e86d649',
'url': Var('chromium_url') + '/catapult.git' + '@' + 'acbf095c15e9524a0a1116792c3b6698f8e9b85b',
'condition': 'checkout_android',
},
'v8/third_party/colorama/src': {
@@ -52,25 +166,25 @@ deps = {
'condition': 'checkout_android',
},
'v8/third_party/fuchsia-sdk': {
'url': Var('chromium_url') + '/chromium/src/third_party/fuchsia-sdk.git' + '@' + '8e8db13b538ecb251e5ce9d5c781fc142f9752fd',
'url': Var('chromium_url') + '/chromium/src/third_party/fuchsia-sdk.git' + '@' + 'a42c2f604f3ae23099e73605df7864988d289d98',
'condition': 'checkout_fuchsia',
},
'v8/third_party/googletest/src':
Var('chromium_url') + '/external/github.com/google/googletest.git' + '@' + 'efecb0bfa687cf87836494f5d62868485c00fb66',
Var('chromium_url') + '/external/github.com/google/googletest.git' + '@' + 'b617b277186e03b1065ac6d43912b1c4147c2982',
'v8/third_party/jinja2':
Var('chromium_url') + '/chromium/src/third_party/jinja2.git' + '@' + 'b41863e42637544c2941b574c7877d3e1f663e25',
'v8/third_party/markupsafe':
Var('chromium_url') + '/chromium/src/third_party/markupsafe.git' + '@' + '8f45f5cfa0009d2a70589bcda0349b8cb2b72783',
'v8/tools/swarming_client':
Var('chromium_url') + '/infra/luci/client-py.git' + '@' + '7a61cf37d6a0163f0ec02d495289a1d038e62457',
Var('chromium_url') + '/infra/luci/client-py.git' + '@' + 'aa60736aded9fc32a0e21a81f5fc51f6009d01f3',
'v8/test/benchmarks/data':
Var('chromium_url') + '/v8/deps/third_party/benchmarks.git' + '@' + '05d7188267b4560491ff9155c5ee13e207ecd65f',
'v8/test/mozilla/data':
Var('chromium_url') + '/v8/deps/third_party/mozilla-tests.git' + '@' + 'f6c578a10ea707b1a8ab0b88943fe5115ce2b9be',
'v8/test/test262/data':
Var('chromium_url') + '/external/github.com/tc39/test262.git' + '@' + '565d7d5b7dd808d9267006b83ac4ea9c48f782cc',
Var('chromium_url') + '/external/github.com/tc39/test262.git' + '@' + '8e5ab69e8c31135265cba570d54d41f6ade19e45',
'v8/test/test262/harness':
Var('chromium_url') + '/external/github.com/test262-utils/test262-harness-py.git' + '@' + '0f2acdd882c84cff43b9d60df7574a1901e2cdcd',
Var('chromium_url') + '/external/github.com/test262-utils/test262-harness-py.git' + '@' + '9bd99c6f33be10561970bfe16f2f16a8a3d88722',
'v8/third_party/qemu-linux-x64': {
'packages': [
{
@@ -92,7 +206,7 @@ deps = {
'dep_type': 'cipd',
},
'v8/tools/clang':
Var('chromium_url') + '/chromium/src/tools/clang.git' + '@' + '257c91cc44b07bd06ff03dde809ccbc46a22bec6',
Var('chromium_url') + '/chromium/src/tools/clang.git' + '@' + 'edee5c0b3641ab345cbe3cf29f1b1cdbd6819549',
'v8/tools/luci-go': {
'packages': [
{
@@ -111,10 +225,23 @@ deps = {
'condition': 'host_cpu != "s390"',
'dep_type': 'cipd',
},
'v8/tools/clang/dsymutil': {
'packages': [
{
'package': 'chromium/llvm-build-tools/dsymutil',
'version': 'OWlhXkmj18li3yhJk59Kmjbc5KdgLh56TwCd1qBdzlIC',
}
],
'condition': 'checkout_mac',
'dep_type': 'cipd',
},
'v8/test/wasm-js/data':
Var('chromium_url') + '/external/github.com/WebAssembly/spec.git' + '@' + '44dfa15cb87b1e9bef36e033ad5d2cdc4c2008fd',
Var('chromium_url') + '/external/github.com/WebAssembly/spec.git' + '@' + 'd14d538e5fccdc03a02948963addad10ad45b50d',
'v8/third_party/perfetto':
Var('android_url') + '/platform/external/perfetto.git' + '@' + '21a33afeef568f72668acf77668a32307a363d6e',
'v8/third_party/protobuf':
Var('chromium_url') + '/external/github.com/google/protobuf'+ '@' + 'b68a347f56137b4b1a746e8c7438495a6ac1bd91',
}
recursedeps = [
'v8/third_party/android_tools',
]
@@ -216,43 +343,6 @@ hooks = [
'--platform=linux*',
],
},
# Pull GN using checked-in hashes.
{
'name': 'gn_win',
'pattern': '.',
'condition': 'host_os == "win"',
'action': [ 'download_from_google_storage',
'--no_resume',
'--platform=win32',
'--no_auth',
'--bucket', 'chromium-gn',
'-s', 'v8/buildtools/win/gn.exe.sha1',
],
},
{
'name': 'gn_mac',
'pattern': '.',
'condition': 'host_os == "mac"',
'action': [ 'download_from_google_storage',
'--no_resume',
'--platform=darwin',
'--no_auth',
'--bucket', 'chromium-gn',
'-s', 'v8/buildtools/mac/gn.sha1',
],
},
{
'name': 'gn_linux',
'pattern': '.',
'condition': 'host_os == "linux"',
'action': [ 'download_from_google_storage',
'--no_resume',
'--platform=linux*',
'--no_auth',
'--bucket', 'chromium-gn',
'-s', 'v8/buildtools/linux64/gn.sha1',
],
},
{
'name': 'wasm_spec_tests',
'pattern': '.',
+6 -4
View File
@@ -20,11 +20,13 @@ are:
This code is copyrighted by Sun Microsystems Inc. and released
under a 3-clause BSD license.
- Valgrind client API header, located at third_party/valgrind/valgrind.h
This is release under the BSD license.
- Valgrind client API header, located at src/third_party/valgrind/valgrind.h
This is released under the BSD license.
- antlr4 parser generator Cpp library located in third_party/antlr4
This is release under the BSD license.
- The Wasm C/C++ API headers, located at third_party/wasm-api/wasm.{h,hh}
This is released under the Apache license. The API's upstream prototype
implementation also formed the basis of V8's implementation in
src/wasm/c-api.cc.
These libraries have their own licenses; we recommend you read them,
as their terms may differ from the terms below.
+1
View File
@@ -31,6 +31,7 @@ petermarshall@chromium.org
rmcilroy@chromium.org
sergiyb@chromium.org
sigurds@chromium.org
szuend@chromium.org
tebbi@chromium.org
titzer@chromium.org
ulan@chromium.org
+3 -3
View File
@@ -10,7 +10,7 @@ browser from Google.
V8 can run standalone, or can be embedded into any C++ application.
V8 Project page: https://github.com/v8/v8/wiki
V8 Project page: https://v8.dev/docs
Getting the Code
@@ -36,5 +36,5 @@ configuration in `.git/config`:
Contributing
=============
Please follow the instructions mentioned on the
[V8 wiki](https://github.com/v8/v8/wiki/Contributing).
Please follow the instructions mentioned at
[v8.dev/docs/contribute](https://v8.dev/docs/contribute).
+4 -11
View File
@@ -985,17 +985,6 @@
TRACE_EVENT_PHASE_LEAVE_CONTEXT, category_group, name, context, \
TRACE_EVENT_FLAG_NONE)
// Macro to specify that two trace IDs are identical. For example,
// TRACE_LINK_IDS(
// "category", "name",
// TRACE_ID_WITH_SCOPE("net::URLRequest", 0x1000),
// TRACE_ID_WITH_SCOPE("blink::ResourceFetcher::FetchRequest", 0x2000))
// tells the trace consumer that events with ID ("net::URLRequest", 0x1000) from
// the current process have the same ID as events with ID
// ("blink::ResourceFetcher::FetchRequest", 0x2000).
#define TRACE_LINK_IDS(category_group, name, id, linked_id) \
INTERNAL_TRACE_EVENT_ADD_LINK_IDS(category_group, name, id, linked_id);
// Macro to efficiently determine if a given category group is enabled.
#define TRACE_EVENT_CATEGORY_GROUP_ENABLED(category_group, ret) \
do { \
@@ -1080,6 +1069,10 @@
#define TRACE_EVENT_FLAG_HAS_PROCESS_ID (static_cast<unsigned int>(1 << 11))
#define TRACE_EVENT_FLAG_HAS_LOCAL_ID (static_cast<unsigned int>(1 << 12))
#define TRACE_EVENT_FLAG_HAS_GLOBAL_ID (static_cast<unsigned int>(1 << 13))
#define TRACE_EVENT_FLAG_DISALLOW_POSTTASK (static_cast<unsigned int>(1 << 14))
// TODO(eseckler): Remove once we have native support for typed proto events in
// TRACE_EVENT macros.
#define TRACE_EVENT_FLAG_TYPED_PROTO_ARGS (static_cast<unsigned int>(1 << 15))
#define TRACE_EVENT_FLAG_SCOPE_MASK \
(static_cast<unsigned int>(TRACE_EVENT_FLAG_SCOPE_OFFSET | \
+10
View File
@@ -6,6 +6,16 @@
# Chromium specific targets in a client project's GN file etc.
build_with_chromium = false
# Used by perfetto to distinguish from its own standalone build and the
# chromium build.
perfetto_build_with_embedder = true
# When embedding perfetto, its build files need to know in which BUILD.gn file
# the embedder (v8) declared the protobuf targets. In the v8 case they are
# declared in the root v8/BUILD.gn.
perfetto_protobuf_target_prefix = "//"
perfetto_protobuf_gni = "//gni/proto_library.gni"
# Uncomment these to specify a different NDK location and version in
# non-Chromium builds.
# default_android_ndk_root = "//third_party/android_ndk"
+1 -2
View File
@@ -1,2 +1 @@
The documentation for V8 can be found at the
[V8 Wiki](https://github.com/v8/v8/wiki).
The documentation for V8 can be found at [v8.dev/docs](https://v8.dev/docs).
+218
View File
@@ -0,0 +1,218 @@
# Copyright 2019 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.
import("//build_overrides/build.gni")
# This file should not be pulled in chromium builds.
assert(!build_with_chromium)
template("proto_library") {
assert(defined(invoker.sources))
proto_sources = invoker.sources
set_sources_assignment_filter([])
# All the proto imports should be relative to the project root.
proto_in_dir = "//"
if (defined(invoker.proto_in_dir)) {
proto_in_dir = invoker.proto_in_dir
}
assert(defined(invoker.proto_out_dir),
"proto_out_dir must be explicitly defined")
proto_out_dir = invoker.proto_out_dir
# We don't support generate_python in the standalone build, but still must
# check that the caller sets this to false. This is because when building in
# the chromium tree, chromium's proto_library.gni in chrome (!= this) defaults
# generate_python = true.
assert(defined(invoker.generate_python) && !invoker.generate_python)
# If false will not generate the default .pb.{cc,h} files. Used for custom
# codegen plugins.
generate_cc = true
if (defined(invoker.generate_cc)) {
generate_cc = invoker.generate_cc
}
generate_descriptor = ""
if (defined(invoker.generate_descriptor)) {
generate_descriptor = invoker.generate_descriptor
}
if (defined(invoker.generator_plugin_label)) {
plugin_host_label = invoker.generator_plugin_label + "($host_toolchain)"
plugin_path = get_label_info(plugin_host_label, "root_out_dir") + "/" +
get_label_info(plugin_host_label, "name")
generate_with_plugin = true
} else if (defined(invoker.generator_plugin_script)) {
plugin_path = invoker.generator_plugin_script
generate_with_plugin = true
} else {
generate_with_plugin = false
}
if (generate_with_plugin) {
if (defined(invoker.generator_plugin_suffix)) {
generator_plugin_suffixes = [
"${invoker.generator_plugin_suffix}.h",
"${invoker.generator_plugin_suffix}.cc",
]
} else {
generator_plugin_suffixes = invoker.generator_plugin_suffixes
}
}
cc_out_dir = "$root_gen_dir/" + proto_out_dir
rel_cc_out_dir = rebase_path(cc_out_dir, root_build_dir)
protos = rebase_path(proto_sources, proto_in_dir)
protogens = []
if (generate_descriptor != "") {
protogens += [ "$root_gen_dir/" + generate_descriptor ]
}
foreach(proto, protos) {
proto_dir = get_path_info(proto, "dir")
proto_name = get_path_info(proto, "name")
proto_path = proto_dir + "/" + proto_name
if (generate_cc) {
protogens += [
"$cc_out_dir/$proto_path.pb.h",
"$cc_out_dir/$proto_path.pb.cc",
]
}
if (generate_with_plugin) {
foreach(suffix, generator_plugin_suffixes) {
protogens += [ "$cc_out_dir/${proto_path}${suffix}" ]
}
}
}
config_name = "${target_name}_config"
action_name = "${target_name}_gen"
source_set_name = target_name
config(config_name) {
include_dirs = [ cc_out_dir ]
}
# The XXX_gen action that generates the .pb.{cc,h} files.
action(action_name) {
visibility = [ ":$source_set_name" ]
script = "//build/gn_run_binary.py"
sources = proto_sources
outputs = get_path_info(protogens, "abspath")
protoc_label = "//:protoc($host_toolchain)"
protoc_path = get_label_info(protoc_label, "root_out_dir") + "/protoc"
args = [
# Path should be rebased because |root_build_dir| for current toolchain
# may be different from |root_out_dir| of protoc built on host toolchain.
"./" + rebase_path(protoc_path, root_build_dir),
"--proto_path",
rebase_path(proto_in_dir, root_build_dir),
]
if (generate_cc) {
args += [
"--cpp_out",
rel_cc_out_dir,
]
}
if (generate_descriptor != "") {
args += [
"--include_imports",
"--descriptor_set_out",
rebase_path("$root_gen_dir/" + generate_descriptor, root_build_dir),
]
}
if (generate_with_plugin) {
plugin_path_rebased = rebase_path(plugin_path, root_build_dir)
plugin_out_args = ""
if (defined(invoker.generator_plugin_options)) {
plugin_out_args += invoker.generator_plugin_options
}
plugin_out_args += ":$rel_cc_out_dir"
args += [
"--plugin=protoc-gen-plugin=$plugin_path_rebased",
"--plugin_out=$plugin_out_args",
]
}
args += rebase_path(proto_sources, root_build_dir)
inputs = [
protoc_path,
]
deps = [
protoc_label,
]
if (generate_with_plugin) {
inputs += [ plugin_path ]
if (defined(plugin_host_label)) {
# Action depends on native generator plugin but for host toolchain only.
deps += [ plugin_host_label ]
}
}
if (defined(invoker.proto_deps)) {
deps += invoker.proto_deps
}
if (defined(invoker.deps)) {
deps += invoker.deps
}
} # action "${target_name}_gen"
# The source_set that builds the generated .pb.cc files.
source_set(target_name) {
forward_variables_from(invoker,
[
"defines",
"include_dirs",
"public_configs",
"testonly",
"visibility",
])
sources = get_target_outputs(":$action_name")
# configs -= [ "//gn/standalone:extra_warnings" ]
if (defined(invoker.extra_configs)) {
configs += invoker.extra_configs
}
if (!defined(invoker.public_configs)) {
public_configs = []
}
public_configs += [
"//:protobuf_gen_config",
":$config_name",
]
# Use protobuf_full only for tests.
if (defined(invoker.use_protobuf_full) &&
invoker.use_protobuf_full == true) {
deps = [
"//:protobuf_full",
]
} else {
deps = [
"//:protobuf_lite",
]
}
deps += [ ":$action_name" ]
if (defined(invoker.deps)) {
deps += invoker.deps
}
if (defined(invoker.link_deps)) {
deps += invoker.link_deps
}
} # source_set(target_name)
} # template
+22 -3
View File
@@ -31,11 +31,18 @@ declare_args() {
# Support for backtrace_symbols on linux.
v8_enable_backtrace = ""
# Enables raw heap snapshots containing internals. Used for debugging memory
# on platform and embedder level.
v8_enable_raw_heap_snapshots = false
# Enable the snapshot feature, for fast context creation.
# https://v8.dev/blog/custom-startup-snapshots
# TODO(thakis): Make snapshots work in 64-bit win/cross builds,
# https://803591
v8_use_snapshot = !(is_win && host_os != "win" && target_cpu == "x64")
# On Mac hosts, 32-bit builds targeting Windows can't use snapshots, see
# https://crbug.com/794838
v8_use_snapshot = !(is_win && host_os != "win" && target_cpu == "x64") &&
!(is_win && host_os == "mac" && target_cpu == "x86")
# Enable several snapshots side-by-side (e.g. default and for trusted code).
v8_use_multi_snapshots = false
@@ -94,8 +101,20 @@ v8_add_configs = [
v8_path_prefix + ":toolchain",
]
v8_remove_configs += [ "//build/config/compiler:default_optimization" ]
v8_add_configs += [ v8_path_prefix + ":default_optimization" ]
if (is_debug && !v8_optimized_debug) {
v8_remove_configs += [ "//build/config/compiler:default_optimization" ]
v8_add_configs += [ "//build/config/compiler:no_optimize" ]
} else {
v8_remove_configs += [ "//build/config/compiler:default_optimization" ]
# TODO(crbug.com/621335) Rework this so that we don't have the confusion
# between "optimize_speed" and "optimize_max".
if (((is_posix && !is_android) || is_fuchsia) && !using_sanitizer) {
v8_add_configs += [ "//build/config/compiler:optimize_speed" ]
} else {
v8_add_configs += [ "//build/config/compiler:optimize_max" ]
}
}
if (v8_code_coverage && !is_clang) {
v8_add_configs += [
+38 -1
View File
@@ -48,7 +48,7 @@ template class V8_EXPORT std::vector<v8::CpuProfileDeoptInfo>;
namespace v8 {
// TickSample captures the information collected for each sample.
struct TickSample {
struct V8_EXPORT TickSample {
// Internal profiling (with --prof + tools/$OS-tick-processor) wants to
// include the runtime function we're calling. Externally exposed tick
// samples don't care.
@@ -129,6 +129,20 @@ class V8_EXPORT CpuProfileNode {
unsigned int hit_count;
};
// An annotation hinting at the source of a CpuProfileNode.
enum SourceType {
// User-supplied script with associated resource information.
kScript = 0,
// Native scripts and provided builtins.
kBuiltin = 1,
// Callbacks into native code.
kCallback = 2,
// VM-internal functions or state.
kInternal = 3,
// A node that failed to symbolize.
kUnresolved = 4,
};
/** Returns function name (empty string for anonymous functions.) */
Local<String> GetFunctionName() const;
@@ -152,6 +166,12 @@ class V8_EXPORT CpuProfileNode {
*/
const char* GetScriptResourceNameStr() const;
/**
* Return true if the script from where the function originates is flagged as
* being shared cross-origin.
*/
bool IsScriptSharedCrossOrigin() const;
/**
* Returns the number, 1-based, of the line where the function originates.
* kNoLineNumberInfo if no line number information is available.
@@ -194,12 +214,20 @@ class V8_EXPORT CpuProfileNode {
/** Returns id of the node. The id is unique within the tree */
unsigned GetNodeId() const;
/**
* Gets the type of the source which the node was captured from.
*/
SourceType GetSourceType() const;
/** Returns child nodes count of the node. */
int GetChildrenCount() const;
/** Retrieves a child node by index. */
const CpuProfileNode* GetChild(int index) const;
/** Retrieves the ancestor node, or null if the root. */
const CpuProfileNode* GetParent() const;
/** Retrieves deopt infos for the node. */
const std::vector<CpuProfileDeoptInfo>& GetDeoptInfos() const;
@@ -301,6 +329,15 @@ class V8_EXPORT CpuProfiler {
*/
void SetSamplingInterval(int us);
/**
* Sets whether or not the profiler should prioritize consistency of sample
* periodicity on Windows. Disabling this can greatly reduce CPU usage, but
* may result in greater variance in sample timings from the platform's
* scheduler. Defaults to enabled. This method must be called when there are
* no profiles being recorded.
*/
void SetUsePreciseSampling(bool);
/**
* Starts collecting CPU profile. Title may be an empty string. It
* is allowed to have several profiles being collected at
+2 -2
View File
@@ -9,9 +9,9 @@
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define V8_MAJOR_VERSION 7
#define V8_MINOR_VERSION 4
#define V8_MINOR_VERSION 5
#define V8_BUILD_NUMBER 288
#define V8_PATCH_LEVEL 27
#define V8_PATCH_LEVEL 22
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
+61 -34
View File
@@ -2520,9 +2520,9 @@ class V8_EXPORT Value : public Data {
V8_WARN_UNUSED_RESULT MaybeLocal<BigInt> ToBigInt(
Local<Context> context) const;
V8_DEPRECATE_SOON("ToBoolean can never throw. Use Local version.",
V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
Local<Context> context) const);
V8_DEPRECATED("ToBoolean can never throw. Use Local version.",
V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
Local<Context> context) const);
V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
Local<Context> context) const;
V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
@@ -2538,16 +2538,16 @@ class V8_EXPORT Value : public Data {
V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
Local<Boolean> ToBoolean(Isolate* isolate) const;
V8_DEPRECATE_SOON("Use maybe version",
Local<Number> ToNumber(Isolate* isolate) const);
V8_DEPRECATE_SOON("Use maybe version",
Local<String> ToString(Isolate* isolate) const);
V8_DEPRECATE_SOON("Use maybe version",
Local<Object> ToObject(Isolate* isolate) const);
V8_DEPRECATE_SOON("Use maybe version",
Local<Integer> ToInteger(Isolate* isolate) const);
V8_DEPRECATE_SOON("Use maybe version",
Local<Int32> ToInt32(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Number> ToNumber(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<String> ToString(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Object> ToObject(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Integer> ToInteger(Isolate* isolate) const);
V8_DEPRECATED("Use maybe version",
Local<Int32> ToInt32(Isolate* isolate) const);
/**
* Attempts to convert a string to an array index.
@@ -2906,7 +2906,7 @@ class V8_EXPORT String : public Name {
int length = -1);
/** Allocates a new string from UTF-16 data.*/
static V8_DEPRECATE_SOON(
static V8_DEPRECATED(
"Use maybe version",
Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
NewStringType type = kNormalString,
@@ -2955,7 +2955,7 @@ class V8_EXPORT String : public Name {
* should the underlying buffer be deallocated or modified except through the
* destructor of the external string resource.
*/
static V8_DEPRECATE_SOON(
static V8_DEPRECATED(
"Use maybe version",
Local<String> NewExternal(Isolate* isolate,
ExternalOneByteStringResource* resource));
@@ -5164,8 +5164,7 @@ class V8_EXPORT SharedArrayBuffer : public Object {
allocation_length_(0),
allocation_mode_(Allocator::AllocationMode::kNormal),
deleter_(nullptr),
deleter_data_(nullptr),
is_growable_(false) {}
deleter_data_(nullptr) {}
void* AllocationBase() const { return allocation_base_; }
size_t AllocationLength() const { return allocation_length_; }
@@ -5177,13 +5176,12 @@ class V8_EXPORT SharedArrayBuffer : public Object {
size_t ByteLength() const { return byte_length_; }
DeleterCallback Deleter() const { return deleter_; }
void* DeleterData() const { return deleter_data_; }
bool IsGrowable() const { return is_growable_; }
private:
Contents(void* data, size_t byte_length, void* allocation_base,
size_t allocation_length,
Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
void* deleter_data, bool is_growable);
void* deleter_data);
void* data_;
size_t byte_length_;
@@ -5192,7 +5190,6 @@ class V8_EXPORT SharedArrayBuffer : public Object {
Allocator::AllocationMode allocation_mode_;
DeleterCallback deleter_;
void* deleter_data_;
bool is_growable_;
friend class SharedArrayBuffer;
};
@@ -5224,9 +5221,11 @@ class V8_EXPORT SharedArrayBuffer : public Object {
* Create a new SharedArrayBuffer over an existing memory block. Propagate
* flags to indicate whether the underlying buffer can be grown.
*/
static Local<SharedArrayBuffer> New(
Isolate* isolate, const SharedArrayBuffer::Contents&,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
V8_DEPRECATED("Use New method with data, and byte_length instead.",
static Local<SharedArrayBuffer> New(
Isolate* isolate, const SharedArrayBuffer::Contents&,
ArrayBufferCreationMode mode =
ArrayBufferCreationMode::kExternalized));
/**
* Returns true if SharedArrayBuffer is externalized, that is, does not
@@ -5315,11 +5314,10 @@ class V8_EXPORT Date : public Object {
* This API should not be called more than needed as it will
* negatively impact the performance of date operations.
*/
V8_DEPRECATE_SOON(
"Use Isolate::DateTimeConfigurationChangeNotification",
static void DateTimeConfigurationChangeNotification(
Isolate* isolate,
TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip));
V8_DEPRECATED("Use Isolate::DateTimeConfigurationChangeNotification",
static void DateTimeConfigurationChangeNotification(
Isolate* isolate, TimeZoneDetection time_zone_detection =
TimeZoneDetection::kSkip));
private:
static void CheckCast(Value* obj);
@@ -6681,7 +6679,7 @@ typedef void (*HostInitializeImportMetaObjectCallback)(Local<Context> context,
* first accessed. The return value will be used as the stack value. If this
* callback is registed, the |Error.prepareStackTrace| API will be disabled.
* |sites| is an array of call sites, specified in
* https://github.com/v8/v8/wiki/Stack-Trace-API
* https://v8.dev/docs/stack-trace-api
*/
typedef MaybeLocal<Value> (*PrepareStackTraceCallback)(Local<Context> context,
Local<Value> error,
@@ -6735,7 +6733,8 @@ class PromiseRejectMessage {
typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
// --- Microtasks Callbacks ---
typedef void (*MicrotasksCompletedCallback)(Isolate*);
V8_DEPRECATE_SOON("Use *WithData version.",
typedef void (*MicrotasksCompletedCallback)(Isolate*));
typedef void (*MicrotasksCompletedCallbackWithData)(Isolate*, void*);
typedef void (*MicrotaskCallback)(void* data);
@@ -6769,7 +6768,8 @@ class V8_EXPORT MicrotaskQueue {
/**
* Creates an empty MicrotaskQueue instance.
*/
static std::unique_ptr<MicrotaskQueue> New(Isolate* isolate);
static std::unique_ptr<MicrotaskQueue> New(
Isolate* isolate, MicrotasksPolicy policy = MicrotasksPolicy::kAuto);
virtual ~MicrotaskQueue() = default;
@@ -6817,6 +6817,12 @@ class V8_EXPORT MicrotaskQueue {
*/
virtual bool IsRunningMicrotasks() const = 0;
/**
* Returns the current depth of nested MicrotasksScope that has
* kRunMicrotasks.
*/
virtual int GetMicrotasksScopeDepth() const = 0;
private:
friend class internal::MicrotaskQueue;
MicrotaskQueue() = default;
@@ -7165,6 +7171,13 @@ enum JitCodeEventOptions {
*/
typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
/**
* Callback function passed to SetUnhandledExceptionCallback.
*/
#if defined(V8_OS_WIN)
typedef int (*UnhandledExceptionCallback)(
_EXCEPTION_POINTERS* exception_pointers);
#endif
/**
* Interface for iterating through all external resources in the heap.
@@ -8379,13 +8392,13 @@ class V8_EXPORT Isolate {
/**
* 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.
* Instead, see GetEmbeddedCodeRange.
*
* 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.
* 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.
*
@@ -8785,6 +8798,20 @@ class V8_EXPORT V8 {
*/
static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
#if defined(V8_OS_WIN)
/**
* On Win64, by default V8 does not emit unwinding data for jitted code,
* which means the OS cannot walk the stack frames and the system Structured
* Exception Handling (SEH) cannot unwind through V8-generated code:
* https://code.google.com/p/v8/issues/detail?id=3598.
*
* This function allows embedders to register a custom exception handler for
* exceptions in V8-generated code.
*/
static void SetUnhandledExceptionCallback(
UnhandledExceptionCallback unhandled_exception_callback);
#endif
private:
V8();
+4
View File
@@ -64,6 +64,7 @@
// V8_OS_FUCHSIA - Fuchsia
// V8_OS_LINUX - Linux
// V8_OS_MACOSX - Mac OS X
// V8_OS_IOS - iOS
// V8_OS_NETBSD - NetBSD
// V8_OS_OPENBSD - OpenBSD
// V8_OS_POSIX - POSIX compatible (mostly everything except Windows)
@@ -80,6 +81,9 @@
# define V8_OS_BSD 1
# define V8_OS_MACOSX 1
# define V8_OS_POSIX 1
# if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
# define V8_OS_IOS 1
# endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#elif defined(__CYGWIN__)
# define V8_OS_CYGWIN 1
# define V8_OS_POSIX 1
+9 -22
View File
@@ -89,11 +89,8 @@
'V8 Linux64 TSAN - builder': 'release_x64_tsan',
'V8 Linux - arm64 - sim - MSAN': 'release_simulate_arm64_msan',
# Misc.
'V8 Linux gcc': 'release_x86_gcc_no_goma',
'V8 Linux64 gcc - debug': 'debug_x64_gcc_no_goma',
# TODO(machenbach): Remove after switching.
'V8 Linux gcc 4.8': 'release_x86_gcc',
'V8 Linux64 gcc 4.8 - debug': 'debug_x64_gcc',
'V8 Linux gcc': 'release_x86_gcc',
'V8 Linux64 gcc - debug': 'debug_x64_gcc',
# FYI.
'V8 Linux64 - pointer compression': 'release_x64_pointer_compression',
'V8 Linux64 - arm64 - sim - pointer compression - builder':
@@ -212,7 +209,7 @@
'v8_linux64_compile_rel_xg': 'release_x64_test_features_trybot',
'v8_linux64_dbg_ng': 'debug_x64_trybot',
'v8_linux64_gc_stress_custom_snapshot_dbg_ng': 'debug_x64_trybot_custom',
'v8_linux64_gcc_compile_dbg': 'debug_x64_gcc_no_goma',
'v8_linux64_gcc_compile_dbg': 'debug_x64_gcc',
'v8_linux64_header_includes_dbg': 'debug_x64_header_includes',
'v8_linux64_fyi_rel_ng': 'release_x64_test_features_trybot',
'v8_linux64_pointer_compression_rel_ng': 'release_x64_pointer_compression',
@@ -434,7 +431,8 @@
'release_x64_fuchsia_trybot': [
'release_trybot', 'x64', 'fuchsia'],
'release_x64_gcc_coverage': [
'release_bot', 'x64', 'coverage', 'gcc', 'no_custom_libcxx', 'no_sysroot'],
'release_bot', 'x64', 'coverage', 'gcc', 'no_custom_libcxx',
'no_sysroot'],
'release_x64_internal': [
'release_bot', 'x64', 'v8_snapshot_internal'],
'release_x64_jumbo': [
@@ -484,9 +482,6 @@
'debug_bot', 'x64', 'fuchsia'],
'debug_x64_gcc': [
'debug_bot', 'x64', 'gcc'],
'debug_x64_gcc_no_goma': [
'debug', 'shared', 'v8_enable_slow_dchecks', 'v8_optimized_debug', 'x64',
'gcc', 'no_goma'],
'debug_x64_header_includes': [
'debug_bot', 'x64', 'v8_check_header_includes'],
'debug_x64_jumbo': [
@@ -518,8 +513,7 @@
'debug_x86_vtunejit': [
'debug_bot', 'x86', 'v8_enable_vtunejit'],
'full_debug_x86': [
'debug', 'x86', 'goma', 'static', 'v8_enable_slow_dchecks',
'v8_full_debug'],
'debug', 'x86', 'goma', 'v8_enable_slow_dchecks', 'v8_full_debug'],
# Release configs for x86.
'release_x86': [
@@ -530,11 +524,8 @@
'release_trybot', 'x86', 'v8_no_enable_embedded_builtins'],
'release_x86_gcc': [
'release_bot', 'x86', 'gcc'],
# TODO(machenbach): Enable back goma once supported.
'release_x86_gcc_minimal_symbols': [
'release', 'static', 'x86', 'gcc', 'minimal_symbols', 'no_goma'],
'release_x86_gcc_no_goma': [
'release', 'static', 'x86', 'gcc', 'no_goma'],
'release_bot', 'x86', 'gcc', 'minimal_symbols'],
'release_x86_gcmole': [
'release_bot', 'x86', 'gcmole'],
'release_x86_gcmole_trybot': [
@@ -704,10 +695,6 @@
'gn_args': 'use_custom_libcxx=false',
},
'no_goma': {
'gn_args': 'use_goma=false',
},
'no_sysroot': {
'gn_args': 'use_sysroot=false',
},
@@ -772,13 +759,13 @@
# TODO(krasin): Remove is_ubsan_no_recover=true when
# https://llvm.org/bugs/show_bug.cgi?id=25569 is fixed and just use
# ubsan instead.
'gn_args': 'is_ubsan=true is_ubsan_no_recover=true',
'gn_args': 'is_ubsan=true is_ubsan_no_recover=true is_ubsan_vptr=true',
},
'ubsan_recover': {
'mixins': ['v8_enable_test_features'],
# Ubsan with recovery.
'gn_args': 'is_ubsan=true is_ubsan_no_recover=false',
'gn_args': 'is_ubsan=true is_ubsan_no_recover=false is_ubsan_vptr=true',
},
'v8_check_header_includes': {
+21 -63
View File
@@ -58,7 +58,7 @@
{'name': 'mjsunit_sp_frame_access'},
{'name': 'mozilla'},
{'name': 'mozilla', 'variant': 'extra'},
{'name': 'test262'},
{'name': 'test262', 'shards': 2},
{'name': 'test262_variants', 'variant': 'extra', 'shards': 3},
{'name': 'v8testing', 'shards': 3},
{'name': 'v8testing', 'variant': 'extra', 'shards': 2},
@@ -216,11 +216,11 @@
},
'v8_linux_arm_rel_ng_triggered': {
'tests': [
{'name': 'mjsunit_sp_frame_access'},
{'name': 'mjsunit_sp_frame_access', 'shards': 2},
{'name': 'mozilla', 'shards': 2},
{'name': 'test262', 'shards': 2},
{'name': 'v8testing', 'shards': 8},
{'name': 'v8testing', 'variant': 'extra', 'shards': 6},
{'name': 'v8testing', 'shards': 10},
{'name': 'v8testing', 'variant': 'extra', 'shards': 8},
{'name': 'v8testing', 'variant': 'trusted', 'shards': 2},
],
},
@@ -368,11 +368,11 @@
},
'v8_linux_arm64_rel_ng_triggered': {
'tests': [
{'name': 'mjsunit_sp_frame_access'},
{'name': 'mjsunit_sp_frame_access', 'shards': 2},
{'name': 'mozilla', 'shards': 2},
{'name': 'test262', 'shards': 2},
{'name': 'v8testing', 'shards': 9},
{'name': 'v8testing', 'variant': 'extra', 'shards': 6},
{'name': 'v8testing', 'shards': 12},
{'name': 'v8testing', 'variant': 'extra', 'shards': 8},
{'name': 'v8testing', 'variant': 'trusted', 'shards': 3},
],
},
@@ -422,7 +422,7 @@
'os': 'Windows-7-SP1',
},
'tests': [
{'name': 'v8testing', 'variant': 'default', 'shards': 3},
{'name': 'v8testing', 'variant': 'default', 'shards': 4},
],
},
'v8_win_rel_ng_triggered': {
@@ -432,7 +432,7 @@
},
'tests': [
{'name': 'mozilla'},
{'name': 'test262'},
{'name': 'test262', 'shards': 2},
{'name': 'v8testing', 'shards': 2},
],
},
@@ -449,7 +449,7 @@
'v8_win64_dbg': {
'swarming_dimensions' : {
'cpu': 'x86-64',
'os': 'Windows-7-SP1',
'os': 'Windows-10-15063',
},
'tests': [
{'name': 'mozilla'},
@@ -461,7 +461,7 @@
'v8_win64_msvc_rel_ng_triggered': {
'swarming_dimensions' : {
'cpu': 'x86-64',
'os': 'Windows-7-SP1',
'os': 'Windows-10-15063',
},
'tests': [
{'name': 'mozilla'},
@@ -472,7 +472,7 @@
'v8_win64_rel_ng_triggered': {
'swarming_dimensions' : {
'cpu': 'x86-64',
'os': 'Windows-7-SP1',
'os': 'Windows-10-15063',
},
'tests': [
{'name': 'mozilla'},
@@ -739,15 +739,6 @@
{'name': 'v8testing'},
],
},
# TODO(machenbach): Remove after switching.
'V8 Linux gcc 4.8': {
'swarming_dimensions' : {
'os': 'Ubuntu-16.04',
},
'tests': [
{'name': 'v8testing'},
],
},
'V8 Linux64': {
'swarming_dimensions': {
'cpu': 'x86-64-avx2',
@@ -1020,7 +1011,7 @@
},
'V8 Win64': {
'swarming_dimensions': {
'os': 'Windows-7-SP1',
'os': 'Windows-10-15063',
},
'tests': [
{'name': 'mozilla'},
@@ -1031,7 +1022,7 @@
},
'V8 Win64 - debug': {
'swarming_dimensions': {
'os': 'Windows-7-SP1',
'os': 'Windows-10-15063',
},
'tests': [
{'name': 'mozilla'},
@@ -1042,7 +1033,7 @@
},
'V8 Win64 - msvc': {
'swarming_dimensions': {
'os': 'Windows-7-SP1',
'os': 'Windows-10-15063',
},
'tests': [
{'name': 'mozilla'},
@@ -1398,8 +1389,8 @@
# Clusterfuzz.
'V8 NumFuzz': {
'swarming_task_attrs': {
'expiration': 14400,
'hard_timeout': 3600,
'expiration': 13800,
'hard_timeout': 4200,
'priority': 35,
},
'tests': [
@@ -1412,8 +1403,8 @@
},
'V8 NumFuzz - TSAN': {
'swarming_task_attrs': {
'expiration': 14400,
'hard_timeout': 3600,
'expiration': 13800,
'hard_timeout': 4200,
'priority': 35,
},
'tests': [
@@ -1423,22 +1414,6 @@
'suffix': 'marking',
'test_args': ['--total-timeout-sec=2100', '--stress-marking=1']
},
{
'name': 'numfuzz',
'suffix': 'endurance',
'test_args': [
'--total-timeout-sec=1200',
'--combine-tests',
'--combine-min=10',
'--combine-max=30',
'--stress-delay-tasks=1',
'--stress-compaction=2',
'--stress-gc=6',
'--stress-marking=6',
'--stress-scavenge=4',
'--stress-thread-pool-size=1',
],
},
{
'name': 'numfuzz',
'suffix': 'delay',
@@ -1473,8 +1448,8 @@
},
'V8 NumFuzz - debug': {
'swarming_task_attrs': {
'expiration': 14400,
'hard_timeout': 3600,
'expiration': 13800,
'hard_timeout': 4200,
'priority': 35,
},
'tests': [
@@ -1485,23 +1460,6 @@
'test_args': ['--total-timeout-sec=2100', '--stress-marking=1'],
'shards': 2
},
{
'name': 'numfuzz',
'suffix': 'endurance',
'test_args': [
'--total-timeout-sec=1200',
'--combine-tests',
'--combine-min=30',
'--combine-max=50',
'--stress-delay-tasks=1',
'--stress-deopt=2',
'--stress-compaction=2',
'--stress-gc=6',
'--stress-marking=6',
'--stress-scavenge=4',
'--stress-thread-pool-size=1',
],
},
{
'name': 'numfuzz',
'suffix': 'delay',
+1 -4
View File
@@ -60,9 +60,6 @@ if (v8_snapshot_toolchain == "") {
# binaries built for the same OS, so build the snapshot with the current
# toolchain here, too.
v8_snapshot_toolchain = current_toolchain
} else if (current_os == "win" && host_os == "mac" && is_clang) {
# This is a mac -> win cross-compile, which is only supported w/ clang.
v8_snapshot_toolchain = "//build/toolchain/mac:clang_${v8_current_cpu}"
} else if (host_cpu == "x64" &&
(v8_current_cpu == "mips" || v8_current_cpu == "mips64")) {
# We don't support snapshot generation for big-endian targets,
@@ -101,7 +98,7 @@ if (v8_snapshot_toolchain == "") {
if (_cpus != "") {
v8_snapshot_toolchain = "//build/toolchain/${host_os}:${_clang}${_cpus}"
} else if (is_win && v8_current_cpu == "arm64") {
# cross compile Windows arm64 with Windows x64 toolchain.
# cross compile Windows arm64 with host toolchain.
v8_snapshot_toolchain = host_toolchain
}
}
+27 -65
View File
@@ -370,10 +370,7 @@ void Accessors::FunctionLengthGetter(
HandleScope scope(isolate);
Handle<JSFunction> function =
Handle<JSFunction>::cast(Utils::OpenHandle(*info.Holder()));
int length = 0;
if (!JSFunction::GetLength(isolate, function).To(&length)) {
isolate->OptionalRescheduleException(false);
}
int length = function->length();
Handle<Object> result(Smi::FromInt(length), isolate);
info.GetReturnValue().Set(Utils::ToLocal(result));
}
@@ -789,35 +786,6 @@ Handle<AccessorInfo> Accessors::MakeBoundFunctionNameInfo(Isolate* isolate) {
// Accessors::ErrorStack
//
namespace {
MaybeHandle<JSReceiver> ClearInternalStackTrace(Isolate* isolate,
Handle<JSObject> error) {
RETURN_ON_EXCEPTION(
isolate,
Object::SetProperty(
isolate, error, isolate->factory()->stack_trace_symbol(),
isolate->factory()->undefined_value(), StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError)),
JSReceiver);
return error;
}
bool IsAccessor(Handle<Object> receiver, Handle<Name> name,
Handle<JSObject> holder) {
LookupIterator it(receiver, name, holder,
LookupIterator::OWN_SKIP_INTERCEPTOR);
// Skip any access checks we might hit. This accessor should never hit in a
// situation where the caller does not have access.
if (it.state() == LookupIterator::ACCESS_CHECK) {
CHECK(it.HasAccess());
it.Next();
}
return (it.state() == LookupIterator::ACCESSOR);
}
} // namespace
void Accessors::ErrorStackGetter(
v8::Local<v8::Name> key, const v8::PropertyCallbackInfo<v8::Value>& info) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
@@ -825,7 +793,9 @@ void Accessors::ErrorStackGetter(
Handle<JSObject> holder =
Handle<JSObject>::cast(Utils::OpenHandle(*info.Holder()));
// Retrieve the structured stack trace.
// Retrieve the stack trace. It can either be structured data in the form of
// a FrameArray, an already formatted stack trace (string) or whatever the
// "prepareStackTrace" callback produced.
Handle<Object> stack_trace;
Handle<Symbol> stack_trace_symbol = isolate->factory()->stack_trace_symbol();
@@ -838,8 +808,15 @@ void Accessors::ErrorStackGetter(
return;
}
// Format it, clear the internal structured trace and reconfigure as a data
// property.
// Only format the stack-trace the first time around. The check for a
// FixedArray is sufficient as the user callback can not create plain
// FixedArrays and the result is a String in case we format the stack
// trace ourselves.
if (!stack_trace->IsFixedArray()) {
info.GetReturnValue().Set(Utils::ToLocal(stack_trace));
return;
}
Handle<Object> formatted_stack_trace;
if (!ErrorUtils::FormatStackTrace(isolate, holder, stack_trace)
@@ -848,34 +825,16 @@ void Accessors::ErrorStackGetter(
return;
}
MaybeHandle<Object> result = ClearInternalStackTrace(isolate, holder);
// Replace the structured stack-trace with the formatting result.
MaybeHandle<Object> result = Object::SetProperty(
isolate, holder, isolate->factory()->stack_trace_symbol(),
formatted_stack_trace, StoreOrigin::kMaybeKeyed,
Just(ShouldThrow::kThrowOnError));
if (result.is_null()) {
isolate->OptionalRescheduleException(false);
return;
}
// If stack is still an accessor (this could have changed in the meantime
// since FormatStackTrace can execute arbitrary JS), replace it with a data
// property.
Handle<Object> receiver =
Utils::OpenHandle(*v8::Local<v8::Value>(info.This()));
Handle<Name> name = Utils::OpenHandle(*key);
if (IsAccessor(receiver, name, holder)) {
result = Accessors::ReplaceAccessorWithDataProperty(receiver, holder, name,
formatted_stack_trace);
if (result.is_null()) {
isolate->OptionalRescheduleException(false);
return;
}
} else {
// The stack property has been modified in the meantime.
if (!JSObject::GetProperty(isolate, holder, name)
.ToHandle(&formatted_stack_trace)) {
isolate->OptionalRescheduleException(false);
return;
}
}
v8::Local<v8::Value> value = Utils::ToLocal(formatted_stack_trace);
info.GetReturnValue().Set(value);
}
@@ -887,14 +846,17 @@ void Accessors::ErrorStackSetter(
HandleScope scope(isolate);
Handle<JSObject> obj = Handle<JSObject>::cast(
Utils::OpenHandle(*v8::Local<v8::Value>(info.This())));
Handle<Object> value = Handle<Object>::cast(Utils::OpenHandle(*val));
// Clear internal properties to avoid memory leaks.
Handle<Symbol> stack_trace_symbol = isolate->factory()->stack_trace_symbol();
if (JSReceiver::HasOwnProperty(obj, stack_trace_symbol).FromMaybe(false)) {
ClearInternalStackTrace(isolate, obj);
// Store the value in the internal symbol to avoid reconfiguration to
// a data property.
MaybeHandle<Object> result = Object::SetProperty(
isolate, obj, isolate->factory()->stack_trace_symbol(), value,
StoreOrigin::kMaybeKeyed, Just(ShouldThrow::kThrowOnError));
if (result.is_null()) {
isolate->OptionalRescheduleException(false);
return;
}
Accessors::ReconfigureToDataProperty(name, val, info);
}
Handle<AccessorInfo> Accessors::MakeErrorStackInfo(Isolate* isolate) {
+1 -1
View File
@@ -114,7 +114,7 @@ class Accessors : public AllStatic {
Local<v8::Name> property, Local<v8::Value> value,
const PropertyCallbackInfo<v8::Boolean>& info);
static Handle<AccessorInfo> MakeAccessor(
V8_EXPORT_PRIVATE static Handle<AccessorInfo> MakeAccessor(
Isolate* isolate, Handle<Name> name, AccessorNameGetterCallback getter,
AccessorNameBooleanSetterCallback setter);
+1 -1
View File
@@ -80,7 +80,7 @@ class FreeStoreAllocationPolicy {
// Call free to release memory allocated with this function.
void* AllocWithRetry(size_t size);
void* AlignedAlloc(size_t size, size_t alignment);
V8_EXPORT_PRIVATE void* AlignedAlloc(size_t size, size_t alignment);
void AlignedFree(void *ptr);
// Returns platfrom page allocator instance. Guaranteed to be a valid pointer.
+13 -7
View File
@@ -69,15 +69,19 @@ MaybeHandle<Object> DefineAccessorProperty(
!FunctionTemplateInfo::cast(*getter)->do_not_cache());
DCHECK(!setter->IsFunctionTemplateInfo() ||
!FunctionTemplateInfo::cast(*setter)->do_not_cache());
if (force_instantiate) {
if (getter->IsFunctionTemplateInfo()) {
if (getter->IsFunctionTemplateInfo()) {
if (force_instantiate ||
FunctionTemplateInfo::cast(*getter)->BreakAtEntry()) {
ASSIGN_RETURN_ON_EXCEPTION(
isolate, getter,
InstantiateFunction(isolate,
Handle<FunctionTemplateInfo>::cast(getter)),
Object);
}
if (setter->IsFunctionTemplateInfo()) {
}
if (setter->IsFunctionTemplateInfo()) {
if (force_instantiate ||
FunctionTemplateInfo::cast(*setter)->BreakAtEntry()) {
ASSIGN_RETURN_ON_EXCEPTION(
isolate, setter,
InstantiateFunction(isolate,
@@ -85,9 +89,10 @@ MaybeHandle<Object> DefineAccessorProperty(
Object);
}
}
RETURN_ON_EXCEPTION(isolate, JSObject::DefineAccessor(object, name, getter,
setter, attributes),
Object);
RETURN_ON_EXCEPTION(
isolate,
JSObject::DefineAccessor(object, name, getter, setter, attributes),
Object);
return object;
}
@@ -492,8 +497,9 @@ MaybeHandle<JSFunction> InstantiateFunction(Isolate* isolate,
ASSIGN_RETURN_ON_EXCEPTION(isolate, parent_prototype,
GetInstancePrototype(isolate, parent),
JSFunction);
CHECK(parent_prototype->IsHeapObject());
JSObject::ForceSetPrototype(Handle<JSObject>::cast(prototype),
parent_prototype);
Handle<HeapObject>::cast(parent_prototype));
}
}
InstanceType function_type =
+84 -44
View File
@@ -116,10 +116,14 @@
#endif
#if V8_OS_WIN
#include <versionhelpers.h>
#include <windows.h>
#include "include/v8-wasm-trap-handler-win.h"
#include "src/trap-handler/handler-inside-win.h"
#endif
#if V8_TARGET_ARCH_X64
#include "src/unwinding-info-win64.h"
#endif // V8_TARGET_ARCH_X64
#endif // V8_OS_WIN
namespace v8 {
@@ -727,7 +731,8 @@ StartupData SnapshotCreator::CreateBlob(
// We need to store the global proxy size upfront in case we need the
// bootstrapper to create a global proxy before we deserialize the context.
i::Handle<i::FixedArray> global_proxy_sizes =
isolate->factory()->NewFixedArray(num_additional_contexts, i::TENURED);
isolate->factory()->NewFixedArray(num_additional_contexts,
i::AllocationType::kOld);
for (int i = 0; i < num_additional_contexts; i++) {
i::Handle<i::Context> context =
v8::Utils::OpenHandle(*data->contexts_.Get(i));
@@ -746,7 +751,7 @@ StartupData SnapshotCreator::CreateBlob(
i::GarbageCollectionReason::kSnapshotCreator);
{
i::HandleScope scope(isolate);
isolate->heap()->CompactWeakArrayLists(internal::TENURED);
isolate->heap()->CompactWeakArrayLists(internal::AllocationType::kOld);
}
isolate->heap()->read_only_space()->ClearStringPaddingIfNeeded();
@@ -1434,8 +1439,8 @@ static Local<FunctionTemplate> FunctionTemplateNew(
v8::Local<Signature> signature, int length, bool do_not_cache,
v8::Local<Private> cached_property_name = v8::Local<Private>(),
SideEffectType side_effect_type = SideEffectType::kHasSideEffect) {
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::FUNCTION_TEMPLATE_INFO_TYPE, i::TENURED);
i::Handle<i::Struct> struct_obj = isolate->factory()->NewStruct(
i::FUNCTION_TEMPLATE_INFO_TYPE, i::AllocationType::kOld);
i::Handle<i::FunctionTemplateInfo> obj =
i::Handle<i::FunctionTemplateInfo>::cast(struct_obj);
InitializeFunctionTemplate(obj);
@@ -1672,8 +1677,8 @@ static Local<ObjectTemplate> ObjectTemplateNew(
bool do_not_cache) {
LOG_API(isolate, ObjectTemplate, New);
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
i::Handle<i::Struct> struct_obj =
isolate->factory()->NewStruct(i::OBJECT_TEMPLATE_INFO_TYPE, i::TENURED);
i::Handle<i::Struct> struct_obj = isolate->factory()->NewStruct(
i::OBJECT_TEMPLATE_INFO_TYPE, i::AllocationType::kOld);
i::Handle<i::ObjectTemplateInfo> obj =
i::Handle<i::ObjectTemplateInfo>::cast(struct_obj);
InitializeTemplate(obj, Consts::OBJECT_TEMPLATE);
@@ -1825,8 +1830,8 @@ static i::Handle<i::InterceptorInfo> CreateInterceptorInfo(
i::Isolate* isolate, Getter getter, Setter setter, Query query,
Descriptor descriptor, Deleter remover, Enumerator enumerator,
Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
auto obj = i::Handle<i::InterceptorInfo>::cast(
isolate->factory()->NewStruct(i::INTERCEPTOR_INFO_TYPE, i::TENURED));
auto obj = i::Handle<i::InterceptorInfo>::cast(isolate->factory()->NewStruct(
i::INTERCEPTOR_INFO_TYPE, i::AllocationType::kOld));
obj->set_flags(0);
if (getter != nullptr) SET_FIELD_WRAPPED(isolate, obj, set_getter, getter);
@@ -1926,8 +1931,8 @@ void ObjectTemplate::SetAccessCheckCallback(AccessCheckCallback callback,
auto cons = EnsureConstructor(isolate, this);
EnsureNotInstantiated(cons, "v8::ObjectTemplate::SetAccessCheckCallback");
i::Handle<i::Struct> struct_info =
isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE, i::TENURED);
i::Handle<i::Struct> struct_info = isolate->factory()->NewStruct(
i::ACCESS_CHECK_INFO_TYPE, i::AllocationType::kOld);
i::Handle<i::AccessCheckInfo> info =
i::Handle<i::AccessCheckInfo>::cast(struct_info);
@@ -1956,8 +1961,8 @@ void ObjectTemplate::SetAccessCheckCallbackAndHandler(
EnsureNotInstantiated(
cons, "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler");
i::Handle<i::Struct> struct_info =
isolate->factory()->NewStruct(i::ACCESS_CHECK_INFO_TYPE, i::TENURED);
i::Handle<i::Struct> struct_info = isolate->factory()->NewStruct(
i::ACCESS_CHECK_INFO_TYPE, i::AllocationType::kOld);
i::Handle<i::AccessCheckInfo> info =
i::Handle<i::AccessCheckInfo>::cast(struct_info);
@@ -5786,6 +5791,18 @@ bool V8::EnableWebAssemblyTrapHandler(bool use_v8_signal_handler) {
return v8::internal::trap_handler::EnableTrapHandler(use_v8_signal_handler);
}
#if defined(V8_OS_WIN)
void V8::SetUnhandledExceptionCallback(
UnhandledExceptionCallback unhandled_exception_callback) {
#if defined(V8_TARGET_ARCH_X64)
v8::internal::win64_unwindinfo::SetUnhandledExceptionCallback(
unhandled_exception_callback);
#else
// Not implemented on ARM64.
#endif
}
#endif
void v8::V8::SetEntropySource(EntropySource entropy_source) {
base::RandomNumberGenerator::SetEntropySource(entropy_source);
}
@@ -6069,16 +6086,14 @@ MaybeLocal<Object> v8::Context::NewRemoteContext(
Utils::ApiCheck(access_check_info->named_interceptor() != i::Object(),
"v8::Context::NewRemoteContext",
"Global template needs to have access check handlers.");
i::Handle<i::JSGlobalProxy> global_proxy =
CreateEnvironment<i::JSGlobalProxy>(
isolate, nullptr, global_template, global_object, 0,
DeserializeInternalFieldsCallback(), nullptr);
i::Handle<i::JSObject> global_proxy = CreateEnvironment<i::JSGlobalProxy>(
isolate, nullptr, global_template, global_object, 0,
DeserializeInternalFieldsCallback(), nullptr);
if (global_proxy.is_null()) {
if (isolate->has_pending_exception()) isolate->clear_pending_exception();
return MaybeLocal<Object>();
}
return Utils::ToLocal(
scope.CloseAndEscape(i::Handle<i::JSObject>::cast(global_proxy)));
return Utils::ToLocal(scope.CloseAndEscape(global_proxy));
}
void v8::Context::SetSecurityToken(Local<Value> token) {
@@ -6628,7 +6643,7 @@ Local<v8::Object> v8::Object::New(Isolate* isolate,
}
i::Handle<i::JSObject> obj =
i_isolate->factory()->NewSlowJSObjectWithPropertiesAndElements(
proto, properties, elements);
i::Handle<i::HeapObject>::cast(proto), properties, elements);
return Utils::ToLocal(obj);
}
@@ -7359,16 +7374,22 @@ MaybeLocal<WasmModuleObject> WasmModuleObject::Compile(Isolate* isolate,
const uint8_t* start,
size_t length) {
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
i::wasm::ErrorThrower thrower(i_isolate, "WasmModuleObject::Compile()");
if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
return MaybeLocal<WasmModuleObject>();
}
auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
i::MaybeHandle<i::JSObject> maybe_compiled =
i_isolate->wasm_engine()->SyncCompile(
i_isolate, enabled_features, &thrower,
i::wasm::ModuleWireBytes(start, start + length));
if (maybe_compiled.is_null()) return MaybeLocal<WasmModuleObject>();
i::MaybeHandle<i::JSObject> maybe_compiled;
{
i::wasm::ErrorThrower thrower(i_isolate, "WasmModuleObject::Compile()");
auto enabled_features = i::wasm::WasmFeaturesFromIsolate(i_isolate);
maybe_compiled = i_isolate->wasm_engine()->SyncCompile(
i_isolate, enabled_features, &thrower,
i::wasm::ModuleWireBytes(start, start + length));
}
CHECK_EQ(maybe_compiled.is_null(), i_isolate->has_pending_exception());
if (maybe_compiled.is_null()) {
i_isolate->OptionalRescheduleException(false);
return MaybeLocal<WasmModuleObject>();
}
return Local<WasmModuleObject>::Cast(
Utils::ToLocal(maybe_compiled.ToHandleChecked()));
}
@@ -7720,15 +7741,14 @@ v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::Externalize() {
v8::SharedArrayBuffer::Contents::Contents(
void* data, size_t byte_length, void* allocation_base,
size_t allocation_length, Allocator::AllocationMode allocation_mode,
DeleterCallback deleter, void* deleter_data, bool is_growable)
DeleterCallback deleter, void* deleter_data)
: data_(data),
byte_length_(byte_length),
allocation_base_(allocation_base),
allocation_length_(allocation_length),
allocation_mode_(allocation_mode),
deleter_(deleter),
deleter_data_(deleter_data),
is_growable_(is_growable) {
deleter_data_(deleter_data) {
DCHECK_LE(allocation_base_, data_);
DCHECK_LE(byte_length_, allocation_length_);
}
@@ -7746,8 +7766,7 @@ v8::SharedArrayBuffer::Contents v8::SharedArrayBuffer::GetContents() {
: reinterpret_cast<Contents::DeleterCallback>(ArrayBufferDeleter),
self->is_wasm_memory()
? static_cast<void*>(self->GetIsolate()->wasm_engine())
: static_cast<void*>(self->GetIsolate()->array_buffer_allocator()),
self->is_growable());
: static_cast<void*>(self->GetIsolate()->array_buffer_allocator()));
return contents;
}
@@ -7787,7 +7806,6 @@ Local<SharedArrayBuffer> v8::SharedArrayBuffer::New(
ArrayBufferCreationMode mode) {
i::Handle<i::JSArrayBuffer> buffer = SetupSharedArrayBuffer(
isolate, contents.Data(), contents.ByteLength(), mode);
buffer->set_is_growable(contents.IsGrowable());
return Utils::ToLocalShared(buffer);
}
@@ -8395,7 +8413,8 @@ bool Isolate::GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
i::Heap* heap = isolate->heap();
i::Space* space = heap->space(static_cast<int>(index));
space_statistics->space_name_ = heap->GetSpaceName(static_cast<int>(index));
space_statistics->space_name_ =
i::Heap::GetSpaceName(static_cast<i::AllocationSpace>(index));
space_statistics->space_size_ = space->CommittedMemory();
space_statistics->space_used_size_ = space->SizeOfObjects();
space_statistics->space_available_size_ = space->Available();
@@ -8414,7 +8433,7 @@ size_t Isolate::NumberOfTrackedHeapObjectTypes() {
bool Isolate::GetHeapObjectStatisticsAtLastGC(
HeapObjectStatistics* object_statistics, size_t type_index) {
if (!object_statistics) return false;
if (V8_LIKELY(!i::FLAG_gc_stats)) return false;
if (V8_LIKELY(!i::TracingFlags::is_gc_stats_enabled())) return false;
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(this);
i::Heap* heap = isolate->heap();
@@ -8685,7 +8704,7 @@ void Isolate::MemoryPressureNotification(MemoryPressureLevel level) {
bool on_isolate_thread =
v8::Locker::IsActive()
? isolate->thread_manager()->IsLockedByCurrentThread()
: i::ThreadId::Current().Equals(isolate->thread_id());
: i::ThreadId::Current() == isolate->thread_id();
isolate->heap()->MemoryPressureNotification(level, on_isolate_thread);
}
@@ -8916,21 +8935,24 @@ void v8::Isolate::LocaleConfigurationChangeNotification() {
}
// static
std::unique_ptr<MicrotaskQueue> MicrotaskQueue::New(Isolate* isolate) {
return i::MicrotaskQueue::New(reinterpret_cast<i::Isolate*>(isolate));
std::unique_ptr<MicrotaskQueue> MicrotaskQueue::New(Isolate* isolate,
MicrotasksPolicy policy) {
auto microtask_queue =
i::MicrotaskQueue::New(reinterpret_cast<i::Isolate*>(isolate));
microtask_queue->set_microtasks_policy(policy);
return microtask_queue;
}
MicrotasksScope::MicrotasksScope(Isolate* isolate, MicrotasksScope::Type type)
: MicrotasksScope(
isolate,
reinterpret_cast<i::Isolate*>(isolate)->default_microtask_queue(),
type) {}
: MicrotasksScope(isolate, nullptr, type) {}
MicrotasksScope::MicrotasksScope(Isolate* isolate,
MicrotaskQueue* microtask_queue,
MicrotasksScope::Type type)
: isolate_(reinterpret_cast<i::Isolate*>(isolate)),
microtask_queue_(static_cast<i::MicrotaskQueue*>(microtask_queue)),
microtask_queue_(microtask_queue
? static_cast<i::MicrotaskQueue*>(microtask_queue)
: isolate_->default_microtask_queue()),
run_(type == MicrotasksScope::kRunMicrotasks) {
if (run_) microtask_queue_->IncrementMicrotasksScopeDepth();
#ifdef DEBUG
@@ -8942,7 +8964,7 @@ MicrotasksScope::~MicrotasksScope() {
if (run_) {
microtask_queue_->DecrementMicrotasksScopeDepth();
if (MicrotasksPolicy::kScoped == microtask_queue_->microtasks_policy()) {
PerformCheckpoint(reinterpret_cast<Isolate*>(isolate_));
microtask_queue_->PerformCheckpoint(reinterpret_cast<Isolate*>(isolate_));
}
}
#ifdef DEBUG
@@ -9972,6 +9994,11 @@ const char* CpuProfileNode::GetScriptResourceNameStr() const {
return node->entry()->resource_name();
}
bool CpuProfileNode::IsScriptSharedCrossOrigin() const {
const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
return node->entry()->is_shared_cross_origin();
}
int CpuProfileNode::GetLineNumber() const {
return reinterpret_cast<const i::ProfileNode*>(this)->line_number();
}
@@ -10016,6 +10043,9 @@ unsigned CpuProfileNode::GetNodeId() const {
return reinterpret_cast<const i::ProfileNode*>(this)->id();
}
CpuProfileNode::SourceType CpuProfileNode::GetSourceType() const {
return reinterpret_cast<const i::ProfileNode*>(this)->source_type();
}
int CpuProfileNode::GetChildrenCount() const {
return static_cast<int>(
@@ -10029,6 +10059,11 @@ const CpuProfileNode* CpuProfileNode::GetChild(int index) const {
return reinterpret_cast<const CpuProfileNode*>(child);
}
const CpuProfileNode* CpuProfileNode::GetParent() const {
const i::ProfileNode* parent =
reinterpret_cast<const i::ProfileNode*>(this)->parent();
return reinterpret_cast<const CpuProfileNode*>(parent);
}
const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
@@ -10105,6 +10140,11 @@ void CpuProfiler::SetSamplingInterval(int us) {
base::TimeDelta::FromMicroseconds(us));
}
void CpuProfiler::SetUsePreciseSampling(bool use_precise_sampling) {
reinterpret_cast<i::CpuProfiler*>(this)->set_use_precise_sampling(
use_precise_sampling);
}
void CpuProfiler::CollectSample() {
reinterpret_cast<i::CpuProfiler*>(this)->CollectSample();
}
+3 -2
View File
@@ -375,8 +375,9 @@ class HandleScopeImplementer {
void FreeThreadResources();
// Garbage collection support.
void Iterate(v8::internal::RootVisitor* v);
static char* Iterate(v8::internal::RootVisitor* v, char* data);
V8_EXPORT_PRIVATE void Iterate(v8::internal::RootVisitor* v);
V8_EXPORT_PRIVATE static char* Iterate(v8::internal::RootVisitor* v,
char* data);
inline internal::Address* GetSpareOrNewBlock();
inline void DeleteExtensions(internal::Address* prev_limit);
+1 -1
View File
@@ -102,7 +102,7 @@ double ClobberDoubleRegisters(double x1, double x2, double x3, double x4);
Type Name(int args_length, Address* args_object, Isolate* isolate) { \
DCHECK(isolate->context().is_null() || isolate->context()->IsContext()); \
CLOBBER_DOUBLE_REGISTERS(); \
if (V8_UNLIKELY(FLAG_runtime_stats)) { \
if (V8_UNLIKELY(TracingFlags::is_runtime_stats_enabled())) { \
return Stats_##Name(args_length, args_object, isolate); \
} \
Arguments args(args_length, args_object); \
+2 -2
View File
@@ -460,8 +460,8 @@ void Assembler::AllocateAndInstallRequestedHeapObjects(Isolate* isolate) {
Handle<HeapObject> object;
switch (request.kind()) {
case HeapObjectRequest::kHeapNumber:
object =
isolate->factory()->NewHeapNumber(request.heap_number(), TENURED);
object = isolate->factory()->NewHeapNumber(request.heap_number(),
AllocationType::kOld);
break;
case HeapObjectRequest::kStringConstant: {
const StringConstantBase* str = request.string();
+4 -7
View File
@@ -79,7 +79,7 @@ enum Coprocessor {
// Machine instruction Operands
// Class Operand represents a shifter operand in data processing instructions
class Operand {
class V8_EXPORT_PRIVATE Operand {
public:
// immediate
V8_INLINE explicit Operand(int32_t immediate,
@@ -182,9 +182,8 @@ class Operand {
friend class Assembler;
};
// Class MemOperand represents a memory operand in load and store instructions
class MemOperand {
class V8_EXPORT_PRIVATE MemOperand {
public:
// [rn +/- offset] Offset/NegOffset
// [rn +/- offset]! PreIndex/NegPreIndex
@@ -240,10 +239,9 @@ class MemOperand {
friend class Assembler;
};
// Class NeonMemOperand represents a memory operand in load and
// store NEON instructions
class NeonMemOperand {
class V8_EXPORT_PRIVATE NeonMemOperand {
public:
// [rn {:align}] Offset
// [rn {:align}]! PostIndex
@@ -264,7 +262,6 @@ class NeonMemOperand {
int align_;
};
// Class NeonListOperand represents a list of NEON registers
class NeonListOperand {
public:
@@ -1399,7 +1396,7 @@ class PatchingAssembler : public Assembler {
// state, even if the list is modified by some other means. Note that this scope
// can be nested but the destructors need to run in the opposite order as the
// constructors. We do not have assertions for this.
class UseScratchRegisterScope {
class V8_EXPORT_PRIVATE UseScratchRegisterScope {
public:
explicit UseScratchRegisterScope(Assembler* assembler);
~UseScratchRegisterScope();
+4 -1
View File
@@ -19,7 +19,10 @@
namespace v8 {
namespace internal {
void CpuFeatures::FlushICache(void* start, size_t size) {
// The inlining of this seems to trigger an LTO bug that clobbers a register on
// arm, see https://crbug.com/952759#c6.
__attribute__((noinline)) void CpuFeatures::FlushICache(void* start,
size_t size) {
#if !defined(USE_SIMULATOR)
#if V8_OS_QNX
msync(start, size, MS_SYNC | MS_INVALIDATE_ICACHE);
+1 -2
View File
@@ -26,8 +26,7 @@ class EntryFrameConstants : public AllStatic {
class ExitFrameConstants : public TypedFrameConstants {
public:
static constexpr int kSPOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(0);
static constexpr int kCodeOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(1);
DEFINE_TYPED_FRAME_SIZES(2);
DEFINE_TYPED_FRAME_SIZES(1);
// The caller fields are below the frame pointer on the stack.
static constexpr int kCallerFPOffset = 0 * kPointerSize;
+12
View File
@@ -34,6 +34,18 @@ void RecordWriteDescriptor::InitializePlatformSpecific(
data->InitializePlatformSpecific(kParameterCount, default_stub_registers);
}
void EphemeronKeyBarrierDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
const Register default_stub_registers[] = {r0, r1, r2, r3, r4};
data->RestrictAllocatableRegisters(default_stub_registers,
arraysize(default_stub_registers));
CHECK_LE(static_cast<size_t>(kParameterCount),
arraysize(default_stub_registers));
data->InitializePlatformSpecific(kParameterCount, default_stub_registers);
}
const Register FastNewFunctionContextDescriptor::ScopeInfoRegister() {
return r1;
}
+22 -11
View File
@@ -675,6 +675,27 @@ void TurboAssembler::RestoreRegisters(RegList registers) {
ldm(ia_w, sp, regs);
}
void TurboAssembler::CallEphemeronKeyBarrier(Register object, Register address,
SaveFPRegsMode fp_mode) {
EphemeronKeyBarrierDescriptor descriptor;
RegList registers = descriptor.allocatable_registers();
SaveRegisters(registers);
Register object_parameter(
descriptor.GetRegisterParameter(EphemeronKeyBarrierDescriptor::kObject));
Register slot_parameter(descriptor.GetRegisterParameter(
EphemeronKeyBarrierDescriptor::kSlotAddress));
Register fp_mode_parameter(
descriptor.GetRegisterParameter(EphemeronKeyBarrierDescriptor::kFPMode));
MovePair(object_parameter, object, slot_parameter, address);
Move(fp_mode_parameter, Smi::FromEnum(fp_mode));
Call(isolate()->builtins()->builtin_handle(Builtins::kEphemeronKeyBarrier),
RelocInfo::CODE_TARGET);
RestoreRegisters(registers);
}
void TurboAssembler::CallRecordWriteStub(
Register object, Register address,
RememberedSetAction remembered_set_action, SaveFPRegsMode fp_mode) {
@@ -781,14 +802,6 @@ void MacroAssembler::RecordWrite(Register object, Register address,
bind(&done);
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
{
UseScratchRegisterScope temps(this);
IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1,
temps.Acquire(), value);
}
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
@@ -1307,14 +1320,12 @@ void MacroAssembler::EnterExitFrame(bool save_doubles, int stack_space,
DCHECK_EQ(0 * kPointerSize, ExitFrameConstants::kCallerFPOffset);
mov(scratch, Operand(StackFrame::TypeToMarker(frame_type)));
PushCommonFrame(scratch);
// Reserve room for saved entry sp and code object.
// Reserve room for saved entry sp.
sub(sp, fp, Operand(ExitFrameConstants::kFixedFrameSizeFromFp));
if (emit_debug_code()) {
mov(scratch, Operand::Zero());
str(scratch, MemOperand(fp, ExitFrameConstants::kSPOffset));
}
Move(scratch, CodeObject());
str(scratch, MemOperand(fp, ExitFrameConstants::kCodeOffset));
// Save the frame pointer and the context in top.
Move(scratch, ExternalReference::Create(IsolateAddressId::kCEntryFPAddress,
+4 -6
View File
@@ -44,9 +44,7 @@ enum TargetAddressStorageMode {
class V8_EXPORT_PRIVATE TurboAssembler : public TurboAssemblerBase {
public:
template <typename... Args>
explicit TurboAssembler(Args&&... args)
: TurboAssemblerBase(std::forward<Args>(args)...) {}
using TurboAssemblerBase::TurboAssemblerBase;
// Activation support.
void EnterFrame(StackFrame::Type type,
@@ -355,6 +353,8 @@ class V8_EXPORT_PRIVATE TurboAssembler : public TurboAssemblerBase {
void CallRecordWriteStub(Register object, Register address,
RememberedSetAction remembered_set_action,
SaveFPRegsMode fp_mode, Address wasm_target);
void CallEphemeronKeyBarrier(Register object, Register address,
SaveFPRegsMode fp_mode);
// Does a runtime check for 16/32 FP registers. Either way, pushes 32 double
// values to location, saving [d0..(d15|d31)].
@@ -550,9 +550,7 @@ class V8_EXPORT_PRIVATE TurboAssembler : public TurboAssemblerBase {
// MacroAssembler implements a collection of frequently used macros.
class V8_EXPORT_PRIVATE MacroAssembler : public TurboAssembler {
public:
template <typename... Args>
explicit MacroAssembler(Args&&... args)
: TurboAssembler(std::forward<Args>(args)...) {}
using TurboAssembler::TurboAssembler;
void Mls(Register dst, Register src1, Register src2, Register srcA,
Condition cond = al);
+4
View File
@@ -19,6 +19,7 @@
#include "src/objects-inl.h"
#include "src/ostreams.h"
#include "src/runtime/runtime-utils.h"
#include "src/utils.h"
#include "src/vector.h"
// Only build the simulator if not compiling for real ARM hardware.
@@ -4180,6 +4181,9 @@ void CompareGreater(Simulator* simulator, int Vd, int Vm, int Vn, bool ge) {
simulator->set_neon_register<T, SIZE>(Vd, src1);
}
float MinMax(float a, float b, bool is_min) {
return is_min ? JSMin(a, b) : JSMax(a, b);
}
template <typename T>
T MinMax(T a, T b, bool is_min) {
return is_min ? std::min(a, b) : std::max(a, b);
+2 -3
View File
@@ -549,7 +549,6 @@ void Assembler::Reset() {
memset(buffer_start_, 0, pc_ - buffer_start_);
#endif
pc_ = buffer_start_;
ReserveCodeTargetSpace(64);
reloc_info_writer.Reposition(buffer_start_ + buffer_->size(), pc_);
constpool_.Clear();
next_constant_pool_check_ = 0;
@@ -563,8 +562,8 @@ void Assembler::AllocateAndInstallRequestedHeapObjects(Isolate* isolate) {
Address pc = reinterpret_cast<Address>(buffer_start_) + request.offset();
switch (request.kind()) {
case HeapObjectRequest::kHeapNumber: {
Handle<HeapObject> object =
isolate->factory()->NewHeapNumber(request.heap_number(), TENURED);
Handle<HeapObject> object = isolate->factory()->NewHeapNumber(
request.heap_number(), AllocationType::kOld);
set_target_address_at(pc, 0 /* unused */, object.address());
break;
}
+1 -1
View File
@@ -49,7 +49,7 @@ class Immediate {
RelocInfo::Mode rmode() const { return rmode_; }
private:
void InitializeHandle(Handle<HeapObject> value);
V8_EXPORT_PRIVATE void InitializeHandle(Handle<HeapObject> value);
int64_t value_;
RelocInfo::Mode rmode_;
+3 -5
View File
@@ -86,7 +86,7 @@ namespace internal {
// The Visitor interface. Disassembler and simulator (and other tools)
// must provide implementations for all of these functions.
class DecoderVisitor {
class V8_EXPORT_PRIVATE DecoderVisitor {
public:
virtual ~DecoderVisitor() {}
@@ -95,9 +95,8 @@ class DecoderVisitor {
#undef DECLARE
};
// A visitor that dispatches to a list of visitors.
class DispatchingDecoderVisitor : public DecoderVisitor {
class V8_EXPORT_PRIVATE DispatchingDecoderVisitor : public DecoderVisitor {
public:
DispatchingDecoderVisitor() {}
virtual ~DispatchingDecoderVisitor() {}
@@ -121,7 +120,7 @@ class DispatchingDecoderVisitor : public DecoderVisitor {
//
// will call in order visitor methods in V3, V2, V1, V4.
void AppendVisitor(DecoderVisitor* visitor);
void PrependVisitor(DecoderVisitor* visitor);
V8_EXPORT_PRIVATE void PrependVisitor(DecoderVisitor* visitor);
void InsertVisitorBefore(DecoderVisitor* new_visitor,
DecoderVisitor* registered_visitor);
void InsertVisitorAfter(DecoderVisitor* new_visitor,
@@ -142,7 +141,6 @@ class DispatchingDecoderVisitor : public DecoderVisitor {
std::list<DecoderVisitor*> visitors_;
};
template<typename V>
class Decoder : public V {
public:
+2 -5
View File
@@ -14,8 +14,7 @@
namespace v8 {
namespace internal {
class DisassemblingDecoder : public DecoderVisitor {
class V8_EXPORT_PRIVATE DisassemblingDecoder : public DecoderVisitor {
public:
DisassemblingDecoder();
DisassemblingDecoder(char* text_buffer, int buffer_size);
@@ -80,8 +79,7 @@ class DisassemblingDecoder : public DecoderVisitor {
bool own_buffer_;
};
class PrintDisassembler : public DisassemblingDecoder {
class V8_EXPORT_PRIVATE PrintDisassembler : public DisassemblingDecoder {
public:
explicit PrintDisassembler(FILE* stream) : stream_(stream) { }
~PrintDisassembler() { }
@@ -92,7 +90,6 @@ class PrintDisassembler : public DisassemblingDecoder {
FILE *stream_;
};
} // namespace internal
} // namespace v8
+2 -4
View File
@@ -44,10 +44,8 @@ class EntryFrameConstants : public AllStatic {
class ExitFrameConstants : public TypedFrameConstants {
public:
static constexpr int kSPOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(0);
static constexpr int kCodeOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(1);
static constexpr int kPaddingOffset = TYPED_FRAME_PUSHED_VALUE_OFFSET(2);
DEFINE_TYPED_FRAME_SIZES(3);
static constexpr int kLastExitFrameField = kPaddingOffset;
DEFINE_TYPED_FRAME_SIZES(1);
static constexpr int kLastExitFrameField = kSPOffset;
static constexpr int kConstantPoolOffset = 0; // Not used
};
+13 -10
View File
@@ -4,6 +4,7 @@
#include <cstdint>
#include "include/v8config.h"
#include "src/base/macros.h"
namespace v8 {
namespace internal {
@@ -28,23 +29,25 @@ extern "C" {
extern const uint16_t kFP16PositiveInfinity = 0x7C00;
extern const uint16_t kFP16NegativeInfinity = 0xFC00;
extern const uint32_t kFP32PositiveInfinity = 0x7F800000;
extern const uint32_t kFP32NegativeInfinity = 0xFF800000;
extern const uint64_t kFP64PositiveInfinity = 0x7FF0000000000000UL;
extern const uint64_t kFP64NegativeInfinity = 0xFFF0000000000000UL;
V8_EXPORT_PRIVATE extern const uint32_t kFP32PositiveInfinity = 0x7F800000;
V8_EXPORT_PRIVATE extern const uint32_t kFP32NegativeInfinity = 0xFF800000;
V8_EXPORT_PRIVATE extern const uint64_t kFP64PositiveInfinity =
0x7FF0000000000000UL;
V8_EXPORT_PRIVATE extern const uint64_t kFP64NegativeInfinity =
0xFFF0000000000000UL;
// This value is a signalling NaN as both a double and as a float (taking the
// least-significant word).
extern const uint64_t kFP64SignallingNaN = 0x7FF000007F800001;
extern const uint32_t kFP32SignallingNaN = 0x7F800001;
V8_EXPORT_PRIVATE extern const uint64_t kFP64SignallingNaN = 0x7FF000007F800001;
V8_EXPORT_PRIVATE extern const uint32_t kFP32SignallingNaN = 0x7F800001;
// A similar value, but as a quiet NaN.
extern const uint64_t kFP64QuietNaN = 0x7FF800007FC00001;
extern const uint32_t kFP32QuietNaN = 0x7FC00001;
V8_EXPORT_PRIVATE extern const uint64_t kFP64QuietNaN = 0x7FF800007FC00001;
V8_EXPORT_PRIVATE extern const uint32_t kFP32QuietNaN = 0x7FC00001;
// The default NaN values (for FPCR.DN=1).
extern const uint64_t kFP64DefaultNaN = 0x7FF8000000000000UL;
extern const uint32_t kFP32DefaultNaN = 0x7FC00000;
V8_EXPORT_PRIVATE extern const uint64_t kFP64DefaultNaN = 0x7FF8000000000000UL;
V8_EXPORT_PRIVATE extern const uint32_t kFP32DefaultNaN = 0x7FC00000;
extern const uint16_t kFP16DefaultNaN = 0x7E00;
#if defined(V8_OS_WIN)
+12 -12
View File
@@ -26,23 +26,23 @@ extern "C" {
extern const float16 kFP16PositiveInfinity;
extern const float16 kFP16NegativeInfinity;
extern const float kFP32PositiveInfinity;
extern const float kFP32NegativeInfinity;
extern const double kFP64PositiveInfinity;
extern const double kFP64NegativeInfinity;
V8_EXPORT_PRIVATE extern const float kFP32PositiveInfinity;
V8_EXPORT_PRIVATE extern const float kFP32NegativeInfinity;
V8_EXPORT_PRIVATE extern const double kFP64PositiveInfinity;
V8_EXPORT_PRIVATE extern const double kFP64NegativeInfinity;
// This value is a signalling NaN as both a double and as a float (taking the
// least-significant word).
extern const double kFP64SignallingNaN;
extern const float kFP32SignallingNaN;
V8_EXPORT_PRIVATE extern const double kFP64SignallingNaN;
V8_EXPORT_PRIVATE extern const float kFP32SignallingNaN;
// A similar value, but as a quiet NaN.
extern const double kFP64QuietNaN;
extern const float kFP32QuietNaN;
V8_EXPORT_PRIVATE extern const double kFP64QuietNaN;
V8_EXPORT_PRIVATE extern const float kFP32QuietNaN;
// The default NaN values (for FPCR.DN=1).
extern const double kFP64DefaultNaN;
extern const float kFP32DefaultNaN;
V8_EXPORT_PRIVATE extern const double kFP64DefaultNaN;
V8_EXPORT_PRIVATE extern const float kFP32DefaultNaN;
extern const float16 kFP16DefaultNaN;
#if defined(V8_OS_WIN)
@@ -401,11 +401,11 @@ class Instruction {
// Find the PC offset encoded in this instruction. 'this' may be a branch or
// a PC-relative addressing instruction.
// The offset returned is unscaled.
int64_t ImmPCOffset();
V8_EXPORT_PRIVATE int64_t ImmPCOffset();
// Find the target of this instruction. 'this' may be a branch or a
// PC-relative addressing instruction.
Instruction* ImmPCOffsetTarget();
V8_EXPORT_PRIVATE Instruction* ImmPCOffsetTarget();
static bool IsValidImmPCOffset(ImmBranchType branch_type, ptrdiff_t offset);
bool IsTargetInImmPCOffsetRange(Instruction* target);
+12
View File
@@ -34,6 +34,18 @@ void RecordWriteDescriptor::InitializePlatformSpecific(
data->InitializePlatformSpecific(kParameterCount, default_stub_registers);
}
void EphemeronKeyBarrierDescriptor::InitializePlatformSpecific(
CallInterfaceDescriptorData* data) {
const Register default_stub_registers[] = {x0, x1, x2, x3, x4};
data->RestrictAllocatableRegisters(default_stub_registers,
arraysize(default_stub_registers));
CHECK_LE(static_cast<size_t>(kParameterCount),
arraysize(default_stub_registers));
data->InitializePlatformSpecific(kParameterCount, default_stub_registers);
}
const Register FastNewFunctionContextDescriptor::ScopeInfoRegister() {
return x1;
}
+46 -27
View File
@@ -2564,14 +2564,10 @@ void MacroAssembler::EnterExitFrame(bool save_doubles, const Register& scratch,
Mov(fp, sp);
Mov(scratch, StackFrame::TypeToMarker(frame_type));
Push(scratch, xzr);
Mov(scratch, CodeObject());
Push(scratch, padreg);
// fp[8]: CallerPC (lr)
// fp -> fp[0]: CallerFP (old fp)
// fp[-8]: STUB marker
// fp[-16]: Space reserved for SPOffset.
// fp[-24]: CodeObject()
// sp -> fp[-32]: padding
// sp -> fp[-16]: Space reserved for SPOffset.
STATIC_ASSERT((2 * kSystemPointerSize) ==
ExitFrameConstants::kCallerSPOffset);
STATIC_ASSERT((1 * kSystemPointerSize) ==
@@ -2579,9 +2575,6 @@ void MacroAssembler::EnterExitFrame(bool save_doubles, const Register& scratch,
STATIC_ASSERT((0 * kSystemPointerSize) ==
ExitFrameConstants::kCallerFPOffset);
STATIC_ASSERT((-2 * kSystemPointerSize) == ExitFrameConstants::kSPOffset);
STATIC_ASSERT((-3 * kSystemPointerSize) == ExitFrameConstants::kCodeOffset);
STATIC_ASSERT((-4 * kSystemPointerSize) ==
ExitFrameConstants::kPaddingOffset);
// Save the frame pointer and context pointer in the top frame.
Mov(scratch,
@@ -2591,7 +2584,7 @@ void MacroAssembler::EnterExitFrame(bool save_doubles, const Register& scratch,
ExternalReference::Create(IsolateAddressId::kContextAddress, isolate()));
Str(cp, MemOperand(scratch));
STATIC_ASSERT((-4 * kSystemPointerSize) ==
STATIC_ASSERT((-2 * kSystemPointerSize) ==
ExitFrameConstants::kLastExitFrameField);
if (save_doubles) {
ExitFramePreserveFPRegs();
@@ -2608,8 +2601,7 @@ void MacroAssembler::EnterExitFrame(bool save_doubles, const Register& scratch,
// fp -> fp[0]: CallerFP (old fp)
// fp[-8]: STUB marker
// fp[-16]: Space reserved for SPOffset.
// fp[-24]: CodeObject()
// fp[-24 - fp_size]: Saved doubles (if save_doubles is true).
// fp[-16 - fp_size]: Saved doubles (if save_doubles is true).
// sp[8]: Extra space reserved for caller (if extra_space != 0).
// sp -> sp[0]: Space reserved for the return address.
@@ -2671,6 +2663,9 @@ void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
DCHECK_NE(value, 0);
if (FLAG_native_code_counters && counter->Enabled()) {
// This operation has to be exactly 32-bit wide in case the external
// reference table redirects the counter to a uint32_t dummy_stats_counter_
// field.
Mov(scratch2, ExternalReference::Create(counter));
Ldr(scratch1.W(), MemOperand(scratch2));
Add(scratch1.W(), scratch1.W(), value);
@@ -2817,18 +2812,25 @@ void TurboAssembler::DecompressTaggedPointer(const Register& destination,
void TurboAssembler::DecompressAnyTagged(const Register& destination,
const MemOperand& field_operand) {
RecordComment("[ DecompressAnyTagged");
UseScratchRegisterScope temps(this);
Ldrsw(destination, field_operand);
// Branchlessly compute |masked_root|:
// masked_root = HAS_SMI_TAG(destination) ? 0 : kRootRegister;
STATIC_ASSERT((kSmiTagSize == 1) && (kSmiTag == 0));
Register masked_root = temps.AcquireX();
// Sign extend tag bit to entire register.
Sbfx(masked_root, destination, 0, kSmiTagSize);
And(masked_root, masked_root, kRootRegister);
// Now this add operation will either leave the value unchanged if it is a smi
// or add the isolate root if it is a heap object.
Add(destination, masked_root, destination);
if (kUseBranchlessPtrDecompression) {
UseScratchRegisterScope temps(this);
// Branchlessly compute |masked_root|:
// masked_root = HAS_SMI_TAG(destination) ? 0 : kRootRegister;
STATIC_ASSERT((kSmiTagSize == 1) && (kSmiTag == 0));
Register masked_root = temps.AcquireX();
// Sign extend tag bit to entire register.
Sbfx(masked_root, destination, 0, kSmiTagSize);
And(masked_root, masked_root, kRootRegister);
// Now this add operation will either leave the value unchanged if it is a
// smi or add the isolate root if it is a heap object.
Add(destination, masked_root, destination);
} else {
Label done;
JumpIfSmi(destination, &done);
Add(destination, kRootRegister, destination);
bind(&done);
}
RecordComment("]");
}
@@ -3010,6 +3012,28 @@ void TurboAssembler::RestoreRegisters(RegList registers) {
PopCPURegList(regs);
}
void TurboAssembler::CallEphemeronKeyBarrier(Register object, Register address,
SaveFPRegsMode fp_mode) {
EphemeronKeyBarrierDescriptor descriptor;
RegList registers = descriptor.allocatable_registers();
SaveRegisters(registers);
Register object_parameter(
descriptor.GetRegisterParameter(EphemeronKeyBarrierDescriptor::kObject));
Register slot_parameter(descriptor.GetRegisterParameter(
EphemeronKeyBarrierDescriptor::kSlotAddress));
Register fp_mode_parameter(
descriptor.GetRegisterParameter(EphemeronKeyBarrierDescriptor::kFPMode));
MovePair(object_parameter, object, slot_parameter, address);
Mov(fp_mode_parameter, Smi::FromEnum(fp_mode));
Call(isolate()->builtins()->builtin_handle(Builtins::kEphemeronKeyBarrier),
RelocInfo::CODE_TARGET);
RestoreRegisters(registers);
}
void TurboAssembler::CallRecordWriteStub(
Register object, Register address,
RememberedSetAction remembered_set_action, SaveFPRegsMode fp_mode) {
@@ -3114,11 +3138,6 @@ void MacroAssembler::RecordWrite(Register object, Register address,
Bind(&done);
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, address,
value);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
+8 -9
View File
@@ -158,9 +158,7 @@ enum PreShiftImmMode {
class V8_EXPORT_PRIVATE TurboAssembler : public TurboAssemblerBase {
public:
template <typename... Args>
explicit TurboAssembler(Args&&... args)
: TurboAssemblerBase(std::forward<Args>(args)...) {}
using TurboAssemblerBase::TurboAssemblerBase;
#if DEBUG
void set_allow_macro_instructions(bool value) {
@@ -748,6 +746,8 @@ class V8_EXPORT_PRIVATE TurboAssembler : public TurboAssemblerBase {
void CallRecordWriteStub(Register object, Register address,
RememberedSetAction remembered_set_action,
SaveFPRegsMode fp_mode, Address wasm_target);
void CallEphemeronKeyBarrier(Register object, Register address,
SaveFPRegsMode fp_mode);
// Alternative forms of Push and Pop, taking a RegList or CPURegList that
// specifies the registers that are to be pushed or popped. Higher-numbered
@@ -1279,9 +1279,7 @@ class V8_EXPORT_PRIVATE TurboAssembler : public TurboAssemblerBase {
class V8_EXPORT_PRIVATE MacroAssembler : public TurboAssembler {
public:
template <typename... Args>
explicit MacroAssembler(Args&&... args)
: TurboAssembler(std::forward<Args>(args)...) {}
using TurboAssembler::TurboAssembler;
// Instruction set functions ------------------------------------------------
// Logical macros.
@@ -2083,7 +2081,7 @@ class InstructionAccurateScope {
// original state, even if the lists were modified by some other means. Note
// that this scope can be nested but the destructors need to run in the opposite
// order as the constructors. We do not have assertions for this.
class UseScratchRegisterScope {
class V8_EXPORT_PRIVATE UseScratchRegisterScope {
public:
explicit UseScratchRegisterScope(TurboAssembler* tasm)
: available_(tasm->TmpList()),
@@ -2094,7 +2092,7 @@ class UseScratchRegisterScope {
DCHECK_EQ(availablefp_->type(), CPURegister::kVRegister);
}
~UseScratchRegisterScope();
V8_EXPORT_PRIVATE ~UseScratchRegisterScope();
// Take a register from the appropriate temps list. It will be returned
// automatically when the scope ends.
@@ -2111,7 +2109,8 @@ class UseScratchRegisterScope {
VRegister AcquireSameSizeAs(const VRegister& reg);
private:
static CPURegister AcquireNextAvailable(CPURegList* available);
V8_EXPORT_PRIVATE static CPURegister AcquireNextAvailable(
CPURegList* available);
// Available scratch registers.
CPURegList* available_; // kRegister
+9 -8
View File
@@ -316,14 +316,14 @@ VectorFormat ScalarFormatFromLaneSize(int lanesize);
VectorFormat VectorFormatHalfWidthDoubleLanes(VectorFormat vform);
VectorFormat VectorFormatFillQ(VectorFormat vform);
VectorFormat ScalarFormatFromFormat(VectorFormat vform);
unsigned RegisterSizeInBitsFromFormat(VectorFormat vform);
V8_EXPORT_PRIVATE unsigned RegisterSizeInBitsFromFormat(VectorFormat vform);
unsigned RegisterSizeInBytesFromFormat(VectorFormat vform);
int LaneSizeInBytesFromFormat(VectorFormat vform);
unsigned LaneSizeInBitsFromFormat(VectorFormat vform);
int LaneSizeInBytesLog2FromFormat(VectorFormat vform);
int LaneCountFromFormat(VectorFormat vform);
V8_EXPORT_PRIVATE int LaneCountFromFormat(VectorFormat vform);
int MaxLaneCountFromFormat(VectorFormat vform);
bool IsVectorFormat(VectorFormat vform);
V8_EXPORT_PRIVATE bool IsVectorFormat(VectorFormat vform);
int64_t MaxIntFromFormat(VectorFormat vform);
int64_t MinIntFromFormat(VectorFormat vform);
uint64_t MaxUintFromFormat(VectorFormat vform);
@@ -529,7 +529,7 @@ bool AreAliased(const CPURegister& reg1, const CPURegister& reg2,
// same size, and are of the same type. The system stack pointer may be
// specified. Arguments set to NoReg are ignored, as are any subsequent
// arguments. At least one argument (reg1) must be valid (not NoCPUReg).
bool AreSameSizeAndType(
V8_EXPORT_PRIVATE bool AreSameSizeAndType(
const CPURegister& reg1, const CPURegister& reg2 = NoCPUReg,
const CPURegister& reg3 = NoCPUReg, const CPURegister& reg4 = NoCPUReg,
const CPURegister& reg5 = NoCPUReg, const CPURegister& reg6 = NoCPUReg,
@@ -546,9 +546,10 @@ bool AreSameFormat(const VRegister& reg1, const VRegister& reg2,
// consecutive in the register file. Arguments may be set to NoVReg, and if so,
// subsequent arguments must also be NoVReg. At least one argument (reg1) must
// be valid (not NoVReg).
bool AreConsecutive(const VRegister& reg1, const VRegister& reg2,
const VRegister& reg3 = NoVReg,
const VRegister& reg4 = NoVReg);
V8_EXPORT_PRIVATE bool AreConsecutive(const VRegister& reg1,
const VRegister& reg2,
const VRegister& reg3 = NoVReg,
const VRegister& reg4 = NoVReg);
typedef VRegister FloatRegister;
typedef VRegister DoubleRegister;
@@ -556,7 +557,7 @@ typedef VRegister Simd128Register;
// -----------------------------------------------------------------------------
// Lists of registers.
class CPURegList {
class V8_EXPORT_PRIVATE CPURegList {
public:
template <typename... CPURegisters>
explicit CPURegList(CPURegister reg0, CPURegisters... regs)
+6 -5
View File
@@ -656,10 +656,11 @@ class Simulator : public DecoderVisitor, public SimulatorBase {
USE(size);
}
explicit Simulator(Decoder<DispatchingDecoderVisitor>* decoder,
Isolate* isolate = nullptr, FILE* stream = stderr);
V8_EXPORT_PRIVATE explicit Simulator(
Decoder<DispatchingDecoderVisitor>* decoder, Isolate* isolate = nullptr,
FILE* stream = stderr);
Simulator();
~Simulator();
V8_EXPORT_PRIVATE ~Simulator();
// System functions.
@@ -744,7 +745,7 @@ class Simulator : public DecoderVisitor, public SimulatorBase {
// Accessor to the internal simulator stack area.
uintptr_t StackLimit(uintptr_t c_limit) const;
void ResetState();
V8_EXPORT_PRIVATE void ResetState();
void DoRuntimeCall(Instruction* instr);
@@ -752,7 +753,7 @@ class Simulator : public DecoderVisitor, public SimulatorBase {
static const Instruction* kEndOfSimAddress;
void DecodeInstruction();
void Run();
void RunFrom(Instruction* start);
V8_EXPORT_PRIVATE void RunFrom(Instruction* start);
// Simulation helpers.
template <typename T>
+14 -12
View File
@@ -2967,7 +2967,7 @@ T Simulator::FPMulx(T op1, T op2) {
if ((std::isinf(op1) && (op2 == 0.0)) || (std::isinf(op2) && (op1 == 0.0))) {
// inf * 0.0 returns +/-2.0.
T two = 2.0;
return copysign(1.0, op1) * copysign(1.0, op2) * two;
return std::copysign(1.0, op1) * std::copysign(1.0, op2) * two;
}
return FPMul(op1, op2);
}
@@ -2976,8 +2976,8 @@ template <typename T>
T Simulator::FPMulAdd(T a, T op1, T op2) {
T result = FPProcessNaNs3(a, op1, op2);
T sign_a = copysign(1.0, a);
T sign_prod = copysign(1.0, op1) * copysign(1.0, op2);
T sign_a = std::copysign(1.0, a);
T sign_prod = std::copysign(1.0, op1) * std::copysign(1.0, op2);
bool isinf_prod = std::isinf(op1) || std::isinf(op2);
bool operation_generates_nan =
(std::isinf(op1) && (op2 == 0.0)) || // inf * 0.0
@@ -3012,7 +3012,7 @@ T Simulator::FPMulAdd(T a, T op1, T op2) {
// Work around broken fma implementations for rounded zero results: If a is
// 0.0, the sign of the result is the sign of op1 * op2 before rounding.
if ((a == 0.0) && (result == 0.0)) {
return copysign(0.0, sign_prod);
return std::copysign(0.0, sign_prod);
}
return result;
@@ -3031,8 +3031,8 @@ T Simulator::FPDiv(T op1, T op2) {
if (op2 == 0.0) {
FPProcessException();
if (!std::isnan(op1)) {
double op1_sign = copysign(1.0, op1);
double op2_sign = copysign(1.0, op2);
double op1_sign = std::copysign(1.0, op1);
double op2_sign = std::copysign(1.0, op2);
return static_cast<T>(op1_sign * op2_sign * kFP64PositiveInfinity);
}
}
@@ -3050,7 +3050,7 @@ T Simulator::FPSqrt(T op) {
FPProcessException();
return FPDefaultNaN<T>();
} else {
return sqrt(op);
return std::sqrt(op);
}
}
@@ -3059,7 +3059,8 @@ T Simulator::FPMax(T a, T b) {
T result = FPProcessNaNs(a, b);
if (std::isnan(result)) return result;
if ((a == 0.0) && (b == 0.0) && (copysign(1.0, a) != copysign(1.0, b))) {
if ((a == 0.0) && (b == 0.0) &&
(std::copysign(1.0, a) != std::copysign(1.0, b))) {
// a and b are zero, and the sign differs: return +0.0.
return 0.0;
} else {
@@ -3084,7 +3085,8 @@ T Simulator::FPMin(T a, T b) {
T result = FPProcessNaNs(a, b);
if (std::isnan(result)) return result;
if ((a == 0.0) && (b == 0.0) && (copysign(1.0, a) != copysign(1.0, b))) {
if ((a == 0.0) && (b == 0.0) &&
(std::copysign(1.0, a) != std::copysign(1.0, b))) {
// a and b are zero, and the sign differs: return -0.0.
return -0.0;
} else {
@@ -3516,7 +3518,7 @@ LogicVRegister Simulator::fabs_(VectorFormat vform, LogicVRegister dst,
dst.ClearForWrite(vform);
for (int i = 0; i < LaneCountFromFormat(vform); i++) {
T op = src.Float<T>(i);
if (copysign(1.0, op) < 0.0) {
if (std::copysign(1.0, op) < 0.0) {
op = -op;
}
dst.SetFloat(i, op);
@@ -3865,12 +3867,12 @@ T Simulator::FPRecipSqrtEstimate(T op) {
if (std::isnan(op)) {
return FPProcessNaN(op);
} else if (op == 0.0) {
if (copysign(1.0, op) < 0.0) {
if (std::copysign(1.0, op) < 0.0) {
return kFP64NegativeInfinity;
} else {
return kFP64PositiveInfinity;
}
} else if (copysign(1.0, op) < 0.0) {
} else if (std::copysign(1.0, op) < 0.0) {
FPProcessException();
return FPDefaultNaN<T>();
} else if (std::isinf(op)) {
+2 -2
View File
@@ -33,8 +33,8 @@ int float16classify(float16 value);
// Bit counting.
int CountLeadingZeros(uint64_t value, int width);
int CountLeadingSignBits(int64_t value, int width);
int CountTrailingZeros(uint64_t value, int width);
int CountSetBits(uint64_t value, int width);
V8_EXPORT_PRIVATE int CountTrailingZeros(uint64_t value, int width);
V8_EXPORT_PRIVATE int CountSetBits(uint64_t value, int width);
int LowestSetBitPosition(uint64_t value);
int HighestSetBitPosition(uint64_t value);
uint64_t LargestPowerOf2Divisor(uint64_t value);
+4 -5
View File
@@ -355,11 +355,11 @@ MaybeHandle<Object> AsmJs::InstantiateAsmWasm(Isolate* isolate,
instantiate_timer.Start();
Handle<HeapNumber> uses_bitset(wasm_data->uses_bitset(), isolate);
Handle<Script> script(Script::cast(shared->script()), isolate);
const auto& wasm_engine = isolate->wasm_engine();
// Allocate the WasmModuleObject.
Handle<WasmModuleObject> module =
isolate->wasm_engine()->FinalizeTranslatedAsmJs(isolate, wasm_data,
script);
wasm_engine->FinalizeTranslatedAsmJs(isolate, wasm_data, script);
// TODO(mstarzinger): The position currently points to the module definition
// but should instead point to the instantiation site (more intuitive).
@@ -387,7 +387,7 @@ MaybeHandle<Object> AsmJs::InstantiateAsmWasm(Isolate* isolate,
ReportInstantiationFailure(script, position, "Requires heap buffer");
return MaybeHandle<Object>();
}
memory->set_is_growable(false);
wasm_engine->memory_tracker()->MarkWasmMemoryNotGrowable(memory);
size_t size = memory->byte_length();
// Check the asm.js heap size against the valid limits.
if (!IsValidAsmjsMemorySize(size)) {
@@ -400,8 +400,7 @@ MaybeHandle<Object> AsmJs::InstantiateAsmWasm(Isolate* isolate,
wasm::ErrorThrower thrower(isolate, "AsmJs::Instantiate");
MaybeHandle<Object> maybe_module_object =
isolate->wasm_engine()->SyncInstantiate(isolate, &thrower, module,
foreign, memory);
wasm_engine->SyncInstantiate(isolate, &thrower, module, foreign, memory);
if (maybe_module_object.is_null()) {
// An exception caused by the module start function will be set as pending
// and bypass the {ErrorThrower}, this happens in case of a stack overflow.
+17 -5
View File
@@ -13,6 +13,7 @@
#include "src/asmjs/asm-types.h"
#include "src/base/optional.h"
#include "src/base/overflowing-math.h"
#include "src/conversions-inl.h"
#include "src/flags.h"
#include "src/parsing/scanner.h"
#include "src/wasm/wasm-limits.h"
@@ -319,6 +320,9 @@ int AsmJsParser::FindContinueLabelDepth(AsmJsScanner::token_t label) {
int count = 0;
for (auto it = block_stack_.rbegin(); it != block_stack_.rend();
++it, ++count) {
// A 'continue' statement targets ...
// - The innermost {kLoop} block if no label is given.
// - The matching {kLoop} block (when a label is provided).
if (it->kind == BlockKind::kLoop &&
(label == kTokenNone || it->label == label)) {
return count;
@@ -331,8 +335,12 @@ int AsmJsParser::FindBreakLabelDepth(AsmJsScanner::token_t label) {
int count = 0;
for (auto it = block_stack_.rbegin(); it != block_stack_.rend();
++it, ++count) {
if (it->kind == BlockKind::kRegular &&
(label == kTokenNone || it->label == label)) {
// A 'break' statement targets ...
// - The innermost {kRegular} block if no label is given.
// - The matching {kRegular} or {kNamed} block (when a label is provided).
if ((it->kind == BlockKind::kRegular &&
(label == kTokenNone || it->label == label)) ||
(it->kind == BlockKind::kNamed && it->label == label)) {
return count;
}
}
@@ -520,7 +528,7 @@ void AsmJsParser::ValidateModuleVarFromGlobal(VarInfo* info,
dvalue = -dvalue;
}
DeclareGlobal(info, mutable_variable, AsmType::Float(), kWasmF32,
WasmInitExpr(static_cast<float>(dvalue)));
WasmInitExpr(DoubleToFloat32(dvalue)));
} else if (CheckForUnsigned(&uvalue)) {
dvalue = uvalue;
if (negate) {
@@ -800,6 +808,9 @@ void AsmJsParser::ValidateFunction() {
// End function
current_function_builder_->Emit(kExprEnd);
if (current_function_builder_->GetPosition() > kV8MaxWasmFunctionSize) {
FAIL("Size of function body exceeds internal limit");
}
// Record (or validate) function type.
AsmType* function_type = AsmType::Function(zone(), return_type_);
for (auto t : params) {
@@ -1041,7 +1052,8 @@ void AsmJsParser::ValidateStatement() {
void AsmJsParser::Block() {
bool can_break_to_block = pending_label_ != 0;
if (can_break_to_block) {
Begin(pending_label_);
BareBegin(BlockKind::kNamed, pending_label_);
current_function_builder_->EmitWithU8(kExprBlock, kLocalVoid);
}
pending_label_ = 0;
EXPECT_TOKEN('{');
@@ -1083,8 +1095,8 @@ void AsmJsParser::IfStatement() {
EXPECT_TOKEN('(');
RECURSE(Expression(AsmType::Int()));
EXPECT_TOKEN(')');
BareBegin(BlockKind::kOther);
current_function_builder_->EmitWithU8(kExprIf, kLocalVoid);
BareBegin();
RECURSE(ValidateStatement());
if (Check(TOK(else))) {
current_function_builder_->Emit(kExprElse);
+14 -3
View File
@@ -107,8 +107,20 @@ class AsmJsParser {
VarInfo* var_info;
};
enum class BlockKind { kRegular, kLoop, kOther };
// Distinguish different kinds of blocks participating in {block_stack}. Each
// entry on that stack represents one block in the wasm code, and determines
// which block 'break' and 'continue' target in the current context:
// - kRegular: The target of a 'break' (with & without identifier).
// Pushed by an IterationStatement and a SwitchStatement.
// - kLoop : The target of a 'continue' (with & without identifier).
// Pushed by an IterationStatement.
// - kNamed : The target of a 'break' with a specific identifier.
// Pushed by a BlockStatement.
// - kOther : Only used for internal blocks, can never be targeted.
enum class BlockKind { kRegular, kLoop, kNamed, kOther };
// One entry in the {block_stack}, see {BlockKind} above for details. Blocks
// without a label have {kTokenNone} set as their label.
struct BlockInfo {
BlockKind kind;
AsmJsScanner::token_t label;
@@ -312,8 +324,7 @@ class AsmJsParser {
// Use to set up block stack layers (including synthetic ones for if-else).
// Begin/Loop/End below are implemented with these plus code generation.
void BareBegin(BlockKind kind = BlockKind::kOther,
AsmJsScanner::token_t label = 0);
void BareBegin(BlockKind kind, AsmJsScanner::token_t label = 0);
void BareEnd();
int FindContinueLabelDepth(AsmJsScanner::token_t label);
int FindBreakLabelDepth(AsmJsScanner::token_t label);
+1 -1
View File
@@ -271,7 +271,7 @@ void AsmJsScanner::ConsumeIdentifier(uc32 ch) {
void AsmJsScanner::ConsumeNumber(uc32 ch) {
std::string number;
number = ch;
number.assign(1, ch);
bool has_dot = ch == '.';
bool has_prefix = false;
for (;;) {
-4
View File
@@ -273,10 +273,6 @@ void AssemblerBase::UpdateCodeTarget(intptr_t code_target_index,
code_targets_[code_target_index] = code;
}
void AssemblerBase::ReserveCodeTargetSpace(size_t num_of_code_targets) {
code_targets_.reserve(num_of_code_targets);
}
int Assembler::WriteCodeComments() {
if (!FLAG_code_comments || code_comments_writer_.entry_count() == 0) return 0;
int offset = pc_offset();
+5 -3
View File
@@ -166,6 +166,10 @@ struct V8_EXPORT_PRIVATE AssemblerOptions {
// this flag, the code range must be small enough to fit all offsets into
// the instruction immediates.
bool use_pc_relative_calls_and_jumps = false;
// Enables the collection of information useful for the generation of unwind
// info. This is useful in some platform (Win64) where the unwind info depends
// on a function prologue/epilogue.
bool collect_win64_unwind_info = false;
// Constructs V8-agnostic set of options from current state.
AssemblerOptions EnableV8AgnosticCode() const;
@@ -275,8 +279,6 @@ class V8_EXPORT_PRIVATE AssemblerBase : public Malloced {
Handle<Code> GetCodeTarget(intptr_t code_target_index) const;
// Update to the code target at {code_target_index} to {target}.
void UpdateCodeTarget(intptr_t code_target_index, Handle<Code> target);
// Reserves space in the code target vector.
void ReserveCodeTargetSpace(size_t num_of_code_targets);
// The buffer into which code and relocation info are generated.
std::unique_ptr<AssemblerBuffer> buffer_;
@@ -372,7 +374,7 @@ class PredictableCodeSizeScope {
// Enable a specified feature within a scope.
class CpuFeatureScope {
class V8_EXPORT_PRIVATE CpuFeatureScope {
public:
enum CheckPolicy {
kCheckSupported,
+15 -4
View File
@@ -8,6 +8,7 @@
#include <stdint.h>
#include "src/base/macros.h"
#include "src/base/optional.h"
#include "src/globals.h"
#include "src/pointer-with-payload.h"
@@ -75,8 +76,8 @@ class PerThreadAssertScope {
template <PerIsolateAssertType type, bool allow>
class PerIsolateAssertScope {
public:
explicit PerIsolateAssertScope(Isolate* isolate);
~PerIsolateAssertScope();
V8_EXPORT_PRIVATE explicit PerIsolateAssertScope(Isolate* isolate);
V8_EXPORT_PRIVATE ~PerIsolateAssertScope();
static bool IsAllowed(Isolate* isolate);
@@ -167,10 +168,20 @@ typedef PerThreadAssertScopeDebugOnly<CODE_DEPENDENCY_CHANGE_ASSERT, true>
AllowCodeDependencyChange;
class DisallowHeapAccess {
DisallowHeapAllocation no_heap_allocation_;
DisallowCodeDependencyChange no_dependency_change_;
DisallowHandleAllocation no_handle_allocation_;
DisallowHandleDereference no_handle_dereference_;
DisallowCodeDependencyChange no_dependency_change_;
DisallowHeapAllocation no_heap_allocation_;
};
class DisallowHeapAccessIf {
public:
explicit DisallowHeapAccessIf(bool condition) {
if (condition) maybe_disallow_.emplace();
}
private:
base::Optional<DisallowHeapAccess> maybe_disallow_;
};
// Per-isolate assert scopes.
+2 -1
View File
@@ -2,10 +2,11 @@ set noparent
adamk@chromium.org
bmeurer@chromium.org
gsathya@chromium.org
littledan@chromium.org
marja@chromium.org
mstarzinger@chromium.org
neis@chromium.org
verwaest@chromium.org
# COMPONENT: Blink>JavaScript>Language
# COMPONENT: Blink>JavaScript>Parser
+1 -1
View File
@@ -186,7 +186,7 @@ AstStringConstants::AstStringConstants(Isolate* isolate, uint64_t hash_seed)
: zone_(isolate->allocator(), ZONE_NAME),
string_table_(AstRawString::Compare),
hash_seed_(hash_seed) {
DCHECK(ThreadId::Current().Equals(isolate->thread_id()));
DCHECK_EQ(ThreadId::Current(), isolate->thread_id());
#define F(name, str) \
{ \
const char* data = str; \
+1 -1
View File
@@ -52,7 +52,7 @@ class AstRawString final : public ZoneObject {
: literal_bytes_.length() / 2;
}
bool AsArrayIndex(uint32_t* index) const;
bool IsOneByteEqualTo(const char* data) const;
V8_EXPORT_PRIVATE bool IsOneByteEqualTo(const char* data) const;
uint16_t FirstCharacter() const;
void Internalize(Isolate* isolate);
+4 -4
View File
@@ -683,8 +683,8 @@ void MaterializedLiteral::BuildConstants(Isolate* isolate) {
Handle<TemplateObjectDescription> GetTemplateObject::GetOrBuildDescription(
Isolate* isolate) {
Handle<FixedArray> raw_strings =
isolate->factory()->NewFixedArray(this->raw_strings()->length(), TENURED);
Handle<FixedArray> raw_strings = isolate->factory()->NewFixedArray(
this->raw_strings()->length(), AllocationType::kOld);
bool raw_and_cooked_match = true;
for (int i = 0; i < raw_strings->length(); ++i) {
if (this->cooked_strings()->at(i) == nullptr ||
@@ -697,7 +697,7 @@ Handle<TemplateObjectDescription> GetTemplateObject::GetOrBuildDescription(
Handle<FixedArray> cooked_strings = raw_strings;
if (!raw_and_cooked_match) {
cooked_strings = isolate->factory()->NewFixedArray(
this->cooked_strings()->length(), TENURED);
this->cooked_strings()->length(), AllocationType::kOld);
for (int i = 0; i < cooked_strings->length(); ++i) {
if (this->cooked_strings()->at(i) != nullptr) {
cooked_strings->set(i, *this->cooked_strings()->at(i)->string());
@@ -872,7 +872,7 @@ Handle<Object> Literal::BuildValue(Isolate* isolate) const {
case kSmi:
return handle(Smi::FromInt(smi_), isolate);
case kHeapNumber:
return isolate->factory()->NewNumber(number_, TENURED);
return isolate->factory()->NewNumber(number_, AllocationType::kOld);
case kString:
return string_->string();
case kSymbol:
+8 -7
View File
@@ -228,7 +228,7 @@ class Expression : public AstNode {
bool IsSmiLiteral() const;
// True iff the expression is a literal represented as a number.
bool IsNumberLiteral() const;
V8_EXPORT_PRIVATE bool IsNumberLiteral() const;
// True iff the expression is a string literal.
bool IsStringLiteral() const;
@@ -2233,15 +2233,14 @@ class FunctionLiteral final : public Expression {
return function_literal_id() == kFunctionLiteralIdTopLevel;
}
bool is_wrapped() const { return function_type() == kWrapped; }
LanguageMode language_mode() const;
V8_EXPORT_PRIVATE LanguageMode language_mode() const;
static bool NeedsHomeObject(Expression* expr);
int expected_property_count() {
// Not valid for lazy functions.
DCHECK(ShouldEagerCompile());
return expected_property_count_;
void add_expected_properties(int number_properties) {
expected_property_count_ += number_properties;
}
int expected_property_count() { return expected_property_count_; }
int parameter_count() { return parameter_count_; }
int function_length() { return function_length_; }
@@ -2300,7 +2299,7 @@ class FunctionLiteral final : public Expression {
// function will be called immediately:
// - (function() { ... })();
// - var x = function() { ... }();
bool ShouldEagerCompile() const;
V8_EXPORT_PRIVATE bool ShouldEagerCompile() const;
V8_EXPORT_PRIVATE void SetShouldEagerCompile();
FunctionType function_type() const {
@@ -2394,6 +2393,8 @@ class FunctionLiteral final : public Expression {
: public BitField<bool, RequiresInstanceMembersInitializer::kNext, 1> {};
class OneshotIIFEBit : public BitField<bool, HasBracesField::kNext, 1> {};
// expected_property_count_ is the sum of instance fields and properties.
// It can vary depending on whether a function is lazily or eagerly parsed.
int expected_property_count_;
int parameter_count_;
int function_length_;
+1 -1
View File
@@ -121,7 +121,7 @@ class ModuleDescriptor : public ZoneObject {
// Custom content-based comparer for the below maps, to keep them stable
// across parses.
struct AstRawStringComparer {
struct V8_EXPORT_PRIVATE AstRawStringComparer {
bool operator()(const AstRawString* lhs, const AstRawString* rhs) const;
};
+270 -61
View File
@@ -140,6 +140,16 @@ ModuleScope::ModuleScope(Isolate* isolate, Handle<ScopeInfo> scope_info,
set_language_mode(LanguageMode::kStrict);
}
ClassScope::ClassScope(Zone* zone, Scope* outer_scope)
: Scope(zone, outer_scope, CLASS_SCOPE) {
set_language_mode(LanguageMode::kStrict);
}
ClassScope::ClassScope(Zone* zone, Handle<ScopeInfo> scope_info)
: Scope(zone, CLASS_SCOPE, scope_info) {
set_language_mode(LanguageMode::kStrict);
}
Scope::Scope(Zone* zone, ScopeType scope_type, Handle<ScopeInfo> scope_info)
: zone_(zone),
outer_scope_(nullptr),
@@ -322,6 +332,8 @@ Scope* Scope::DeserializeScopeChain(Isolate* isolate, Zone* zone,
} else if (scope_info->scope_type() == EVAL_SCOPE) {
outer_scope = new (zone)
DeclarationScope(zone, EVAL_SCOPE, handle(scope_info, isolate));
} else if (scope_info->scope_type() == CLASS_SCOPE) {
outer_scope = new (zone) ClassScope(zone, handle(scope_info, isolate));
} else if (scope_info->scope_type() == BLOCK_SCOPE) {
if (scope_info->is_declaration_scope()) {
outer_scope = new (zone)
@@ -391,6 +403,16 @@ const ModuleScope* Scope::AsModuleScope() const {
return static_cast<const ModuleScope*>(this);
}
ClassScope* Scope::AsClassScope() {
DCHECK(is_class_scope());
return static_cast<ClassScope*>(this);
}
const ClassScope* Scope::AsClassScope() const {
DCHECK(is_class_scope());
return static_cast<const ClassScope*>(this);
}
void DeclarationScope::DeclareSloppyBlockFunction(
SloppyBlockFunctionStatement* sloppy_block_function) {
sloppy_block_functions_.Add(sloppy_block_function);
@@ -521,7 +543,7 @@ bool DeclarationScope::Analyze(ParseInfo* info) {
if (!scope->AllocateVariables(info)) return false;
#ifdef DEBUG
if (info->is_native() ? FLAG_print_builtin_scopes : FLAG_print_scopes) {
if (FLAG_print_scopes) {
PrintF("Global scope:\n");
scope->Print();
}
@@ -624,6 +646,8 @@ Scope* Scope::FinalizeBlockScope() {
return this;
}
DCHECK(!is_class_scope());
// Remove this scope from outer scope.
outer_scope()->RemoveInnerScope(this);
@@ -1126,6 +1150,13 @@ bool DeclarationScope::AllocateVariables(ParseInfo* info) {
// to ensure that UpdateNeedsHoleCheck() can detect import variables.
if (is_module_scope()) AsModuleScope()->AllocateModuleVariables();
ClassScope* closest_class_scope = GetClassScope();
if (closest_class_scope != nullptr &&
!closest_class_scope->ResolvePrivateNames(info)) {
DCHECK(info->pending_error_handler()->has_pending_error());
return false;
}
if (!ResolveVariablesRecursively(info)) {
DCHECK(info->pending_error_handler()->has_pending_error());
return false;
@@ -1208,6 +1239,17 @@ int Scope::ContextChainLengthUntilOutermostSloppyEval() const {
return result;
}
ClassScope* Scope::GetClassScope() {
Scope* scope = this;
while (scope != nullptr && !scope->is_class_scope()) {
scope = scope->outer_scope();
}
if (scope != nullptr && scope->is_class_scope()) {
return scope->AsClassScope();
}
return nullptr;
}
DeclarationScope* Scope::GetDeclarationScope() {
Scope* scope = this;
while (!scope->is_declaration_scope()) {
@@ -1345,8 +1387,7 @@ void Scope::AnalyzePartially(DeclarationScope* max_outer_scope,
// Don't copy unresolved references to the script scope, unless it's a
// reference to a private name or method. In that case keep it so we
// can fail later.
if (!max_outer_scope->outer_scope()->is_script_scope() ||
proxy->IsPrivateName()) {
if (!max_outer_scope->outer_scope()->is_script_scope()) {
VariableProxy* copy = ast_node_factory->CopyVariableProxy(proxy);
new_unresolved_list->Add(copy);
}
@@ -1483,6 +1524,8 @@ const char* Header(ScopeType scope_type, FunctionKind function_kind,
case SCRIPT_SCOPE: return "global";
case CATCH_SCOPE: return "catch";
case BLOCK_SCOPE: return is_declaration_scope ? "varblock" : "block";
case CLASS_SCOPE:
return "class";
case WITH_SCOPE: return "with";
}
UNREACHABLE();
@@ -1662,6 +1705,14 @@ void Scope::Print(int n) {
PrintMap(n1, "// dynamic vars:\n", &variables_, false, function);
}
if (is_class_scope()) {
ClassScope* class_scope = AsClassScope();
if (class_scope->rare_data_ != nullptr) {
PrintMap(n1, "// private name vars:\n",
&(class_scope->rare_data_->private_name_map), true, function);
}
}
// Print inner scopes (disable by providing negative n).
if (n >= 0) {
for (Scope* scope = inner_scope_; scope != nullptr;
@@ -1777,7 +1828,6 @@ Variable* Scope::Lookup(VariableProxy* proxy, Scope* scope,
if (mode == kParsedScope && !scope->is_script_scope()) {
return nullptr;
}
if (V8_UNLIKELY(proxy->IsPrivateName())) return nullptr;
// No binding has been found. Declare a variable on the global object.
return scope->AsDeclarationScope()->DeclareDynamicGlobal(
@@ -1864,20 +1914,12 @@ Variable* Scope::LookupSloppyEval(VariableProxy* proxy, Scope* scope,
return var;
}
bool Scope::ResolveVariable(ParseInfo* info, VariableProxy* proxy) {
void Scope::ResolveVariable(ParseInfo* info, VariableProxy* proxy) {
DCHECK(info->script_scope()->is_script_scope());
DCHECK(!proxy->is_resolved());
Variable* var = Lookup<kParsedScope>(proxy, this, nullptr);
if (var == nullptr) {
DCHECK(proxy->IsPrivateName());
info->pending_error_handler()->ReportMessageAt(
proxy->position(), proxy->position() + 1,
MessageTemplate::kInvalidPrivateFieldResolution, proxy->raw_name(),
kSyntaxError);
return false;
}
DCHECK_NOT_NULL(var);
ResolveTo(info, proxy, var);
return true;
}
namespace {
@@ -1941,33 +1983,12 @@ void UpdateNeedsHoleCheck(Variable* var, VariableProxy* proxy, Scope* scope) {
} // anonymous namespace
void Scope::ResolveTo(ParseInfo* info, VariableProxy* proxy, Variable* var) {
#ifdef DEBUG
if (info->is_native()) {
// To avoid polluting the global object in native scripts
// - Variables must not be allocated to the global scope.
DCHECK_NOT_NULL(outer_scope());
// - Variables must be bound locally or unallocated.
if (var->IsGlobalObjectProperty()) {
// The following variable name may be minified. If so, disable
// minification in js2c.py for better output.
Handle<String> name = proxy->raw_name()->string();
FATAL("Unbound variable: '%s' in native script.",
name->ToCString().get());
}
VariableLocation location = var->location();
DCHECK(location == VariableLocation::LOCAL ||
location == VariableLocation::CONTEXT ||
location == VariableLocation::PARAMETER ||
location == VariableLocation::UNALLOCATED);
}
#endif
DCHECK_NOT_NULL(var);
UpdateNeedsHoleCheck(var, proxy, this);
proxy->BindTo(var);
}
bool Scope::ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
void Scope::ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
Scope* end) {
// Resolve the variable in all parsed scopes to force context allocation.
for (; scope != end; scope = scope->outer_scope_) {
@@ -1977,25 +1998,10 @@ bool Scope::ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
if (!var->is_dynamic()) {
var->ForceContextAllocation();
if (proxy->is_assigned()) var->set_maybe_assigned();
return;
}
return true;
}
}
if (!proxy->IsPrivateName()) return true;
// If we're resolving a private name, throw an exception of we didn't manage
// to resolve. In case of eval, also look in all outer scope-info backed
// scopes except for the script scope. Don't throw an exception if a reference
// was found.
Scope* start = scope;
for (; !scope->is_script_scope(); scope = scope->outer_scope_) {
if (scope->LookupInScopeInfo(proxy->raw_name(), start) != nullptr) {
return true;
}
}
return false;
}
bool Scope::ResolveVariablesRecursively(ParseInfo* info) {
@@ -2010,19 +2016,12 @@ bool Scope::ResolveVariablesRecursively(ParseInfo* info) {
if (!end->is_script_scope()) end = end->outer_scope();
for (VariableProxy* proxy : unresolved_list_) {
if (!ResolvePreparsedVariable(proxy, outer_scope(), end)) {
info->pending_error_handler()->ReportMessageAt(
proxy->position(), proxy->position() + 1,
MessageTemplate::kInvalidPrivateFieldResolution, proxy->raw_name(),
kSyntaxError);
DCHECK(proxy->IsPrivateName());
return false;
}
ResolvePreparsedVariable(proxy, outer_scope(), end);
}
} else {
// Resolve unresolved variables for this scope.
for (VariableProxy* proxy : unresolved_list_) {
if (!ResolveVariable(info, proxy)) return false;
ResolveVariable(info, proxy);
}
// Resolve unresolved variables for inner scopes.
@@ -2303,5 +2302,215 @@ int Scope::ContextLocalCount() const {
(is_function_var_in_context ? 1 : 0);
}
Variable* ClassScope::DeclarePrivateName(const AstRawString* name,
bool* was_added) {
Variable* result = EnsureRareData()->private_name_map.Declare(
zone(), this, name, VariableMode::kConst, NORMAL_VARIABLE,
InitializationFlag::kNeedsInitialization,
MaybeAssignedFlag::kMaybeAssigned, was_added);
if (*was_added) {
locals_.Add(result);
}
result->ForceContextAllocation();
return result;
}
Variable* ClassScope::LookupLocalPrivateName(const AstRawString* name) {
if (rare_data_ == nullptr) {
return nullptr;
}
return rare_data_->private_name_map.Lookup(name);
}
UnresolvedList::Iterator ClassScope::GetUnresolvedPrivateNameTail() {
if (rare_data_ == nullptr) {
return UnresolvedList::Iterator();
}
return rare_data_->unresolved_private_names.end();
}
void ClassScope::ResetUnresolvedPrivateNameTail(UnresolvedList::Iterator tail) {
if (rare_data_ == nullptr ||
rare_data_->unresolved_private_names.end() == tail) {
return;
}
bool tail_is_empty = tail == UnresolvedList::Iterator();
if (tail_is_empty) {
// If the saved tail is empty, the list used to be empty, so clear it.
rare_data_->unresolved_private_names.Clear();
} else {
rare_data_->unresolved_private_names.Rewind(tail);
}
}
void ClassScope::MigrateUnresolvedPrivateNameTail(
AstNodeFactory* ast_node_factory, UnresolvedList::Iterator tail) {
if (rare_data_ == nullptr ||
rare_data_->unresolved_private_names.end() == tail) {
return;
}
UnresolvedList migrated_names;
// If the saved tail is empty, the list used to be empty, so we should
// migrate everything after the head.
bool tail_is_empty = tail == UnresolvedList::Iterator();
UnresolvedList::Iterator it =
tail_is_empty ? rare_data_->unresolved_private_names.begin() : tail;
for (; it != rare_data_->unresolved_private_names.end(); ++it) {
VariableProxy* proxy = *it;
VariableProxy* copy = ast_node_factory->CopyVariableProxy(proxy);
migrated_names.Add(copy);
}
// Replace with the migrated copies.
if (tail_is_empty) {
rare_data_->unresolved_private_names.Clear();
} else {
rare_data_->unresolved_private_names.Rewind(tail);
}
rare_data_->unresolved_private_names.Append(std::move(migrated_names));
}
void ClassScope::AddUnresolvedPrivateName(VariableProxy* proxy) {
// During a reparse, already_resolved_ may be true here, because
// the class scope is deserialized while the function scope inside may
// be new.
DCHECK(!proxy->is_resolved());
DCHECK(proxy->IsPrivateName());
EnsureRareData()->unresolved_private_names.Add(proxy);
}
Variable* ClassScope::LookupPrivateNameInScopeInfo(const AstRawString* name) {
DCHECK(!scope_info_.is_null());
DCHECK_NULL(LookupLocalPrivateName(name));
DisallowHeapAllocation no_gc;
String name_handle = *name->string();
VariableMode mode;
InitializationFlag init_flag;
MaybeAssignedFlag maybe_assigned_flag;
int index = ScopeInfo::ContextSlotIndex(*scope_info_, name_handle, &mode,
&init_flag, &maybe_assigned_flag);
if (index < 0) {
return nullptr;
}
DCHECK_EQ(mode, VariableMode::kConst);
DCHECK_EQ(init_flag, InitializationFlag::kNeedsInitialization);
DCHECK_EQ(maybe_assigned_flag, MaybeAssignedFlag::kMaybeAssigned);
// Add the found private name to the map to speed up subsequent
// lookups for the same name.
bool was_added;
Variable* var = DeclarePrivateName(name, &was_added);
DCHECK(was_added);
var->AllocateTo(VariableLocation::CONTEXT, index);
return var;
}
Variable* ClassScope::LookupPrivateName(VariableProxy* proxy) {
DCHECK(!proxy->is_resolved());
for (Scope* scope = this; !scope->is_script_scope();
scope = scope->outer_scope_) {
if (!scope->is_class_scope()) continue; // Only search in class scopes
ClassScope* class_scope = scope->AsClassScope();
// Try finding it in the private name map first, if it can't be found,
// try the deseralized scope info.
Variable* var = class_scope->LookupLocalPrivateName(proxy->raw_name());
if (var == nullptr && !class_scope->scope_info_.is_null()) {
var = class_scope->LookupPrivateNameInScopeInfo(proxy->raw_name());
}
return var;
}
return nullptr;
}
bool ClassScope::ResolvePrivateNames(ParseInfo* info) {
if (rare_data_ == nullptr ||
rare_data_->unresolved_private_names.is_empty()) {
return true;
}
UnresolvedList& list = rare_data_->unresolved_private_names;
for (VariableProxy* proxy : list) {
Variable* var = LookupPrivateName(proxy);
if (var == nullptr) {
Scanner::Location loc = proxy->location();
info->pending_error_handler()->ReportMessageAt(
loc.beg_pos, loc.end_pos,
MessageTemplate::kInvalidPrivateFieldResolution, proxy->raw_name(),
kSyntaxError);
return false;
} else {
var->set_is_used();
proxy->BindTo(var);
}
}
// By now all unresolved private names should be resolved so
// clear the list.
list.Clear();
return true;
}
VariableProxy* ClassScope::ResolvePrivateNamesPartially() {
if (rare_data_ == nullptr ||
rare_data_->unresolved_private_names.is_empty()) {
return nullptr;
}
ClassScope* outer_class_scope =
outer_scope_ == nullptr ? nullptr : outer_scope_->GetClassScope();
UnresolvedList& unresolved = rare_data_->unresolved_private_names;
bool has_private_names = rare_data_->private_name_map.capacity() > 0;
// If the class itself does not have private names, nor does it have
// an outer class scope, then we are certain any private name access
// inside cannot be resolved.
if (!has_private_names && outer_class_scope == nullptr &&
!unresolved.is_empty()) {
return unresolved.first();
}
for (VariableProxy* proxy = unresolved.first(); proxy != nullptr;) {
DCHECK(proxy->IsPrivateName());
VariableProxy* next = proxy->next_unresolved();
unresolved.Remove(proxy);
Variable* var = nullptr;
// If we can find private name in the current class scope, we can bind
// them immediately because it's going to shadow any outer private names.
if (has_private_names) {
var = LookupLocalPrivateName(proxy->raw_name());
if (var != nullptr) {
var->set_is_used();
proxy->BindTo(var);
}
}
// If the current scope does not have declared private names,
// try looking from the outer class scope later.
if (var == nullptr) {
// There's no outer class scope so we are certain that the variable
// cannot be resolved later.
if (outer_class_scope == nullptr) {
return proxy;
}
// The private name may be found later in the outer class scope,
// so push it to the outer sopce.
outer_class_scope->AddUnresolvedPrivateName(proxy);
}
proxy = next;
}
DCHECK(unresolved.is_empty());
return nullptr;
}
} // namespace internal
} // namespace v8
+87 -9
View File
@@ -30,8 +30,11 @@ class Statement;
class StringSet;
class VariableProxy;
typedef base::ThreadedList<VariableProxy, VariableProxy::UnresolvedNext>
UnresolvedList;
// A hash map to support fast variable declaration and lookup.
class VariableMap: public ZoneHashMap {
class VariableMap : public ZoneHashMap {
public:
explicit VariableMap(Zone* zone);
@@ -40,7 +43,7 @@ class VariableMap: public ZoneHashMap {
InitializationFlag initialization_flag,
MaybeAssignedFlag maybe_assigned_flag, bool* was_added);
Variable* Lookup(const AstRawString* name);
V8_EXPORT_PRIVATE Variable* Lookup(const AstRawString* name);
void Remove(Variable* var);
void Add(Zone* zone, Variable* var);
};
@@ -79,13 +82,12 @@ class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
}
#endif
typedef base::ThreadedList<VariableProxy, VariableProxy::UnresolvedNext>
UnresolvedList;
DeclarationScope* AsDeclarationScope();
const DeclarationScope* AsDeclarationScope() const;
ModuleScope* AsModuleScope();
const ModuleScope* AsModuleScope() const;
ClassScope* AsClassScope();
const ClassScope* AsClassScope() const;
class Snapshot final {
public:
@@ -347,9 +349,12 @@ class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
bool is_module_scope() const { return scope_type_ == MODULE_SCOPE; }
bool is_script_scope() const { return scope_type_ == SCRIPT_SCOPE; }
bool is_catch_scope() const { return scope_type_ == CATCH_SCOPE; }
bool is_block_scope() const { return scope_type_ == BLOCK_SCOPE; }
bool is_block_scope() const {
return scope_type_ == BLOCK_SCOPE || scope_type_ == CLASS_SCOPE;
}
bool is_with_scope() const { return scope_type_ == WITH_SCOPE; }
bool is_declaration_scope() const { return is_declaration_scope_; }
bool is_class_scope() const { return scope_type_ == CLASS_SCOPE; }
bool inner_scope_calls_eval() const { return inner_scope_calls_eval_; }
bool IsAsmModule() const;
@@ -456,6 +461,10 @@ class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
// sloppy eval call. One if this->calls_sloppy_eval().
int ContextChainLengthUntilOutermostSloppyEval() const;
// Find the closest class scope in the current scope and outer scopes. If no
// class scope is found, nullptr will be returned.
ClassScope* GetClassScope();
// Find the first function, script, eval or (declaration) block scope. This is
// the scope where var declarations will be hoisted to in the implementation.
DeclarationScope* GetDeclarationScope();
@@ -589,11 +598,10 @@ class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
static Variable* LookupSloppyEval(VariableProxy* proxy, Scope* scope,
Scope* outer_scope_end, Scope* entry_point,
bool force_context_allocation);
static bool ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
static void ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
Scope* end);
void ResolveTo(ParseInfo* info, VariableProxy* proxy, Variable* var);
V8_WARN_UNUSED_RESULT bool ResolveVariable(ParseInfo* info,
VariableProxy* proxy);
void ResolveVariable(ParseInfo* info, VariableProxy* proxy);
V8_WARN_UNUSED_RESULT bool ResolveVariablesRecursively(ParseInfo* info);
// Finds free variables of this scope. This mutates the unresolved variables
@@ -638,6 +646,7 @@ class V8_EXPORT_PRIVATE Scope : public NON_EXPORTED_BASE(ZoneObject) {
void SetDefaults();
friend class DeclarationScope;
friend class ClassScope;
friend class ScopeTestHelper;
Zone* zone_;
@@ -1156,6 +1165,75 @@ class ModuleScope final : public DeclarationScope {
ModuleDescriptor* const module_descriptor_;
};
class V8_EXPORT_PRIVATE ClassScope : public Scope {
public:
ClassScope(Zone* zone, Scope* outer_scope);
// Deserialization.
ClassScope(Zone* zone, Handle<ScopeInfo> scope_info);
// Declare a private name in the private name map and add it to the
// local variables of this scope.
Variable* DeclarePrivateName(const AstRawString* name, bool* was_added);
void AddUnresolvedPrivateName(VariableProxy* proxy);
// Try resolving all unresolved private names found in the current scope.
// Called from DeclarationScope::AllocateVariables() when reparsing a
// method to generate code or when eval() is called to access private names.
// If there are any private names that cannot be resolved, returns false.
V8_WARN_UNUSED_RESULT bool ResolvePrivateNames(ParseInfo* info);
// Called after the entire class literal is parsed.
// - If we are certain a private name cannot be resolve, return that
// variable proxy.
// - If we find the private name in the scope chain, return nullptr.
// If the name is found in the current class scope, resolve it
// immediately.
// - If we are not sure if the private name can be resolved or not yet,
// return nullptr.
VariableProxy* ResolvePrivateNamesPartially();
// Get the current tail of unresolved private names to be used to
// reset the tail.
UnresolvedList::Iterator GetUnresolvedPrivateNameTail();
// Reset the tail of unresolved private names, discard everything
// between the tail passed into this method and the current tail.
void ResetUnresolvedPrivateNameTail(UnresolvedList::Iterator tail);
// Migrate private names added between the tail passed into this method
// and the current tail.
void MigrateUnresolvedPrivateNameTail(AstNodeFactory* ast_node_factory,
UnresolvedList::Iterator tail);
private:
friend class Scope;
// Find the private name declared in the private name map first,
// if it cannot be found there, try scope info if there is any.
// Returns nullptr if it cannot be found.
Variable* LookupPrivateName(VariableProxy* proxy);
// Lookup a private name from the local private name map of the current
// scope.
Variable* LookupLocalPrivateName(const AstRawString* name);
// Lookup a private name from the scope info of the current scope.
Variable* LookupPrivateNameInScopeInfo(const AstRawString* name);
struct RareData : public ZoneObject {
explicit RareData(Zone* zone) : private_name_map(zone) {}
UnresolvedList unresolved_private_names;
VariableMap private_name_map;
};
V8_INLINE RareData* EnsureRareData() {
if (rare_data_ == nullptr) {
rare_data_ = new (zone_) RareData(zone_);
}
return rare_data_;
}
RareData* rare_data_ = nullptr;
};
} // namespace internal
} // namespace v8
+1 -1
View File
@@ -15,7 +15,7 @@ namespace base {
// Helper class representing an address region of certain size.
class AddressRegion {
public:
typedef uintptr_t Address;
using Address = uintptr_t;
AddressRegion() = default;
+6 -6
View File
@@ -39,22 +39,22 @@
namespace v8 {
namespace base {
typedef char Atomic8;
typedef int16_t Atomic16;
typedef int32_t Atomic32;
using Atomic8 = char;
using Atomic16 = int16_t;
using Atomic32 = int32_t;
#if defined(V8_HOST_ARCH_64_BIT)
// We need to be able to go between Atomic64 and AtomicWord implicitly. This
// means Atomic64 and AtomicWord should be the same type on 64-bit.
#if defined(__ILP32__)
typedef int64_t Atomic64;
using Atomic64 = int64_t;
#else
typedef intptr_t Atomic64;
using Atomic64 = intptr_t;
#endif // defined(__ILP32__)
#endif // defined(V8_HOST_ARCH_64_BIT)
// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or
// Atomic64 routines below, depending on your architecture.
typedef intptr_t AtomicWord;
using AtomicWord = intptr_t;
// Atomically execute:
// result = *ptr;
+17 -37
View File
@@ -7,7 +7,6 @@
#include <limits>
#include "src/base/logging.h"
#include "src/base/safe_math.h"
namespace v8 {
namespace base {
@@ -71,49 +70,30 @@ int32_t SignedMod32(int32_t lhs, int32_t rhs) {
return lhs % rhs;
}
int64_t FromCheckedNumeric(const internal::CheckedNumeric<int64_t> value) {
if (value.IsValid())
return value.ValueUnsafe();
// We could return max/min but we don't really expose what the maximum delta
// is. Instead, return max/(-max), which is something that clients can reason
// about.
// TODO(rvargas) crbug.com/332611: don't use internal values.
int64_t limit = std::numeric_limits<int64_t>::max();
if (value.validity() == internal::RANGE_UNDERFLOW)
limit = -limit;
return value.ValueOrDefault(limit);
}
int64_t SignedSaturatedAdd64(int64_t lhs, int64_t rhs) {
internal::CheckedNumeric<int64_t> rv(lhs);
rv += rhs;
return FromCheckedNumeric(rv);
using limits = std::numeric_limits<int64_t>;
// Underflow if {lhs + rhs < min}. In that case, return {min}.
if (rhs < 0 && lhs < limits::min() - rhs) return limits::min();
// Overflow if {lhs + rhs > max}. In that case, return {max}.
if (rhs >= 0 && lhs > limits::max() - rhs) return limits::max();
return lhs + rhs;
}
int64_t SignedSaturatedSub64(int64_t lhs, int64_t rhs) {
internal::CheckedNumeric<int64_t> rv(lhs);
rv -= rhs;
return FromCheckedNumeric(rv);
using limits = std::numeric_limits<int64_t>;
// Underflow if {lhs - rhs < min}. In that case, return {min}.
if (rhs > 0 && lhs < limits::min() + rhs) return limits::min();
// Overflow if {lhs - rhs > max}. In that case, return {max}.
if (rhs <= 0 && lhs > limits::max() + rhs) return limits::max();
return lhs - rhs;
}
bool SignedMulOverflow32(int32_t lhs, int32_t rhs, int32_t* val) {
internal::CheckedNumeric<int32_t> rv(lhs);
rv *= rhs;
int32_t limit = std::numeric_limits<int32_t>::max();
*val = rv.ValueOrDefault(limit);
return !rv.IsValid();
}
bool SignedMulOverflow64(int64_t lhs, int64_t rhs, int64_t* val) {
internal::CheckedNumeric<int64_t> rv(lhs);
rv *= rhs;
int64_t limit = std::numeric_limits<int64_t>::max();
*val = rv.ValueOrDefault(limit);
return !rv.IsValid();
// Compute the result as {int64_t}, then check for overflow.
int64_t result = int64_t{lhs} * int64_t{rhs};
*val = static_cast<int32_t>(result);
using limits = std::numeric_limits<int32_t>;
return result < limits::min() || result > limits::max();
}
} // namespace bits
-15
View File
@@ -19,12 +19,6 @@
namespace v8 {
namespace base {
namespace internal {
template <typename T>
class CheckedNumeric;
}
namespace bits {
// CountPopulation(value) returns the number of bits set in |value|.
@@ -242,11 +236,6 @@ inline bool SignedSubOverflow64(int64_t lhs, int64_t rhs, int64_t* val) {
return ((res ^ lhs) & (res ^ ~rhs) & (1ULL << 63)) != 0;
}
// SignedMulOverflow64(lhs,rhs,val) performs a signed multiplication of |lhs|
// and |rhs| and stores the result into the variable pointed to by |val| and
// returns true if the signed multiplication resulted in an overflow.
V8_BASE_EXPORT bool SignedMulOverflow64(int64_t lhs, int64_t rhs, int64_t* val);
// SignedMulHigh32(lhs, rhs) multiplies two signed 32-bit values |lhs| and
// |rhs|, extracts the most significant 32 bits of the result, and returns
// those.
@@ -295,10 +284,6 @@ inline uint32_t UnsignedMod32(uint32_t lhs, uint32_t rhs) {
}
// Clamp |value| on overflow and underflow conditions.
V8_BASE_EXPORT int64_t
FromCheckedNumeric(const internal::CheckedNumeric<int64_t> value);
// SignedSaturatedAdd64(lhs, rhs) adds |lhs| and |rhs|,
// checks and returns the result.
V8_BASE_EXPORT int64_t SignedSaturatedAdd64(int64_t lhs, int64_t rhs);
+1 -1
View File
@@ -25,7 +25,7 @@ namespace base {
// The implementation is thread-safe.
class V8_BASE_EXPORT BoundedPageAllocator : public v8::PageAllocator {
public:
typedef uintptr_t Address;
using Address = uintptr_t;
BoundedPageAllocator(v8::PageAllocator* page_allocator, Address start,
size_t size, size_t allocate_page_size);
+6 -2
View File
@@ -201,8 +201,12 @@
#define V8_TARGET_ARCH_STORES_RETURN_ADDRESS_ON_STACK false
#endif
// Number of bits to represent the page size for paged spaces. The value of 19
// gives 512Kb bytes per page.
// Number of bits to represent the page size for paged spaces.
#if defined(V8_TARGET_ARCH_PPC) || defined(V8_TARGET_ARCH_PPC64)
// PPC has large (64KB) physical pages.
const int kPageSizeBits = 19;
#else
const int kPageSizeBits = 18;
#endif
#endif // V8_BASE_BUILD_CONFIG_H_
+8 -10
View File
@@ -16,11 +16,11 @@
#include <windows.h>
#include <dbghelp.h>
#include <Shlwapi.h>
#include <stddef.h>
#include <iostream>
#include <memory>
#include <string>
#include "src/base/logging.h"
#include "src/base/macros.h"
@@ -49,12 +49,6 @@ long WINAPI StackDumpExceptionFilter(EXCEPTION_POINTERS* info) { // NOLINT
return EXCEPTION_CONTINUE_SEARCH;
}
void GetExePath(wchar_t* path_out) {
GetModuleFileName(nullptr, path_out, MAX_PATH);
path_out[MAX_PATH - 1] = L'\0';
PathRemoveFileSpec(path_out);
}
bool InitializeSymbols() {
if (g_initialized_symbols) return g_init_error == ERROR_SUCCESS;
g_initialized_symbols = true;
@@ -87,9 +81,13 @@ bool InitializeSymbols() {
}
wchar_t exe_path[MAX_PATH];
GetExePath(exe_path);
std::wstring new_path(std::wstring(symbols_path.get()) + L";" +
std::wstring(exe_path));
GetModuleFileName(nullptr, exe_path, MAX_PATH);
std::wstring exe_path_wstring(exe_path);
// To get the path without the filename, we just need to remove the final
// slash and everything after it.
std::wstring new_path(
std::wstring(symbols_path.get()) + L";" +
exe_path_wstring.substr(0, exe_path_wstring.find_last_of(L"\\/")));
if (!SymSetSearchPathW(GetCurrentProcess(), new_path.c_str())) {
g_init_error = GetLastError();
return false;
+2 -2
View File
@@ -24,8 +24,8 @@ namespace base {
template <typename T, typename S = int>
class Flags final {
public:
typedef T flag_type;
typedef S mask_type;
using flag_type = T;
using mask_type = S;
constexpr Flags() : mask_(0) {}
constexpr Flags(flag_type flag) // NOLINT(runtime/explicit)
+12 -15
View File
@@ -27,7 +27,7 @@ class DefaultAllocationPolicy {
template <typename Key, typename Value, class MatchFun, class AllocationPolicy>
class TemplateHashMapImpl {
public:
typedef TemplateHashMapEntry<Key, Value> Entry;
using Entry = TemplateHashMapEntry<Key, Value>;
// The default capacity. This is used by the call sites which want
// to pass in a non-default AllocationPolicy but want to use the
@@ -389,13 +389,12 @@ class CustomMatcherTemplateHashMapImpl
void*, void*,
HashEqualityThenKeyMatcher<void*, bool (*)(void*, void*)>,
AllocationPolicy> {
typedef TemplateHashMapImpl<
using Base = TemplateHashMapImpl<
void*, void*, HashEqualityThenKeyMatcher<void*, bool (*)(void*, void*)>,
AllocationPolicy>
Base;
AllocationPolicy>;
public:
typedef bool (*MatchFun)(void*, void*);
using MatchFun = bool (*)(void*, void*);
CustomMatcherTemplateHashMapImpl(
MatchFun match, uint32_t capacity = Base::kDefaultHashMapCapacity,
@@ -412,8 +411,8 @@ class CustomMatcherTemplateHashMapImpl
DISALLOW_COPY_AND_ASSIGN(CustomMatcherTemplateHashMapImpl);
};
typedef CustomMatcherTemplateHashMapImpl<DefaultAllocationPolicy>
CustomMatcherHashMap;
using CustomMatcherHashMap =
CustomMatcherTemplateHashMapImpl<DefaultAllocationPolicy>;
// Match function which compares keys directly by equality.
template <typename Key>
@@ -429,9 +428,8 @@ template <typename AllocationPolicy>
class PointerTemplateHashMapImpl
: public TemplateHashMapImpl<void*, void*, KeyEqualityMatcher<void*>,
AllocationPolicy> {
typedef TemplateHashMapImpl<void*, void*, KeyEqualityMatcher<void*>,
AllocationPolicy>
Base;
using Base = TemplateHashMapImpl<void*, void*, KeyEqualityMatcher<void*>,
AllocationPolicy>;
public:
PointerTemplateHashMapImpl(uint32_t capacity = Base::kDefaultHashMapCapacity,
@@ -439,7 +437,7 @@ class PointerTemplateHashMapImpl
: Base(capacity, KeyEqualityMatcher<void*>(), allocator) {}
};
typedef PointerTemplateHashMapImpl<DefaultAllocationPolicy> HashMap;
using HashMap = PointerTemplateHashMapImpl<DefaultAllocationPolicy>;
// A hash map for pointer keys and values with an STL-like interface.
template <class Key, class Value, class MatchFun, class AllocationPolicy>
@@ -447,10 +445,9 @@ class TemplateHashMap
: private TemplateHashMapImpl<void*, void*,
HashEqualityThenKeyMatcher<void*, MatchFun>,
AllocationPolicy> {
typedef TemplateHashMapImpl<void*, void*,
HashEqualityThenKeyMatcher<void*, MatchFun>,
AllocationPolicy>
Base;
using Base = TemplateHashMapImpl<void*, void*,
HashEqualityThenKeyMatcher<void*, MatchFun>,
AllocationPolicy>;
public:
STATIC_ASSERT(sizeof(Key*) == sizeof(void*)); // NOLINT
+4 -4
View File
@@ -57,7 +57,7 @@ namespace {
#if V8_TARGET_LITTLE_ENDIAN
typedef union {
union ieee_double_shape_type {
double value;
struct {
uint32_t lsw;
@@ -66,11 +66,11 @@ typedef union {
struct {
uint64_t w;
} xparts;
} ieee_double_shape_type;
};
#else
typedef union {
union ieee_double_shape_type {
double value;
struct {
uint32_t msw;
@@ -79,7 +79,7 @@ typedef union {
struct {
uint64_t w;
} xparts;
} ieee_double_shape_type;
};
#endif
+12 -12
View File
@@ -13,11 +13,11 @@ namespace base {
template <class Category, class Type, class Diff = std::ptrdiff_t,
class Pointer = Type*, class Reference = Type&>
struct iterator {
typedef Category iterator_category;
typedef Type value_type;
typedef Diff difference_type;
typedef Pointer pointer;
typedef Reference reference;
using iterator_category = Category;
using value_type = Type;
using difference_type = Diff;
using pointer = Pointer;
using reference = Reference;
};
// The intention of the base::iterator_range class is to encapsulate two
@@ -27,13 +27,13 @@ struct iterator {
template <typename ForwardIterator>
class iterator_range {
public:
typedef ForwardIterator iterator;
typedef ForwardIterator const_iterator;
typedef typename std::iterator_traits<iterator>::pointer pointer;
typedef typename std::iterator_traits<iterator>::reference reference;
typedef typename std::iterator_traits<iterator>::value_type value_type;
typedef
typename std::iterator_traits<iterator>::difference_type difference_type;
using iterator = ForwardIterator;
using const_iterator = ForwardIterator;
using pointer = typename std::iterator_traits<iterator>::pointer;
using reference = typename std::iterator_traits<iterator>::reference;
using value_type = typename std::iterator_traits<iterator>::value_type;
using difference_type =
typename std::iterator_traits<iterator>::difference_type;
iterator_range() : begin_(), end_() {}
template <typename ForwardIterator1, typename ForwardIterator2>
+6 -6
View File
@@ -199,8 +199,8 @@ template <typename T,
typename InitOnceTrait = ThreadSafeInitOnceTrait,
typename DestroyTrait = LeakyInstanceTrait<T> >
struct LazyStaticInstance {
typedef LazyInstanceImpl<T, StaticallyAllocatedInstanceTrait<T>,
CreateTrait, InitOnceTrait, DestroyTrait> type;
using type = LazyInstanceImpl<T, StaticallyAllocatedInstanceTrait<T>,
CreateTrait, InitOnceTrait, DestroyTrait>;
};
@@ -210,8 +210,8 @@ template <typename T,
typename DestroyTrait = LeakyInstanceTrait<T> >
struct LazyInstance {
// A LazyInstance is a LazyStaticInstance.
typedef typename LazyStaticInstance<T, CreateTrait, InitOnceTrait,
DestroyTrait>::type type;
using type = typename LazyStaticInstance<T, CreateTrait, InitOnceTrait,
DestroyTrait>::type;
};
@@ -220,8 +220,8 @@ template <typename T,
typename InitOnceTrait = ThreadSafeInitOnceTrait,
typename DestroyTrait = LeakyInstanceTrait<T> >
struct LazyDynamicInstance {
typedef LazyInstanceImpl<T, DynamicallyAllocatedInstanceTrait<T>,
CreateTrait, InitOnceTrait, DestroyTrait> type;
using type = LazyInstanceImpl<T, DynamicallyAllocatedInstanceTrait<T>,
CreateTrait, InitOnceTrait, DestroyTrait>;
};
// LeakyObject<T> wraps an object of type T, which is initialized in the
+7 -10
View File
@@ -10,15 +10,12 @@
#include <sched.h>
#endif
#include "src/base/atomicops.h"
namespace v8 {
namespace base {
void CallOnceImpl(OnceType* once, std::function<void()> init_func) {
AtomicWord state = Acquire_Load(once);
// Fast path. The provided function was already executed.
if (state == ONCE_STATE_DONE) {
if (once->load(std::memory_order_acquire) == ONCE_STATE_DONE) {
return;
}
@@ -29,23 +26,23 @@ void CallOnceImpl(OnceType* once, std::function<void()> init_func) {
//
// First, try to change the state from UNINITIALIZED to EXECUTING_FUNCTION
// atomically.
state = Acquire_CompareAndSwap(
once, ONCE_STATE_UNINITIALIZED, ONCE_STATE_EXECUTING_FUNCTION);
if (state == ONCE_STATE_UNINITIALIZED) {
uint8_t expected = ONCE_STATE_UNINITIALIZED;
if (once->compare_exchange_strong(expected, ONCE_STATE_EXECUTING_FUNCTION,
std::memory_order_acq_rel)) {
// We are the first thread to call this function, so we have to call the
// function.
init_func();
Release_Store(once, ONCE_STATE_DONE);
once->store(ONCE_STATE_DONE, std::memory_order_release);
} else {
// Another thread has already started executing the function. We need to
// wait until it completes the initialization.
while (state == ONCE_STATE_EXECUTING_FUNCTION) {
while (once->load(std::memory_order_acquire) ==
ONCE_STATE_EXECUTING_FUNCTION) {
#ifdef _WIN32
::Sleep(0);
#else
sched_yield();
#endif
state = Acquire_Load(once);
}
}
}
+10 -11
View File
@@ -53,48 +53,47 @@
#define V8_BASE_ONCE_H_
#include <stddef.h>
#include <atomic>
#include <functional>
#include "src/base/atomicops.h"
#include "src/base/base-export.h"
namespace v8 {
namespace base {
typedef AtomicWord OnceType;
using OnceType = std::atomic<uint8_t>;
#define V8_ONCE_INIT 0
#define V8_ONCE_INIT \
{ 0 }
#define V8_DECLARE_ONCE(NAME) ::v8::base::OnceType NAME
enum {
enum : uint8_t {
ONCE_STATE_UNINITIALIZED = 0,
ONCE_STATE_EXECUTING_FUNCTION = 1,
ONCE_STATE_DONE = 2
};
typedef void (*NoArgFunction)();
typedef void (*PointerArgFunction)(void* arg);
using PointerArgFunction = void (*)(void* arg);
template <typename T>
struct OneArgFunction {
typedef void (*type)(T);
using type = void (*)(T);
};
V8_BASE_EXPORT void CallOnceImpl(OnceType* once,
std::function<void()> init_func);
inline void CallOnce(OnceType* once, NoArgFunction init_func) {
if (Acquire_Load(once) != ONCE_STATE_DONE) {
inline void CallOnce(OnceType* once, std::function<void()> init_func) {
if (once->load(std::memory_order_acquire) != ONCE_STATE_DONE) {
CallOnceImpl(once, init_func);
}
}
template <typename Arg>
inline void CallOnce(OnceType* once,
typename OneArgFunction<Arg*>::type init_func, Arg* arg) {
if (Acquire_Load(once) != ONCE_STATE_DONE) {
if (once->load(std::memory_order_acquire) != ONCE_STATE_DONE) {
CallOnceImpl(once, [=]() { init_func(arg); });
}
}
+4 -4
View File
@@ -304,7 +304,7 @@ struct CopyConstructible {};
template <>
struct CopyConstructible<false> {
constexpr CopyConstructible() = default;
constexpr CopyConstructible(const CopyConstructible&) = delete;
constexpr CopyConstructible(const CopyConstructible&) V8_NOEXCEPT = delete;
constexpr CopyConstructible(CopyConstructible&&) V8_NOEXCEPT = default;
CopyConstructible& operator=(const CopyConstructible&) V8_NOEXCEPT = default;
CopyConstructible& operator=(CopyConstructible&&) V8_NOEXCEPT = default;
@@ -317,7 +317,7 @@ template <>
struct MoveConstructible<false> {
constexpr MoveConstructible() = default;
constexpr MoveConstructible(const MoveConstructible&) V8_NOEXCEPT = default;
constexpr MoveConstructible(MoveConstructible&&) = delete;
constexpr MoveConstructible(MoveConstructible&&) V8_NOEXCEPT = delete;
MoveConstructible& operator=(const MoveConstructible&) V8_NOEXCEPT = default;
MoveConstructible& operator=(MoveConstructible&&) V8_NOEXCEPT = default;
};
@@ -330,7 +330,7 @@ struct CopyAssignable<false> {
constexpr CopyAssignable() = default;
constexpr CopyAssignable(const CopyAssignable&) V8_NOEXCEPT = default;
constexpr CopyAssignable(CopyAssignable&&) V8_NOEXCEPT = default;
CopyAssignable& operator=(const CopyAssignable&) = delete;
CopyAssignable& operator=(const CopyAssignable&) V8_NOEXCEPT = delete;
CopyAssignable& operator=(CopyAssignable&&) V8_NOEXCEPT = default;
};
@@ -343,7 +343,7 @@ struct MoveAssignable<false> {
constexpr MoveAssignable(const MoveAssignable&) V8_NOEXCEPT = default;
constexpr MoveAssignable(MoveAssignable&&) V8_NOEXCEPT = default;
MoveAssignable& operator=(const MoveAssignable&) V8_NOEXCEPT = default;
MoveAssignable& operator=(MoveAssignable&&) = delete;
MoveAssignable& operator=(MoveAssignable&&) V8_NOEXCEPT = delete;
};
// Helper to conditionally enable converting constructors and assign operators.
+2 -2
View File
@@ -24,7 +24,7 @@ namespace base {
template <typename signed_type> \
inline signed_type Name##WithWraparound(signed_type a, signed_type b) { \
ASSERT_SIGNED_INTEGER_TYPE(signed_type); \
typedef typename std::make_unsigned<signed_type>::type unsigned_type; \
using unsigned_type = typename std::make_unsigned<signed_type>::type; \
unsigned_type a_unsigned = static_cast<unsigned_type>(a); \
unsigned_type b_unsigned = static_cast<unsigned_type>(b); \
unsigned_type result = a_unsigned OP b_unsigned; \
@@ -57,7 +57,7 @@ inline signed_type NegateWithWraparound(signed_type a) {
template <typename signed_type>
inline signed_type ShlWithWraparound(signed_type a, signed_type b) {
ASSERT_SIGNED_INTEGER_TYPE(signed_type);
typedef typename std::make_unsigned<signed_type>::type unsigned_type;
using unsigned_type = typename std::make_unsigned<signed_type>::type;
const unsigned_type kMask = (sizeof(a) * 8) - 1;
return static_cast<signed_type>(static_cast<unsigned_type>(a) << (b & kMask));
}
+6 -5
View File
@@ -61,9 +61,9 @@ class V8_BASE_EXPORT ConditionVariable final {
// The implementation-defined native handle type.
#if V8_OS_POSIX
typedef pthread_cond_t NativeHandle;
using NativeHandle = pthread_cond_t;
#elif V8_OS_WIN
typedef CONDITION_VARIABLE NativeHandle;
using NativeHandle = CONDITION_VARIABLE;
#endif
NativeHandle& native_handle() {
@@ -89,9 +89,10 @@ class V8_BASE_EXPORT ConditionVariable final {
// MutexGuard lock_guard(&my_mutex);
// my_condvar.Pointer()->Wait(&my_mutex);
// }
typedef LazyStaticInstance<
ConditionVariable, DefaultConstructTrait<ConditionVariable>,
ThreadSafeInitOnceTrait>::type LazyConditionVariable;
using LazyConditionVariable =
LazyStaticInstance<ConditionVariable,
DefaultConstructTrait<ConditionVariable>,
ThreadSafeInitOnceTrait>::type;
#define LAZY_CONDITION_VARIABLE_INITIALIZER LAZY_STATIC_INSTANCE_INITIALIZER
+11 -11
View File
@@ -55,9 +55,9 @@ class V8_BASE_EXPORT Mutex final {
// The implementation-defined native handle type.
#if V8_OS_POSIX
typedef pthread_mutex_t NativeHandle;
using NativeHandle = pthread_mutex_t;
#elif V8_OS_WIN
typedef SRWLOCK NativeHandle;
using NativeHandle = SRWLOCK;
#endif
NativeHandle& native_handle() {
@@ -101,8 +101,8 @@ class V8_BASE_EXPORT Mutex final {
// // Do something.
// }
//
typedef LazyStaticInstance<Mutex, DefaultConstructTrait<Mutex>,
ThreadSafeInitOnceTrait>::type LazyMutex;
using LazyMutex = LazyStaticInstance<Mutex, DefaultConstructTrait<Mutex>,
ThreadSafeInitOnceTrait>::type;
#define LAZY_MUTEX_INITIALIZER LAZY_STATIC_INSTANCE_INITIALIZER
@@ -153,9 +153,9 @@ class V8_BASE_EXPORT RecursiveMutex final {
private:
// The implementation-defined native handle type.
#if V8_OS_POSIX
typedef pthread_mutex_t NativeHandle;
using NativeHandle = pthread_mutex_t;
#elif V8_OS_WIN
typedef CRITICAL_SECTION NativeHandle;
using NativeHandle = CRITICAL_SECTION;
#endif
NativeHandle native_handle_;
@@ -177,9 +177,9 @@ class V8_BASE_EXPORT RecursiveMutex final {
// // Do something.
// }
//
typedef LazyStaticInstance<RecursiveMutex,
DefaultConstructTrait<RecursiveMutex>,
ThreadSafeInitOnceTrait>::type LazyRecursiveMutex;
using LazyRecursiveMutex =
LazyStaticInstance<RecursiveMutex, DefaultConstructTrait<RecursiveMutex>,
ThreadSafeInitOnceTrait>::type;
#define LAZY_RECURSIVE_MUTEX_INITIALIZER LAZY_STATIC_INSTANCE_INITIALIZER
@@ -241,9 +241,9 @@ class V8_BASE_EXPORT SharedMutex final {
private:
// The implementation-defined native handle type.
#if V8_OS_POSIX
typedef pthread_rwlock_t NativeHandle;
using NativeHandle = pthread_rwlock_t;
#elif V8_OS_WIN
typedef SRWLOCK NativeHandle;
using NativeHandle = SRWLOCK;
#endif
NativeHandle native_handle_;
+2
View File
@@ -127,5 +127,7 @@ std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
void OS::SignalCodeMovingGC() {}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+2
View File
@@ -268,5 +268,7 @@ void OS::SignalCodeMovingGC() {
// Nothing to do on Cygwin.
}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+2
View File
@@ -86,5 +86,7 @@ std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
void OS::SignalCodeMovingGC() {}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+2
View File
@@ -163,5 +163,7 @@ int OS::GetUserTime(uint32_t* secs, uint32_t* usecs) {
return 0;
}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+2
View File
@@ -172,5 +172,7 @@ void OS::SignalCodeMovingGC() {
fclose(f);
}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+20
View File
@@ -73,5 +73,25 @@ TimezoneCache* OS::CreateTimezoneCache() {
return new PosixDefaultTimezoneCache();
}
void OS::AdjustSchedulingParams() {
#if V8_TARGET_ARCH_X64 || V8_TARGET_ARCH_IA32
{
// Check availability of scheduling params.
uint32_t val = 0;
size_t valSize = sizeof(val);
int rc = sysctlbyname("kern.tcsm_available", &val, &valSize, NULL, 0);
if (rc < 0 || !val) return;
}
{
// Adjust scheduling params.
uint32_t val = 1;
int rc = sysctlbyname("kern.tcsm_enable", NULL, NULL, &val, sizeof(val));
DCHECK_GE(rc, 0);
USE(rc);
}
#endif
}
} // namespace base
} // namespace v8
+2
View File
@@ -120,5 +120,7 @@ void OS::SignalCodeMovingGC() {
fclose(f);
}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+15 -9
View File
@@ -43,7 +43,7 @@
#include "src/base/utils/random-number-generator.h"
#ifdef V8_FAST_TLS_SUPPORTED
#include "src/base/atomicops.h"
#include <atomic>
#endif
#if V8_OS_MACOSX
@@ -444,15 +444,22 @@ class PosixMemoryMappedFile final : public OS::MemoryMappedFile {
// static
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
if (FILE* file = fopen(name, "r+")) {
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name,
FileMode mode) {
const char* fopen_mode = (mode == FileMode::kReadOnly) ? "r" : "r+";
if (FILE* file = fopen(name, fopen_mode)) {
if (fseek(file, 0, SEEK_END) == 0) {
long size = ftell(file); // NOLINT(runtime/int)
if (size == 0) return new PosixMemoryMappedFile(file, nullptr, 0);
if (size > 0) {
int prot = PROT_READ;
int flags = MAP_PRIVATE;
if (mode == FileMode::kReadWrite) {
prot |= PROT_WRITE;
flags = MAP_SHARED;
}
void* const memory =
mmap(OS::GetRandomMmapAddr(), size, PROT_READ | PROT_WRITE,
MAP_SHARED, fileno(file), 0);
mmap(OS::GetRandomMmapAddr(), size, prot, flags, fileno(file), 0);
if (memory != MAP_FAILED) {
return new PosixMemoryMappedFile(file, memory, size);
}
@@ -463,7 +470,6 @@ OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
return nullptr;
}
// static
OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name,
size_t size, void* initial) {
@@ -815,7 +821,7 @@ static pthread_key_t LocalKeyToPthreadKey(Thread::LocalStorageKey local_key) {
#ifdef V8_FAST_TLS_SUPPORTED
static Atomic32 tls_base_offset_initialized = 0;
static std::atomic<bool> tls_base_offset_initialized{false};
intptr_t kMacTlsBaseOffset = 0;
// It's safe to do the initialization more that once, but it has to be
@@ -851,7 +857,7 @@ static void InitializeTlsBaseOffset() {
kMacTlsBaseOffset = 0;
}
Release_Store(&tls_base_offset_initialized, 1);
tls_base_offset_initialized.store(true, std::memory_order_release);
}
@@ -871,7 +877,7 @@ static void CheckFastTls(Thread::LocalStorageKey key) {
Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
#ifdef V8_FAST_TLS_SUPPORTED
bool check_fast_tls = false;
if (tls_base_offset_initialized == 0) {
if (!tls_base_offset_initialized.load(std::memory_order_acquire)) {
check_fast_tls = true;
InitializeTlsBaseOffset();
}
+2
View File
@@ -146,5 +146,7 @@ std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
void OS::SignalCodeMovingGC() {}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+2
View File
@@ -63,5 +63,7 @@ std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
void OS::SignalCodeMovingGC() {}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+41 -46
View File
@@ -973,27 +973,34 @@ class Win32MemoryMappedFile final : public OS::MemoryMappedFile {
// static
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name,
FileMode mode) {
// Open a physical file.
HANDLE file = CreateFileA(name, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, 0, nullptr);
DWORD access = GENERIC_READ;
if (mode == FileMode::kReadWrite) {
access |= GENERIC_WRITE;
}
HANDLE file = CreateFileA(name, access, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_EXISTING, 0, nullptr);
if (file == INVALID_HANDLE_VALUE) return nullptr;
DWORD size = GetFileSize(file, nullptr);
if (size == 0) return new Win32MemoryMappedFile(file, nullptr, nullptr, 0);
DWORD protection =
(mode == FileMode::kReadOnly) ? PAGE_READONLY : PAGE_READWRITE;
// Create a file mapping for the physical file.
HANDLE file_mapping =
CreateFileMapping(file, nullptr, PAGE_READWRITE, 0, size, nullptr);
CreateFileMapping(file, nullptr, protection, 0, size, nullptr);
if (file_mapping == nullptr) return nullptr;
// Map a view of the file into memory.
void* memory = MapViewOfFile(file_mapping, FILE_MAP_ALL_ACCESS, 0, 0, size);
DWORD view_access =
(mode == FileMode::kReadOnly) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;
void* memory = MapViewOfFile(file_mapping, view_access, 0, 0, size);
return new Win32MemoryMappedFile(file, file_mapping, memory, size);
}
// static
OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name,
size_t size, void* initial) {
@@ -1065,58 +1072,44 @@ Win32MemoryMappedFile::~Win32MemoryMappedFile() {
// DbgHelp isn't supported on MinGW yet
#ifndef __MINGW32__
// DbgHelp.h functions.
typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymInitialize))(IN HANDLE hProcess,
IN PSTR UserSearchPath,
IN BOOL fInvadeProcess);
typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymGetOptions))(VOID);
typedef DWORD (__stdcall *DLL_FUNC_TYPE(SymSetOptions))(IN DWORD SymOptions);
typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSearchPath))(
IN HANDLE hProcess,
OUT PSTR SearchPath,
IN DWORD SearchPathLength);
typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymLoadModule64))(
IN HANDLE hProcess,
IN HANDLE hFile,
IN PSTR ImageName,
IN PSTR ModuleName,
IN DWORD64 BaseOfDll,
IN DWORD SizeOfDll);
typedef BOOL (__stdcall *DLL_FUNC_TYPE(StackWalk64))(
DWORD MachineType,
HANDLE hProcess,
HANDLE hThread,
LPSTACKFRAME64 StackFrame,
PVOID ContextRecord,
using DLL_FUNC_TYPE(SymInitialize) = BOOL(__stdcall*)(IN HANDLE hProcess,
IN PSTR UserSearchPath,
IN BOOL fInvadeProcess);
using DLL_FUNC_TYPE(SymGetOptions) = DWORD(__stdcall*)(VOID);
using DLL_FUNC_TYPE(SymSetOptions) = DWORD(__stdcall*)(IN DWORD SymOptions);
using DLL_FUNC_TYPE(SymGetSearchPath) = BOOL(__stdcall*)(
IN HANDLE hProcess, OUT PSTR SearchPath, IN DWORD SearchPathLength);
using DLL_FUNC_TYPE(SymLoadModule64) = DWORD64(__stdcall*)(
IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName,
IN DWORD64 BaseOfDll, IN DWORD SizeOfDll);
using DLL_FUNC_TYPE(StackWalk64) = BOOL(__stdcall*)(
DWORD MachineType, HANDLE hProcess, HANDLE hThread,
LPSTACKFRAME64 StackFrame, PVOID ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetSymFromAddr64))(
IN HANDLE hProcess,
IN DWORD64 qwAddr,
OUT PDWORD64 pdwDisplacement,
using DLL_FUNC_TYPE(SymGetSymFromAddr64) = BOOL(__stdcall*)(
IN HANDLE hProcess, IN DWORD64 qwAddr, OUT PDWORD64 pdwDisplacement,
OUT PIMAGEHLP_SYMBOL64 Symbol);
typedef BOOL (__stdcall *DLL_FUNC_TYPE(SymGetLineFromAddr64))(
IN HANDLE hProcess,
IN DWORD64 qwAddr,
OUT PDWORD pdwDisplacement,
OUT PIMAGEHLP_LINE64 Line64);
using DLL_FUNC_TYPE(SymGetLineFromAddr64) =
BOOL(__stdcall*)(IN HANDLE hProcess, IN DWORD64 qwAddr,
OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line64);
// DbgHelp.h typedefs. Implementation found in dbghelp.dll.
typedef PVOID (__stdcall *DLL_FUNC_TYPE(SymFunctionTableAccess64))(
using DLL_FUNC_TYPE(SymFunctionTableAccess64) = PVOID(__stdcall*)(
HANDLE hProcess,
DWORD64 AddrBase); // DbgHelp.h typedef PFUNCTION_TABLE_ACCESS_ROUTINE64
typedef DWORD64 (__stdcall *DLL_FUNC_TYPE(SymGetModuleBase64))(
using DLL_FUNC_TYPE(SymGetModuleBase64) = DWORD64(__stdcall*)(
HANDLE hProcess,
DWORD64 AddrBase); // DbgHelp.h typedef PGET_MODULE_BASE_ROUTINE64
// TlHelp32.h functions.
typedef HANDLE (__stdcall *DLL_FUNC_TYPE(CreateToolhelp32Snapshot))(
DWORD dwFlags,
DWORD th32ProcessID);
typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32FirstW))(HANDLE hSnapshot,
LPMODULEENTRY32W lpme);
typedef BOOL (__stdcall *DLL_FUNC_TYPE(Module32NextW))(HANDLE hSnapshot,
using DLL_FUNC_TYPE(CreateToolhelp32Snapshot) =
HANDLE(__stdcall*)(DWORD dwFlags, DWORD th32ProcessID);
using DLL_FUNC_TYPE(Module32FirstW) = BOOL(__stdcall*)(HANDLE hSnapshot,
LPMODULEENTRY32W lpme);
using DLL_FUNC_TYPE(Module32NextW) = BOOL(__stdcall*)(HANDLE hSnapshot,
LPMODULEENTRY32W lpme);
#undef IN
#undef VOID
@@ -1404,5 +1397,7 @@ void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
DCHECK(result);
}
void OS::AdjustSchedulingParams() {}
} // namespace base
} // namespace v8
+7 -2
View File
@@ -188,11 +188,14 @@ class V8_BASE_EXPORT OS {
class V8_BASE_EXPORT MemoryMappedFile {
public:
enum class FileMode { kReadOnly, kReadWrite };
virtual ~MemoryMappedFile() = default;
virtual void* memory() const = 0;
virtual size_t size() const = 0;
static MemoryMappedFile* open(const char* name);
static MemoryMappedFile* open(const char* name,
FileMode mode = FileMode::kReadWrite);
static MemoryMappedFile* create(const char* name, size_t size,
void* initial);
};
@@ -246,6 +249,8 @@ class V8_BASE_EXPORT OS {
static int GetCurrentThreadId();
static void AdjustSchedulingParams();
static void ExitProcess(int exit_code);
private:
@@ -308,7 +313,7 @@ inline void EnsureConsoleOutput() {
class V8_BASE_EXPORT Thread {
public:
// Opaque data type for thread-local storage keys.
typedef int32_t LocalStorageKey;
using LocalStorageKey = int32_t;
class Options {
public:
+5 -5
View File
@@ -50,11 +50,11 @@ class V8_BASE_EXPORT Semaphore final {
bool WaitFor(const TimeDelta& rel_time) V8_WARN_UNUSED_RESULT;
#if V8_OS_MACOSX
typedef semaphore_t NativeHandle;
using NativeHandle = semaphore_t;
#elif V8_OS_POSIX
typedef sem_t NativeHandle;
using NativeHandle = sem_t;
#elif V8_OS_WIN
typedef HANDLE NativeHandle;
using NativeHandle = HANDLE;
#endif
NativeHandle& native_handle() {
@@ -90,8 +90,8 @@ struct CreateSemaphoreTrait {
template <int N>
struct LazySemaphore {
typedef typename LazyDynamicInstance<Semaphore, CreateSemaphoreTrait<N>,
ThreadSafeInitOnceTrait>::type type;
using typename LazyDynamicInstance<Semaphore, CreateSemaphoreTrait<N>,
ThreadSafeInitOnceTrait>::type;
};
#define LAZY_SEMAPHORE_INITIALIZER LAZY_DYNAMIC_INSTANCE_INITIALIZER
+38 -21
View File
@@ -19,7 +19,6 @@
#include <ostream>
#if V8_OS_WIN
#include "src/base/atomicops.h"
#include "src/base/lazy-instance.h"
#include "src/base/win32-headers.h"
#endif
@@ -40,13 +39,23 @@ int64_t ComputeThreadTicks() {
&thread_info_count);
CHECK_EQ(kr, KERN_SUCCESS);
v8::base::CheckedNumeric<int64_t> absolute_micros(
thread_info_data.user_time.seconds +
thread_info_data.system_time.seconds);
absolute_micros *= v8::base::Time::kMicrosecondsPerSecond;
absolute_micros += (thread_info_data.user_time.microseconds +
thread_info_data.system_time.microseconds);
return absolute_micros.ValueOrDie();
// We can add the seconds into a {int64_t} without overflow.
CHECK_LE(thread_info_data.user_time.seconds,
std::numeric_limits<int64_t>::max() -
thread_info_data.system_time.seconds);
int64_t seconds =
thread_info_data.user_time.seconds + thread_info_data.system_time.seconds;
// Multiplying the seconds by {kMicrosecondsPerSecond}, and adding something
// in [0, 2 * kMicrosecondsPerSecond) must result in a valid {int64_t}.
static constexpr int64_t kSecondsLimit =
(std::numeric_limits<int64_t>::max() /
v8::base::Time::kMicrosecondsPerSecond) -
2;
CHECK_GT(kSecondsLimit, seconds);
int64_t micros = seconds * v8::base::Time::kMicrosecondsPerSecond;
micros += (thread_info_data.user_time.microseconds +
thread_info_data.system_time.microseconds);
return micros;
}
#elif V8_OS_POSIX
// Helper function to get results from clock_gettime() and convert to a
@@ -70,8 +79,14 @@ V8_INLINE int64_t ClockNow(clockid_t clk_id) {
if (clock_gettime(clk_id, &ts) != 0) {
UNREACHABLE();
}
v8::base::internal::CheckedNumeric<int64_t> result(ts.tv_sec);
result *= v8::base::Time::kMicrosecondsPerSecond;
// Multiplying the seconds by {kMicrosecondsPerSecond}, and adding something
// in [0, kMicrosecondsPerSecond) must result in a valid {int64_t}.
static constexpr int64_t kSecondsLimit =
(std::numeric_limits<int64_t>::max() /
v8::base::Time::kMicrosecondsPerSecond) -
1;
CHECK_GT(kSecondsLimit, ts.tv_sec);
int64_t result = int64_t{ts.tv_sec} * v8::base::Time::kMicrosecondsPerSecond;
#if defined(V8_OS_AIX)
if (clk_id == CLOCK_THREAD_CPUTIME_ID) {
result += (tc.stime / v8::base::Time::kNanosecondsPerMicrosecond);
@@ -81,7 +96,7 @@ V8_INLINE int64_t ClockNow(clockid_t clk_id) {
#else
result += (ts.tv_nsec / v8::base::Time::kNanosecondsPerMicrosecond);
#endif
return result.ValueOrDie();
return result;
#else // Monotonic clock not supported.
return 0;
#endif
@@ -493,7 +508,7 @@ DWORD (*g_tick_function)(void) = &timeGetTimeWrapper;
// "rollover" counter.
union LastTimeAndRolloversState {
// The state as a single 32-bit opaque value.
base::Atomic32 as_opaque_32;
int32_t as_opaque_32;
// The state as usable values.
struct {
@@ -509,7 +524,7 @@ union LastTimeAndRolloversState {
uint16_t rollovers;
} as_values;
};
base::Atomic32 g_last_time_and_rollovers = 0;
std::atomic<int32_t> g_last_time_and_rollovers{0};
static_assert(sizeof(LastTimeAndRolloversState) <=
sizeof(g_last_time_and_rollovers),
"LastTimeAndRolloversState does not fit in a single atomic word");
@@ -523,12 +538,12 @@ TimeTicks RolloverProtectedNow() {
LastTimeAndRolloversState state;
DWORD now; // DWORD is always unsigned 32 bits.
// Fetch the "now" and "last" tick values, updating "last" with "now" and
// incrementing the "rollovers" counter if the tick-value has wrapped back
// around. Atomic operations ensure that both "last" and "rollovers" are
// always updated together.
int32_t original = g_last_time_and_rollovers.load(std::memory_order_acquire);
while (true) {
// Fetch the "now" and "last" tick values, updating "last" with "now" and
// incrementing the "rollovers" counter if the tick-value has wrapped back
// around. Atomic operations ensure that both "last" and "rollovers" are
// always updated together.
int32_t original = base::Acquire_Load(&g_last_time_and_rollovers);
state.as_opaque_32 = original;
now = g_tick_function();
uint8_t now_8 = static_cast<uint8_t>(now >> 24);
@@ -540,11 +555,13 @@ TimeTicks RolloverProtectedNow() {
// Save the changed state. If the existing value is unchanged from the
// original, exit the loop.
int32_t check = base::Release_CompareAndSwap(&g_last_time_and_rollovers,
original, state.as_opaque_32);
if (check == original) break;
if (g_last_time_and_rollovers.compare_exchange_weak(
original, state.as_opaque_32, std::memory_order_acq_rel)) {
break;
}
// Another thread has done something in between so retry from the top.
// {original} has been updated by the {compare_exchange_weak}.
}
return TimeTicks() +
-1
View File
@@ -14,7 +14,6 @@
#include "src/base/base-export.h"
#include "src/base/bits.h"
#include "src/base/macros.h"
#include "src/base/safe_math.h"
#if V8_OS_WIN
#include "src/base/win32-headers.h"
#endif
+2 -2
View File
@@ -25,7 +25,7 @@ namespace base {
// Not thread-safe.
class V8_BASE_EXPORT RegionAllocator final {
public:
typedef uintptr_t Address;
using Address = uintptr_t;
static constexpr Address kAllocationFailure = static_cast<Address>(-1);
@@ -121,7 +121,7 @@ class V8_BASE_EXPORT RegionAllocator final {
}
};
// All regions ordered by addresses.
typedef std::set<Region*, AddressEndOrder> AllRegionsSet;
using AllRegionsSet = std::set<Region*, AddressEndOrder>;
AllRegionsSet all_regions_;
struct SizeAddressOrder {
-276
View File
@@ -1,276 +0,0 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Slightly adapted for inclusion in V8.
// Copyright 2014 the V8 project authors. All rights reserved.
#ifndef V8_BASE_SAFE_MATH_H_
#define V8_BASE_SAFE_MATH_H_
#include "src/base/safe_math_impl.h"
namespace v8 {
namespace base {
namespace internal {
// CheckedNumeric implements all the logic and operators for detecting integer
// boundary conditions such as overflow, underflow, and invalid conversions.
// The CheckedNumeric type implicitly converts from floating point and integer
// data types, and contains overloads for basic arithmetic operations (i.e.: +,
// -, *, /, %).
//
// The following methods convert from CheckedNumeric to standard numeric values:
// IsValid() - Returns true if the underlying numeric value is valid (i.e. has
// has not wrapped and is not the result of an invalid conversion).
// ValueOrDie() - Returns the underlying value. If the state is not valid this
// call will crash on a CHECK.
// ValueOrDefault() - Returns the current value, or the supplied default if the
// state is not valid.
// ValueFloating() - Returns the underlying floating point value (valid only
// only for floating point CheckedNumeric types).
//
// Bitwise operations are explicitly not supported, because correct
// handling of some cases (e.g. sign manipulation) is ambiguous. Comparison
// operations are explicitly not supported because they could result in a crash
// on a CHECK condition. You should use patterns like the following for these
// operations:
// Bitwise operation:
// CheckedNumeric<int> checked_int = untrusted_input_value;
// int x = checked_int.ValueOrDefault(0) | kFlagValues;
// Comparison:
// CheckedNumeric<size_t> checked_size;
// CheckedNumeric<int> checked_size = untrusted_input_value;
// checked_size = checked_size + HEADER LENGTH;
// if (checked_size.IsValid() && checked_size.ValueOrDie() < buffer_size)
// Do stuff...
template <typename T>
class CheckedNumeric {
public:
typedef T type;
CheckedNumeric() = default;
// Copy constructor.
template <typename Src>
CheckedNumeric(const CheckedNumeric<Src>& rhs)
: state_(rhs.ValueUnsafe(), rhs.validity()) {}
template <typename Src>
CheckedNumeric(Src value, RangeConstraint validity)
: state_(value, validity) {}
// This is not an explicit constructor because we implicitly upgrade regular
// numerics to CheckedNumerics to make them easier to use.
template <typename Src>
CheckedNumeric(Src value) // NOLINT
: state_(value) {
// Argument must be numeric.
STATIC_ASSERT(std::numeric_limits<Src>::is_specialized);
}
// IsValid() is the public API to test if a CheckedNumeric is currently valid.
bool IsValid() const { return validity() == RANGE_VALID; }
// ValueOrDie() The primary accessor for the underlying value. If the current
// state is not valid it will CHECK and crash.
T ValueOrDie() const {
CHECK(IsValid());
return state_.value();
}
// ValueOrDefault(T default_value) A convenience method that returns the
// current value if the state is valid, and the supplied default_value for
// any other state.
T ValueOrDefault(T default_value) const {
return IsValid() ? state_.value() : default_value;
}
// ValueFloating() - Since floating point values include their validity state,
// we provide an easy method for extracting them directly, without a risk of
// crashing on a CHECK.
T ValueFloating() const {
// Argument must be a floating-point value.
STATIC_ASSERT(std::numeric_limits<T>::is_iec559);
return CheckedNumeric<T>::cast(*this).ValueUnsafe();
}
// validity() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now for
// tests and to avoid a big matrix of friend operator overloads. But the
// values it returns are likely to change in the future.
// Returns: current validity state (i.e. valid, overflow, underflow, nan).
// TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
// saturation/wrapping so we can expose this state consistently and implement
// saturated arithmetic.
RangeConstraint validity() const { return state_.validity(); }
// ValueUnsafe() - DO NOT USE THIS IN EXTERNAL CODE - It is public right now
// for tests and to avoid a big matrix of friend operator overloads. But the
// values it returns are likely to change in the future.
// Returns: the raw numeric value, regardless of the current state.
// TODO(jschuh): crbug.com/332611 Figure out and implement semantics for
// saturation/wrapping so we can expose this state consistently and implement
// saturated arithmetic.
T ValueUnsafe() const { return state_.value(); }
// Prototypes for the supported arithmetic operator overloads.
template <typename Src> CheckedNumeric& operator+=(Src rhs);
template <typename Src> CheckedNumeric& operator-=(Src rhs);
template <typename Src> CheckedNumeric& operator*=(Src rhs);
template <typename Src> CheckedNumeric& operator/=(Src rhs);
template <typename Src> CheckedNumeric& operator%=(Src rhs);
CheckedNumeric operator-() const {
RangeConstraint validity;
T value = CheckedNeg(state_.value(), &validity);
// Negation is always valid for floating point.
if (std::numeric_limits<T>::is_iec559)
return CheckedNumeric<T>(value);
validity = GetRangeConstraint(state_.validity() | validity);
return CheckedNumeric<T>(value, validity);
}
CheckedNumeric Abs() const {
RangeConstraint validity;
T value = CheckedAbs(state_.value(), &validity);
// Absolute value is always valid for floating point.
if (std::numeric_limits<T>::is_iec559)
return CheckedNumeric<T>(value);
validity = GetRangeConstraint(state_.validity() | validity);
return CheckedNumeric<T>(value, validity);
}
CheckedNumeric& operator++() {
*this += 1;
return *this;
}
CheckedNumeric operator++(int) {
CheckedNumeric value = *this;
*this += 1;
return value;
}
CheckedNumeric& operator--() {
*this -= 1;
return *this;
}
CheckedNumeric operator--(int) {
CheckedNumeric value = *this;
*this -= 1;
return value;
}
// These static methods behave like a convenience cast operator targeting
// the desired CheckedNumeric type. As an optimization, a reference is
// returned when Src is the same type as T.
template <typename Src>
static CheckedNumeric<T> cast(
Src u,
typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
0) {
return u;
}
template <typename Src>
static CheckedNumeric<T> cast(
const CheckedNumeric<Src>& u,
typename enable_if<!is_same<Src, T>::value, int>::type = 0) {
return u;
}
static const CheckedNumeric<T>& cast(const CheckedNumeric<T>& u) { return u; }
private:
CheckedNumericState<T> state_;
};
// This is the boilerplate for the standard arithmetic operator overloads. A
// macro isn't the prettiest solution, but it beats rewriting these five times.
// Some details worth noting are:
// * We apply the standard arithmetic promotions.
// * We skip range checks for floating points.
// * We skip range checks for destination integers with sufficient range.
// TODO(jschuh): extract these out into templates.
#define BASE_NUMERIC_ARITHMETIC_OPERATORS(NAME, OP, COMPOUND_OP) \
/* Binary arithmetic operator for CheckedNumerics of the same type. */ \
template <typename T> \
CheckedNumeric<typename ArithmeticPromotion<T>::type> operator OP( \
const CheckedNumeric<T>& lhs, const CheckedNumeric<T>& rhs) { \
typedef typename ArithmeticPromotion<T>::type Promotion; \
/* Floating point always takes the fast path */ \
if (std::numeric_limits<T>::is_iec559) \
return CheckedNumeric<T>(lhs.ValueUnsafe() OP rhs.ValueUnsafe()); \
if (IsIntegerArithmeticSafe<Promotion, T, T>::value) \
return CheckedNumeric<Promotion>( \
lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
GetRangeConstraint(rhs.validity() | lhs.validity())); \
RangeConstraint validity = RANGE_VALID; \
T result = Checked##NAME(static_cast<Promotion>(lhs.ValueUnsafe()), \
static_cast<Promotion>(rhs.ValueUnsafe()), \
&validity); \
return CheckedNumeric<Promotion>( \
result, \
GetRangeConstraint(validity | lhs.validity() | rhs.validity())); \
} \
/* Assignment arithmetic operator implementation from CheckedNumeric. */ \
template <typename T> \
template <typename Src> \
CheckedNumeric<T>& CheckedNumeric<T>::operator COMPOUND_OP(Src rhs) { \
*this = CheckedNumeric<T>::cast(*this) OP CheckedNumeric<Src>::cast(rhs); \
return *this; \
} \
/* Binary arithmetic operator for CheckedNumeric of different type. */ \
template <typename T, typename Src> \
CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
const CheckedNumeric<Src>& lhs, const CheckedNumeric<T>& rhs) { \
typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
return CheckedNumeric<Promotion>( \
lhs.ValueUnsafe() OP rhs.ValueUnsafe(), \
GetRangeConstraint(rhs.validity() | lhs.validity())); \
return CheckedNumeric<Promotion>::cast(lhs) \
OP CheckedNumeric<Promotion>::cast(rhs); \
} \
/* Binary arithmetic operator for left CheckedNumeric and right numeric. */ \
template <typename T, typename Src> \
CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
const CheckedNumeric<T>& lhs, Src rhs) { \
typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
return CheckedNumeric<Promotion>(lhs.ValueUnsafe() OP rhs, \
lhs.validity()); \
return CheckedNumeric<Promotion>::cast(lhs) \
OP CheckedNumeric<Promotion>::cast(rhs); \
} \
/* Binary arithmetic operator for right numeric and left CheckedNumeric. */ \
template <typename T, typename Src> \
CheckedNumeric<typename ArithmeticPromotion<T, Src>::type> operator OP( \
Src lhs, const CheckedNumeric<T>& rhs) { \
typedef typename ArithmeticPromotion<T, Src>::type Promotion; \
if (IsIntegerArithmeticSafe<Promotion, T, Src>::value) \
return CheckedNumeric<Promotion>(lhs OP rhs.ValueUnsafe(), \
rhs.validity()); \
return CheckedNumeric<Promotion>::cast(lhs) \
OP CheckedNumeric<Promotion>::cast(rhs); \
}
BASE_NUMERIC_ARITHMETIC_OPERATORS(Add, +, += )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Sub, -, -= )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Mul, *, *= )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Div, /, /= )
BASE_NUMERIC_ARITHMETIC_OPERATORS(Mod, %, %= )
#undef BASE_NUMERIC_ARITHMETIC_OPERATORS
} // namespace internal
using internal::CheckedNumeric;
} // namespace base
} // namespace v8
#endif // V8_BASE_SAFE_MATH_H_
-531
View File
@@ -1,531 +0,0 @@
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Slightly adapted for inclusion in V8.
// Copyright 2014 the V8 project authors. All rights reserved.
#ifndef V8_BASE_SAFE_MATH_IMPL_H_
#define V8_BASE_SAFE_MATH_IMPL_H_
#include <stdint.h>
#include <cmath>
#include <cstdlib>
#include <limits>
#include "src/base/macros.h"
#include "src/base/safe_conversions.h"
namespace v8 {
namespace base {
namespace internal {
// From Chromium's base/template_util.h:
template<class T, T v>
struct integral_constant {
static const T value = v;
typedef T value_type;
typedef integral_constant<T, v> type;
};
template <class T, T v> const T integral_constant<T, v>::value;
typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;
template <class T, class U> struct is_same : public false_type {};
template <class T> struct is_same<T, T> : true_type {};
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T> { typedef T type; };
// </template_util.h>
// Everything from here up to the floating point operations is portable C++,
// but it may not be fast. This code could be split based on
// platform/architecture and replaced with potentially faster implementations.
// Integer promotion templates used by the portable checked integer arithmetic.
template <size_t Size, bool IsSigned>
struct IntegerForSizeAndSign;
template <>
struct IntegerForSizeAndSign<1, true> {
typedef int8_t type;
};
template <>
struct IntegerForSizeAndSign<1, false> {
typedef uint8_t type;
};
template <>
struct IntegerForSizeAndSign<2, true> {
typedef int16_t type;
};
template <>
struct IntegerForSizeAndSign<2, false> {
typedef uint16_t type;
};
template <>
struct IntegerForSizeAndSign<4, true> {
typedef int32_t type;
};
template <>
struct IntegerForSizeAndSign<4, false> {
typedef uint32_t type;
};
template <>
struct IntegerForSizeAndSign<8, true> {
typedef int64_t type;
};
template <>
struct IntegerForSizeAndSign<8, false> {
typedef uint64_t type;
};
// WARNING: We have no IntegerForSizeAndSign<16, *>. If we ever add one to
// support 128-bit math, then the ArithmeticPromotion template below will need
// to be updated (or more likely replaced with a decltype expression).
template <typename Integer>
struct UnsignedIntegerForSize {
typedef typename enable_if<
std::numeric_limits<Integer>::is_integer,
typename IntegerForSizeAndSign<sizeof(Integer), false>::type>::type type;
};
template <typename Integer>
struct SignedIntegerForSize {
typedef typename enable_if<
std::numeric_limits<Integer>::is_integer,
typename IntegerForSizeAndSign<sizeof(Integer), true>::type>::type type;
};
template <typename Integer>
struct TwiceWiderInteger {
typedef typename enable_if<
std::numeric_limits<Integer>::is_integer,
typename IntegerForSizeAndSign<
sizeof(Integer) * 2,
std::numeric_limits<Integer>::is_signed>::type>::type type;
};
template <typename Integer>
struct PositionOfSignBit {
static const typename enable_if<std::numeric_limits<Integer>::is_integer,
size_t>::type value = 8 * sizeof(Integer) - 1;
};
// Helper templates for integer manipulations.
template <typename T>
bool HasSignBit(T x) {
// Cast to unsigned since right shift on signed is undefined.
return !!(static_cast<typename UnsignedIntegerForSize<T>::type>(x) >>
PositionOfSignBit<T>::value);
}
// This wrapper undoes the standard integer promotions.
template <typename T>
T BinaryComplement(T x) {
return ~x;
}
// Here are the actual portable checked integer math implementations.
// TODO(jschuh): Break this code out from the enable_if pattern and find a clean
// way to coalesce things into the CheckedNumericState specializations below.
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer, T>::type
CheckedAdd(T x, T y, RangeConstraint* validity) {
// Since the value of x+y is undefined if we have a signed type, we compute
// it using the unsigned type of the same size.
typedef typename UnsignedIntegerForSize<T>::type UnsignedDst;
UnsignedDst ux = static_cast<UnsignedDst>(x);
UnsignedDst uy = static_cast<UnsignedDst>(y);
UnsignedDst uresult = ux + uy;
// Addition is valid if the sign of (x + y) is equal to either that of x or
// that of y.
if (std::numeric_limits<T>::is_signed) {
if (HasSignBit(BinaryComplement((uresult ^ ux) & (uresult ^ uy))))
*validity = RANGE_VALID;
else // Direction of wrap is inverse of result sign.
*validity = HasSignBit(uresult) ? RANGE_OVERFLOW : RANGE_UNDERFLOW;
} else { // Unsigned is either valid or overflow.
*validity = BinaryComplement(x) >= y ? RANGE_VALID : RANGE_OVERFLOW;
}
return static_cast<T>(uresult);
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer, T>::type
CheckedSub(T x, T y, RangeConstraint* validity) {
// Since the value of x+y is undefined if we have a signed type, we compute
// it using the unsigned type of the same size.
typedef typename UnsignedIntegerForSize<T>::type UnsignedDst;
UnsignedDst ux = static_cast<UnsignedDst>(x);
UnsignedDst uy = static_cast<UnsignedDst>(y);
UnsignedDst uresult = ux - uy;
// Subtraction is valid if either x and y have same sign, or (x-y) and x have
// the same sign.
if (std::numeric_limits<T>::is_signed) {
if (HasSignBit(BinaryComplement((uresult ^ ux) & (ux ^ uy))))
*validity = RANGE_VALID;
else // Direction of wrap is inverse of result sign.
*validity = HasSignBit(uresult) ? RANGE_OVERFLOW : RANGE_UNDERFLOW;
} else { // Unsigned is either valid or underflow.
*validity = x >= y ? RANGE_VALID : RANGE_UNDERFLOW;
}
return static_cast<T>(uresult);
}
// Integer multiplication is a bit complicated. In the fast case we just
// we just promote to a twice wider type, and range check the result. In the
// slow case we need to manually check that the result won't be truncated by
// checking with division against the appropriate bound.
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && sizeof(T) * 2 <= sizeof(uintmax_t),
T>::type
CheckedMul(T x, T y, RangeConstraint* validity) {
typedef typename TwiceWiderInteger<T>::type IntermediateType;
IntermediateType tmp =
static_cast<IntermediateType>(x) * static_cast<IntermediateType>(y);
*validity = DstRangeRelationToSrcRange<T>(tmp);
return static_cast<T>(tmp);
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer &&
std::numeric_limits<T>::is_signed &&
(sizeof(T) * 2 > sizeof(uintmax_t)),
T>::type
CheckedMul(T x, T y, RangeConstraint* validity) {
// If either side is zero then the result will be zero.
if (!x || !y) {
return RANGE_VALID;
} else if (x > 0) {
if (y > 0)
*validity =
x <= std::numeric_limits<T>::max() / y ? RANGE_VALID : RANGE_OVERFLOW;
else
*validity = y >= std::numeric_limits<T>::min() / x ? RANGE_VALID
: RANGE_UNDERFLOW;
} else {
if (y > 0)
*validity = x >= std::numeric_limits<T>::min() / y ? RANGE_VALID
: RANGE_UNDERFLOW;
else
*validity =
y >= std::numeric_limits<T>::max() / x ? RANGE_VALID : RANGE_OVERFLOW;
}
return x * y;
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_integer &&
!std::numeric_limits<T>::is_signed &&
(sizeof(T) * 2 > sizeof(uintmax_t)),
T>::type
CheckedMul(T x, T y, RangeConstraint* validity) {
*validity = (y == 0 || x <= std::numeric_limits<T>::max() / y)
? RANGE_VALID
: RANGE_OVERFLOW;
return x * y;
}
// Division just requires a check for an invalid negation on signed min/-1.
template <typename T>
T CheckedDiv(
T x,
T y,
RangeConstraint* validity,
typename enable_if<std::numeric_limits<T>::is_integer, int>::type = 0) {
if (std::numeric_limits<T>::is_signed && x == std::numeric_limits<T>::min() &&
y == static_cast<T>(-1)) {
*validity = RANGE_OVERFLOW;
return std::numeric_limits<T>::min();
}
*validity = RANGE_VALID;
return x / y;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,
T>::type
CheckedMod(T x, T y, RangeConstraint* validity) {
*validity = y > 0 ? RANGE_VALID : RANGE_INVALID;
return x % y;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,
T>::type
CheckedMod(T x, T y, RangeConstraint* validity) {
*validity = RANGE_VALID;
return x % y;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,
T>::type
CheckedNeg(T value, RangeConstraint* validity) {
*validity =
value != std::numeric_limits<T>::min() ? RANGE_VALID : RANGE_OVERFLOW;
// The negation of signed min is min, so catch that one.
return -value;
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,
T>::type
CheckedNeg(T value, RangeConstraint* validity) {
// The only legal unsigned negation is zero.
*validity = value ? RANGE_UNDERFLOW : RANGE_VALID;
return static_cast<T>(
-static_cast<typename SignedIntegerForSize<T>::type>(value));
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && std::numeric_limits<T>::is_signed,
T>::type
CheckedAbs(T value, RangeConstraint* validity) {
*validity =
value != std::numeric_limits<T>::min() ? RANGE_VALID : RANGE_OVERFLOW;
return std::abs(value);
}
template <typename T>
typename enable_if<
std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed,
T>::type
CheckedAbs(T value, RangeConstraint* validity) {
// Absolute value of a positive is just its identiy.
*validity = RANGE_VALID;
return value;
}
// These are the floating point stubs that the compiler needs to see. Only the
// negation operation is ever called.
#define BASE_FLOAT_ARITHMETIC_STUBS(NAME) \
template <typename T> \
typename enable_if<std::numeric_limits<T>::is_iec559, T>::type \
Checked##NAME(T, T, RangeConstraint*) { \
UNREACHABLE(); \
return 0; \
}
BASE_FLOAT_ARITHMETIC_STUBS(Add)
BASE_FLOAT_ARITHMETIC_STUBS(Sub)
BASE_FLOAT_ARITHMETIC_STUBS(Mul)
BASE_FLOAT_ARITHMETIC_STUBS(Div)
BASE_FLOAT_ARITHMETIC_STUBS(Mod)
#undef BASE_FLOAT_ARITHMETIC_STUBS
template <typename T>
typename enable_if<std::numeric_limits<T>::is_iec559, T>::type CheckedNeg(
T value,
RangeConstraint*) {
return -value;
}
template <typename T>
typename enable_if<std::numeric_limits<T>::is_iec559, T>::type CheckedAbs(
T value,
RangeConstraint*) {
return std::abs(value);
}
// Floats carry around their validity state with them, but integers do not. So,
// we wrap the underlying value in a specialization in order to hide that detail
// and expose an interface via accessors.
enum NumericRepresentation {
NUMERIC_INTEGER,
NUMERIC_FLOATING,
NUMERIC_UNKNOWN
};
template <typename NumericType>
struct GetNumericRepresentation {
static const NumericRepresentation value =
std::numeric_limits<NumericType>::is_integer
? NUMERIC_INTEGER
: (std::numeric_limits<NumericType>::is_iec559 ? NUMERIC_FLOATING
: NUMERIC_UNKNOWN);
};
template <typename T, NumericRepresentation type =
GetNumericRepresentation<T>::value>
class CheckedNumericState {};
// Integrals require quite a bit of additional housekeeping to manage state.
template <typename T>
class CheckedNumericState<T, NUMERIC_INTEGER> {
private:
T value_;
RangeConstraint validity_;
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
CheckedNumericState() : value_(0), validity_(RANGE_VALID) {}
template <typename Src>
CheckedNumericState(Src value, RangeConstraint validity)
: value_(value),
validity_(GetRangeConstraint(validity |
DstRangeRelationToSrcRange<T>(value))) {
// Argument must be numeric.
STATIC_ASSERT(std::numeric_limits<Src>::is_specialized);
}
// Copy constructor.
template <typename Src>
CheckedNumericState(const CheckedNumericState<Src>& rhs)
: value_(static_cast<T>(rhs.value())),
validity_(GetRangeConstraint(
rhs.validity() | DstRangeRelationToSrcRange<T>(rhs.value()))) {}
template <typename Src>
explicit CheckedNumericState(
Src value,
typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
0)
: value_(static_cast<T>(value)),
validity_(DstRangeRelationToSrcRange<T>(value)) {}
RangeConstraint validity() const { return validity_; }
T value() const { return value_; }
};
// Floating points maintain their own validity, but need translation wrappers.
template <typename T>
class CheckedNumericState<T, NUMERIC_FLOATING> {
private:
T value_;
public:
template <typename Src, NumericRepresentation type>
friend class CheckedNumericState;
CheckedNumericState() : value_(0.0) {}
template <typename Src>
CheckedNumericState(
Src value,
RangeConstraint validity,
typename enable_if<std::numeric_limits<Src>::is_integer, int>::type = 0) {
switch (DstRangeRelationToSrcRange<T>(value)) {
case RANGE_VALID:
value_ = static_cast<T>(value);
break;
case RANGE_UNDERFLOW:
value_ = -std::numeric_limits<T>::infinity();
break;
case RANGE_OVERFLOW:
value_ = std::numeric_limits<T>::infinity();
break;
case RANGE_INVALID:
value_ = std::numeric_limits<T>::quiet_NaN();
break;
}
}
template <typename Src>
explicit CheckedNumericState(
Src value,
typename enable_if<std::numeric_limits<Src>::is_specialized, int>::type =
0)
: value_(static_cast<T>(value)) {}
// Copy constructor.
template <typename Src>
CheckedNumericState(const CheckedNumericState<Src>& rhs)
: value_(static_cast<T>(rhs.value())) {}
RangeConstraint validity() const {
return GetRangeConstraint(value_ <= std::numeric_limits<T>::max(),
value_ >= -std::numeric_limits<T>::max());
}
T value() const { return value_; }
};
// For integers less than 128-bit and floats 32-bit or larger, we can distil
// C/C++ arithmetic promotions down to two simple rules:
// 1. The type with the larger maximum exponent always takes precedence.
// 2. The resulting type must be promoted to at least an int.
// The following template specializations implement that promotion logic.
enum ArithmeticPromotionCategory {
LEFT_PROMOTION,
RIGHT_PROMOTION,
DEFAULT_PROMOTION
};
template <typename Lhs,
typename Rhs = Lhs,
ArithmeticPromotionCategory Promotion =
(MaxExponent<Lhs>::value > MaxExponent<Rhs>::value)
? (MaxExponent<Lhs>::value > MaxExponent<int>::value
? LEFT_PROMOTION
: DEFAULT_PROMOTION)
: (MaxExponent<Rhs>::value > MaxExponent<int>::value
? RIGHT_PROMOTION
: DEFAULT_PROMOTION) >
struct ArithmeticPromotion;
template <typename Lhs, typename Rhs>
struct ArithmeticPromotion<Lhs, Rhs, LEFT_PROMOTION> {
typedef Lhs type;
};
template <typename Lhs, typename Rhs>
struct ArithmeticPromotion<Lhs, Rhs, RIGHT_PROMOTION> {
typedef Rhs type;
};
template <typename Lhs, typename Rhs>
struct ArithmeticPromotion<Lhs, Rhs, DEFAULT_PROMOTION> {
typedef int type;
};
// We can statically check if operations on the provided types can wrap, so we
// can skip the checked operations if they're not needed. So, for an integer we
// care if the destination type preserves the sign and is twice the width of
// the source.
template <typename T, typename Lhs, typename Rhs>
struct IsIntegerArithmeticSafe {
static const bool value = !std::numeric_limits<T>::is_iec559 &&
StaticDstRangeRelationToSrcRange<T, Lhs>::value ==
NUMERIC_RANGE_CONTAINED &&
sizeof(T) >= (2 * sizeof(Lhs)) &&
StaticDstRangeRelationToSrcRange<T, Rhs>::value !=
NUMERIC_RANGE_CONTAINED &&
sizeof(T) >= (2 * sizeof(Rhs));
};
} // namespace internal
} // namespace base
} // namespace v8
#endif // V8_BASE_SAFE_MATH_IMPL_H_
+1
View File
@@ -26,6 +26,7 @@ class SmallVector {
static constexpr size_t kInlineSize = kSize;
SmallVector() = default;
explicit SmallVector(size_t size) { resize_no_init(size); }
SmallVector(const SmallVector& other) V8_NOEXCEPT { *this = other; }
SmallVector(SmallVector&& other) V8_NOEXCEPT { *this = std::move(other); }
Loaded 100 of 1302 files, more files were not shown because too many files have changed in this diff. Show more