diff --git a/LICENSE b/LICENSE index f87654b61c3dbf..d17113b221c0c3 100644 --- a/LICENSE +++ b/LICENSE @@ -1070,106 +1070,3 @@ The externally maintained libraries used by Node.js are: (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ - -- v8_inspector, located at deps/v8_inspector/third_party/v8_inspector, is licensed as follows: - """ - // Copyright 2015 The Chromium Authors. All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions are - // met: - // - // * Redistributions of source code must retain the above copyright - // notice, this list of conditions and the following disclaimer. - // * Redistributions in binary form must reproduce the above - // copyright notice, this list of conditions and the following disclaimer - // in the documentation and/or other materials provided with the - // distribution. - // * Neither the name of Google Inc. nor the names of its - // contributors may be used to endorse or promote products derived from - // this software without specific prior written permission. - // - // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - """ - -- jinja2, located at deps/v8_inspector/third_party/jinja2, is licensed as follows: - """ - Copyright (c) 2009 by the Jinja Team, see AUTHORS for more details. - - Some rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - - * The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - """ - -- markupsafe, located at deps/v8_inspector/third_party/markupsafe, is licensed as follows: - """ - Copyright (c) 2010 by Armin Ronacher and contributors. See AUTHORS - for more details. - - Some rights reserved. - - Redistribution and use in source and binary forms of the software as well - as documentation, with or without modification, are permitted provided - that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - - * The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND - CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT - NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER - OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE AND DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH - DAMAGE. - """ diff --git a/configure b/configure index 50078df43a9ed5..e1e8ab5a861c29 100755 --- a/configure +++ b/configure @@ -1283,7 +1283,7 @@ def configure_inspector(o): disable_inspector = (options.without_inspector or options.with_intl in (None, 'none') or options.without_ssl) - o['variables']['v8_inspector'] = b(not disable_inspector) + o['variables']['v8_enable_inspector'] = 0 if disable_inspector else 1 output = { 'variables': {}, diff --git a/deps/v8/.gitignore b/deps/v8/.gitignore index 29fd9226dee7b0..cd72bebbd6b12d 100644 --- a/deps/v8/.gitignore +++ b/deps/v8/.gitignore @@ -65,17 +65,9 @@ shell_g !/testing/gtest/include/gtest /testing/gtest/include/gtest/* !/testing/gtest/include/gtest/gtest_prod.h -/third_party -/third_party/android_tools -/third_party/cygwin -/third_party/icu -/third_party/instrumented_libraries -/third_party/inspector_protocol -/third_party/jinga2 -/third_party/llvm -/third_party/llvm-build -/third_party/markupsafe -/third_party/WebKit +/third_party/* +!/third_party/binutils +!/third_party/inspector_protocol /tools/clang /tools/gcmole/gcmole-tools /tools/gcmole/gcmole-tools.tar.gz @@ -109,4 +101,6 @@ v8.ignition_dispatches_table.json /test/fuzzer/wasm.tar.gz /test/fuzzer/wasm_asmjs.tar.gz /src/inspector/build/closure-compiler.tar.gz -/src/inspector/build/closure-compiler \ No newline at end of file +/src/inspector/build/closure-compiler +!/third_party/jinja2 +!/third_party/markupsafe diff --git a/deps/v8/AUTHORS b/deps/v8/AUTHORS index 0229c9259e5c73..476d0c36328c18 100644 --- a/deps/v8/AUTHORS +++ b/deps/v8/AUTHORS @@ -65,6 +65,7 @@ Franziska Hinkelmann Geoffrey Garside Gwang Yoon Hwang Han Choongwoo +Henrique Ferreiro Hirofumi Mako Honggyu Kim Ioseb Dzmanashvili @@ -111,6 +112,7 @@ Robert Mustacchi Robert Nagy Ryan Dahl Sakthipriyan Vairamani (thefourtheye) +Sander Mathijs van Veen Sandro Santilli Sanjoy Das Seo Sanghyeon diff --git a/deps/v8/BUILD.gn b/deps/v8/BUILD.gn index 06870b6039f2b0..8587356ddcca34 100644 --- a/deps/v8/BUILD.gn +++ b/deps/v8/BUILD.gn @@ -43,10 +43,6 @@ declare_args() { # Sets -dENABLE_HANDLE_ZAPPING. v8_enable_handle_zapping = is_debug - # Enable ECMAScript Internationalization API. Enabling this feature will - # add a dependency on the ICU library. - v8_enable_i18n_support = true - # Enable slow dchecks. v8_enable_slow_dchecks = false @@ -65,6 +61,9 @@ declare_args() { # Switches off inlining in V8. v8_no_inline = false + # Override OS page size when generating snapshot + v8_os_page_size = "0" + # Similar to vfp but on MIPS. v8_can_use_fpu_instructions = true @@ -128,6 +127,20 @@ config("internal_config_base") { # This config should be applied to code using the libplatform. config("libplatform_config") { include_dirs = [ "include" ] + if (is_component_build) { + defines = [ "USING_V8_PLATFORM_SHARED" ] + } +} + +# This config should be applied to code using the libbase. +config("libbase_config") { + if (is_component_build) { + defines = [ "USING_V8_BASE_SHARED" ] + } + libs = [] + if (is_android && current_toolchain != host_toolchain) { + libs += [ "log" ] + } } # This config should be applied to code using the libsampler. @@ -145,10 +158,6 @@ config("external_config") { if (v8_enable_inspector_override) { include_dirs += [ "$target_gen_dir/include" ] } - libs = [] - if (is_android && current_toolchain != host_toolchain) { - libs += [ "log" ] - } } # This config should only be applied to code that needs to be explicitly @@ -361,6 +370,20 @@ config("toolchain") { "-fno-inline", ] } + + if (is_clang) { + cflags += [ + "-Wsign-compare", + + # TODO(hans): Remove once http://crbug.com/428099 is resolved. + "-Winconsistent-missing-override", + ] + + if (v8_current_cpu == "x64" || v8_current_cpu == "arm64" || + v8_current_cpu == "mips64el") { + cflags += [ "-Wshorten-64-to-32" ] + } + } } ############################################################################### @@ -388,8 +411,6 @@ action("js2c") { "src/js/symbol.js", "src/js/array.js", "src/js/string.js", - "src/js/math.js", - "src/js/regexp.js", "src/js/arraybuffer.js", "src/js/typedarray.js", "src/js/collection.js", @@ -397,7 +418,6 @@ action("js2c") { "src/js/collection-iterator.js", "src/js/promise.js", "src/js/messages.js", - "src/js/array-iterator.js", "src/js/templates.js", "src/js/spread.js", "src/js/proxy.js", @@ -662,6 +682,13 @@ action("run_mksnapshot") { ] } + if (v8_os_page_size != "0") { + args += [ + "--v8_os_page_size", + v8_os_page_size, + ] + } + if (v8_use_external_startup_data) { outputs += [ "$root_out_dir/snapshot_blob.bin" ] args += [ @@ -715,6 +742,7 @@ action("v8_dump_build_config") { "is_tsan=$is_tsan", "target_cpu=\"$target_cpu\"", "v8_enable_i18n_support=$v8_enable_i18n_support", + "v8_enable_inspector=$v8_enable_inspector_override", "v8_target_cpu=\"$v8_target_cpu\"", "v8_use_snapshot=$v8_use_snapshot", ] @@ -863,6 +891,8 @@ v8_source_set("v8_base") { "src/asmjs/asm-types.h", "src/asmjs/asm-wasm-builder.cc", "src/asmjs/asm-wasm-builder.h", + "src/asmjs/switch-logic.cc", + "src/asmjs/switch-logic.h", "src/assembler.cc", "src/assembler.h", "src/assert-scope.cc", @@ -930,6 +960,7 @@ v8_source_set("v8_base") { "src/builtins/builtins-math.cc", "src/builtins/builtins-number.cc", "src/builtins/builtins-object.cc", + "src/builtins/builtins-promise.cc", "src/builtins/builtins-proxy.cc", "src/builtins/builtins-reflect.cc", "src/builtins/builtins-regexp.cc", @@ -969,6 +1000,8 @@ v8_source_set("v8_base") { "src/compilation-statistics.h", "src/compiler-dispatcher/compiler-dispatcher-job.cc", "src/compiler-dispatcher/compiler-dispatcher-job.h", + "src/compiler-dispatcher/compiler-dispatcher-tracer.cc", + "src/compiler-dispatcher/compiler-dispatcher-tracer.h", "src/compiler-dispatcher/optimizing-compile-dispatcher.cc", "src/compiler-dispatcher/optimizing-compile-dispatcher.h", "src/compiler.cc", @@ -1007,6 +1040,8 @@ v8_source_set("v8_base") { "src/compiler/common-operator-reducer.h", "src/compiler/common-operator.cc", "src/compiler/common-operator.h", + "src/compiler/compiler-source-position-table.cc", + "src/compiler/compiler-source-position-table.h", "src/compiler/control-builders.cc", "src/compiler/control-builders.h", "src/compiler/control-equivalence.cc", @@ -1145,14 +1180,14 @@ v8_source_set("v8_base") { "src/compiler/scheduler.h", "src/compiler/select-lowering.cc", "src/compiler/select-lowering.h", + "src/compiler/simd-scalar-lowering.cc", + "src/compiler/simd-scalar-lowering.h", "src/compiler/simplified-lowering.cc", "src/compiler/simplified-lowering.h", "src/compiler/simplified-operator-reducer.cc", "src/compiler/simplified-operator-reducer.h", "src/compiler/simplified-operator.cc", "src/compiler/simplified-operator.h", - "src/compiler/source-position.cc", - "src/compiler/source-position.h", "src/compiler/state-values-utils.cc", "src/compiler/state-values-utils.h", "src/compiler/store-store-elimination.cc", @@ -1177,8 +1212,8 @@ v8_source_set("v8_base") { "src/compiler/wasm-compiler.cc", "src/compiler/wasm-compiler.h", "src/compiler/wasm-linkage.cc", - "src/compiler/zone-pool.cc", - "src/compiler/zone-pool.h", + "src/compiler/zone-stats.cc", + "src/compiler/zone-stats.h", "src/context-measure.cc", "src/context-measure.h", "src/contexts-inl.h", @@ -1218,8 +1253,6 @@ v8_source_set("v8_base") { "src/crankshaft/hydrogen-instructions.h", "src/crankshaft/hydrogen-load-elimination.cc", "src/crankshaft/hydrogen-load-elimination.h", - "src/crankshaft/hydrogen-mark-deoptimize.cc", - "src/crankshaft/hydrogen-mark-deoptimize.h", "src/crankshaft/hydrogen-mark-unreachable.cc", "src/crankshaft/hydrogen-mark-unreachable.h", "src/crankshaft/hydrogen-osr.cc", @@ -1262,6 +1295,7 @@ v8_source_set("v8_base") { "src/debug/debug-evaluate.h", "src/debug/debug-frames.cc", "src/debug/debug-frames.h", + "src/debug/debug-interface.h", "src/debug/debug-scopes.cc", "src/debug/debug-scopes.h", "src/debug/debug.cc", @@ -1363,7 +1397,6 @@ v8_source_set("v8_base") { "src/heap/objects-visiting.cc", "src/heap/objects-visiting.h", "src/heap/page-parallel-job.h", - "src/heap/remembered-set.cc", "src/heap/remembered-set.h", "src/heap/scavenge-job.cc", "src/heap/scavenge-job.h", @@ -1378,12 +1411,14 @@ v8_source_set("v8_base") { "src/heap/store-buffer.h", "src/i18n.cc", "src/i18n.h", + "src/ic/access-compiler-data.h", "src/ic/access-compiler.cc", "src/ic/access-compiler.h", "src/ic/call-optimization.cc", "src/ic/call-optimization.h", "src/ic/handler-compiler.cc", "src/ic/handler-compiler.h", + "src/ic/handler-configuration-inl.h", "src/ic/handler-configuration.h", "src/ic/ic-compiler.cc", "src/ic/ic-compiler.h", @@ -1392,6 +1427,8 @@ v8_source_set("v8_base") { "src/ic/ic-state.h", "src/ic/ic.cc", "src/ic/ic.h", + "src/ic/keyed-store-generic.cc", + "src/ic/keyed-store-generic.h", "src/ic/stub-cache.cc", "src/ic/stub-cache.h", "src/icu_util.cc", @@ -1541,6 +1578,8 @@ v8_source_set("v8_base") { "src/profiler/tracing-cpu-profiler.h", "src/profiler/unbound-queue-inl.h", "src/profiler/unbound-queue.h", + "src/promise-utils.cc", + "src/promise-utils.h", "src/property-descriptor.cc", "src/property-descriptor.h", "src/property-details.h", @@ -1566,6 +1605,8 @@ v8_source_set("v8_base") { "src/regexp/regexp-parser.h", "src/regexp/regexp-stack.cc", "src/regexp/regexp-stack.h", + "src/regexp/regexp-utils.cc", + "src/regexp/regexp-utils.h", "src/register-configuration.cc", "src/register-configuration.h", "src/runtime-profiler.cc", @@ -1588,9 +1629,11 @@ v8_source_set("v8_base") { "src/runtime/runtime-literals.cc", "src/runtime/runtime-liveedit.cc", "src/runtime/runtime-maths.cc", + "src/runtime/runtime-module.cc", "src/runtime/runtime-numbers.cc", "src/runtime/runtime-object.cc", "src/runtime/runtime-operators.cc", + "src/runtime/runtime-promise.cc", "src/runtime/runtime-proxy.cc", "src/runtime/runtime-regexp.cc", "src/runtime/runtime-scopes.cc", @@ -1628,6 +1671,7 @@ v8_source_set("v8_base") { "src/snapshot/startup-serializer.h", "src/source-position-table.cc", "src/source-position-table.h", + "src/source-position.cc", "src/source-position.h", "src/splay-tree-inl.h", "src/splay-tree.h", @@ -1642,6 +1686,10 @@ v8_source_set("v8_base") { "src/strtod.h", "src/tracing/trace-event.cc", "src/tracing/trace-event.h", + "src/tracing/traced-value.cc", + "src/tracing/traced-value.h", + "src/tracing/tracing-category-observer.cc", + "src/tracing/tracing-category-observer.h", "src/transitions-inl.h", "src/transitions.cc", "src/transitions.h", @@ -1680,16 +1728,14 @@ v8_source_set("v8_base") { "src/wasm/ast-decoder.h", "src/wasm/decoder.h", "src/wasm/leb-helper.h", + "src/wasm/managed.h", "src/wasm/module-decoder.cc", "src/wasm/module-decoder.h", - "src/wasm/switch-logic.cc", - "src/wasm/switch-logic.h", + "src/wasm/signature-map.cc", + "src/wasm/signature-map.h", "src/wasm/wasm-debug.cc", - "src/wasm/wasm-debug.h", "src/wasm/wasm-external-refs.cc", "src/wasm/wasm-external-refs.h", - "src/wasm/wasm-function-name-table.cc", - "src/wasm/wasm-function-name-table.h", "src/wasm/wasm-interpreter.cc", "src/wasm/wasm-interpreter.h", "src/wasm/wasm-js.cc", @@ -1699,6 +1745,8 @@ v8_source_set("v8_base") { "src/wasm/wasm-module-builder.h", "src/wasm/wasm-module.cc", "src/wasm/wasm-module.h", + "src/wasm/wasm-objects.cc", + "src/wasm/wasm-objects.h", "src/wasm/wasm-opcodes.cc", "src/wasm/wasm-opcodes.h", "src/wasm/wasm-result.cc", @@ -1707,6 +1755,7 @@ v8_source_set("v8_base") { "src/zone/accounting-allocator.h", "src/zone/zone-allocator.h", "src/zone/zone-allocator.h", + "src/zone/zone-chunk-list.h", "src/zone/zone-containers.h", "src/zone/zone-segment.cc", "src/zone/zone-segment.h", @@ -2152,24 +2201,15 @@ v8_source_set("v8_base") { } } -v8_source_set("v8_libbase") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - +v8_component("v8_libbase") { sources = [ "src/base/adapters.h", "src/base/atomic-utils.h", "src/base/atomicops.h", - "src/base/atomicops_internals_arm64_gcc.h", - "src/base/atomicops_internals_arm_gcc.h", "src/base/atomicops_internals_atomicword_compat.h", - "src/base/atomicops_internals_mac.h", - "src/base/atomicops_internals_mips64_gcc.h", - "src/base/atomicops_internals_mips_gcc.h", - "src/base/atomicops_internals_s390_gcc.h", - "src/base/atomicops_internals_tsan.h", - "src/base/atomicops_internals_x86_gcc.cc", - "src/base/atomicops_internals_x86_gcc.h", + "src/base/atomicops_internals_portable.h", "src/base/atomicops_internals_x86_msvc.h", + "src/base/base-export.h", "src/base/bits.cc", "src/base/bits.h", "src/base/build_config.h", @@ -2208,6 +2248,7 @@ v8_source_set("v8_libbase") { "src/base/platform/semaphore.h", "src/base/platform/time.cc", "src/base/platform/time.h", + "src/base/ring-buffer.h", "src/base/safe_conversions.h", "src/base/safe_conversions_impl.h", "src/base/safe_math.h", @@ -2220,8 +2261,14 @@ v8_source_set("v8_libbase") { configs = [ ":internal_config_base" ] + public_configs = [ ":libbase_config" ] + defines = [] + if (is_component_build) { + defines = [ "BUILDING_V8_BASE_SHARED" ] + } + if (is_posix) { sources += [ "src/base/platform/platform-posix.cc" ] } @@ -2285,9 +2332,10 @@ v8_source_set("v8_libbase") { # TODO(jochen): Add support for qnx, freebsd, openbsd, netbsd, and solaris. } -v8_source_set("v8_libplatform") { +v8_component("v8_libplatform") { sources = [ "//base/trace_event/common/trace_event_common.h", + "include/libplatform/libplatform-export.h", "include/libplatform/libplatform.h", "include/libplatform/v8-tracing.h", "src/libplatform/default-platform.cc", @@ -2307,6 +2355,10 @@ v8_source_set("v8_libplatform") { configs = [ ":internal_config_base" ] + if (is_component_build) { + defines = [ "BUILDING_V8_PLATFORM_SHARED" ] + } + public_configs = [ ":libplatform_config" ] deps = [ @@ -2344,27 +2396,7 @@ v8_source_set("fuzzer_support") { ] public_deps = [ - ":v8_libplatform", - ] -} - -# Used by fuzzers that would require exposing too many symbols for a proper -# component build. -v8_source_set("fuzzer_support_nocomponent") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - - sources = [ - "test/fuzzer/fuzzer-support.cc", - "test/fuzzer/fuzzer-support.h", - ] - - configs = [ ":internal_config_base" ] - - deps = [ - ":v8_maybe_snapshot", - ] - - public_deps = [ + ":v8_libbase", ":v8_libplatform", ] } @@ -2393,6 +2425,7 @@ if (current_toolchain == v8_snapshot_toolchain) { deps = [ ":v8_base", + ":v8_libbase", ":v8_libplatform", ":v8_nosnapshot", "//build/config/sanitizers:deps", @@ -2515,6 +2548,7 @@ v8_executable("d8") { deps = [ ":d8_js2c", ":v8", + ":v8_libbase", ":v8_libplatform", "//build/config/sanitizers:deps", "//build/win:default_exe_manifest", @@ -2531,6 +2565,11 @@ v8_executable("d8") { if (v8_enable_i18n_support) { deps += [ "//third_party/icu" ] } + + defines = [] + if (v8_enable_inspector_override) { + defines += [ "V8_INSPECTOR_ENABLED" ] + } } v8_isolate_run("d8") { @@ -2555,6 +2594,7 @@ v8_executable("v8_hello_world") { deps = [ ":v8", + ":v8_libbase", ":v8_libplatform", "//build/config/sanitizers:deps", "//build/win:default_exe_manifest", @@ -2579,6 +2619,7 @@ v8_executable("v8_sample_process") { deps = [ ":v8", + ":v8_libbase", ":v8_libplatform", "//build/config/sanitizers:deps", "//build/win:default_exe_manifest", @@ -2601,32 +2642,16 @@ v8_executable("v8_parser_shell") { ] deps = [ + ":v8", + ":v8_libbase", ":v8_libplatform", "//build/config/sanitizers:deps", "//build/win:default_exe_manifest", ] - if (is_component_build) { - # v8_parser_shell can't be built against a shared library, so we - # need to depend on the underlying static target in that case. - deps += [ ":v8_maybe_snapshot" ] - } else { - deps += [ ":v8" ] - } - if (v8_enable_i18n_support) { deps += [ "//third_party/icu" ] } - - if (is_win) { - # Suppress warnings about importing locally defined symbols. - if (is_component_build) { - ldflags = [ - "/ignore:4049", - "/ignore:4217", - ] - } - } } if (want_v8_shell) { @@ -2644,6 +2669,7 @@ if (want_v8_shell) { deps = [ ":v8", + ":v8_libbase", ":v8_libplatform", "//build/config/sanitizers:deps", "//build/win:default_exe_manifest", @@ -2693,7 +2719,7 @@ v8_source_set("parser_fuzzer") { ] deps = [ - ":fuzzer_support_nocomponent", + ":fuzzer_support", ] configs = [ @@ -2804,6 +2830,26 @@ v8_source_set("wasm_code_fuzzer") { v8_fuzzer("wasm_code_fuzzer") { } +v8_source_set("wasm_call_fuzzer") { + sources = [ + "test/fuzzer/wasm-call.cc", + ] + + deps = [ + ":fuzzer_support", + ":wasm_module_runner", + ":wasm_test_signatures", + ] + + configs = [ + ":external_config", + ":internal_config_base", + ] +} + +v8_fuzzer("wasm_call_fuzzer") { +} + v8_source_set("lib_wasm_section_fuzzer") { sources = [ "test/fuzzer/wasm-section-fuzzers.cc", diff --git a/deps/v8/ChangeLog b/deps/v8/ChangeLog index 40c8537022d79d..2dc77568d4c9a3 100644 --- a/deps/v8/ChangeLog +++ b/deps/v8/ChangeLog @@ -1,3 +1,1690 @@ +2016-11-15: Version 5.6.326 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.325 + + [wasm] Be more lenient on the names section (issue 5632). + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.324 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.323 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.322 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.321 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.320 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.319 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.318 + + Performance and stability improvements on all platforms. + + +2016-11-15: Version 5.6.317 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.316 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.315 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.314 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.313 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.312 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.311 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.310 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.309 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.308 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.307 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.306 + + Performance and stability improvements on all platforms. + + +2016-11-14: Version 5.6.305 + + Performance and stability improvements on all platforms. + + +2016-11-12: Version 5.6.304 + + Performance and stability improvements on all platforms. + + +2016-11-12: Version 5.6.303 + + Performance and stability improvements on all platforms. + + +2016-11-12: Version 5.6.302 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.301 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.300 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.299 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.298 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.297 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.296 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.295 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.294 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.293 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.292 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.291 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.290 + + Performance and stability improvements on all platforms. + + +2016-11-11: Version 5.6.289 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.288 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.287 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.286 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.285 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.284 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.283 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.282 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.281 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.280 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.279 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.278 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.277 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.276 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.275 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.274 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.273 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.272 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.271 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.270 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.269 + + Performance and stability improvements on all platforms. + + +2016-11-10: Version 5.6.268 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.267 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.266 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.265 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.264 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.263 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.262 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.261 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.260 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.259 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.258 + + Performance and stability improvements on all platforms. + + +2016-11-09: Version 5.6.257 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.256 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.255 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.254 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.253 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.252 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.251 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.250 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.249 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.248 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.247 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.246 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.245 + + Performance and stability improvements on all platforms. + + +2016-11-08: Version 5.6.244 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.243 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.242 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.241 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.240 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.239 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.238 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.237 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.236 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.235 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.234 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.233 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.232 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.231 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.230 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.229 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.228 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.227 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.226 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.225 + + Performance and stability improvements on all platforms. + + +2016-11-07: Version 5.6.224 + + Performance and stability improvements on all platforms. + + +2016-11-06: Version 5.6.223 + + Performance and stability improvements on all platforms. + + +2016-11-05: Version 5.6.222 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.221 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.220 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.219 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.218 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.217 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.216 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.215 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.214 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.213 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.212 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.211 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.210 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.209 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.208 + + Performance and stability improvements on all platforms. + + +2016-11-04: Version 5.6.207 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.206 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.205 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.204 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.203 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.202 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.201 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.200 + + Performance and stability improvements on all platforms. + + +2016-11-03: Version 5.6.199 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.198 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.197 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.196 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.195 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.194 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.193 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.192 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.191 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.190 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.189 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.188 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.187 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.186 + + Performance and stability improvements on all platforms. + + +2016-11-02: Version 5.6.185 + + Performance and stability improvements on all platforms. + + +2016-10-31: Version 5.6.184 + + Performance and stability improvements on all platforms. + + +2016-10-31: Version 5.6.183 + + Performance and stability improvements on all platforms. + + +2016-10-31: Version 5.6.182 + + Performance and stability improvements on all platforms. + + +2016-10-31: Version 5.6.181 + + Performance and stability improvements on all platforms. + + +2016-10-31: Version 5.6.180 + + Performance and stability improvements on all platforms. + + +2016-10-31: Version 5.6.179 + + Performance and stability improvements on all platforms. + + +2016-10-29: Version 5.6.178 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.177 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.176 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.175 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.174 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.173 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.172 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.171 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.170 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.169 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.168 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.167 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.166 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.165 + + Performance and stability improvements on all platforms. + + +2016-10-28: Version 5.6.164 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.163 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.162 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.161 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.160 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.159 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.158 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.157 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.156 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.155 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.154 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.153 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.152 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.151 + + Performance and stability improvements on all platforms. + + +2016-10-27: Version 5.6.150 + + Performance and stability improvements on all platforms. + + +2016-10-26: Version 5.6.149 + + Performance and stability improvements on all platforms. + + +2016-10-25: Version 5.6.148 + + Performance and stability improvements on all platforms. + + +2016-10-25: Version 5.6.147 + + Performance and stability improvements on all platforms. + + +2016-10-25: Version 5.6.146 + + Performance and stability improvements on all platforms. + + +2016-10-25: Version 5.6.145 + + Performance and stability improvements on all platforms. + + +2016-10-25: Version 5.6.144 + + Performance and stability improvements on all platforms. + + +2016-10-25: Version 5.6.143 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.142 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.141 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.140 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.139 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.138 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.137 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.136 + + Performance and stability improvements on all platforms. + + +2016-10-24: Version 5.6.135 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.134 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.133 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.132 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.131 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.130 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.129 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.128 + + Performance and stability improvements on all platforms. + + +2016-10-21: Version 5.6.127 + + Performance and stability improvements on all platforms. + + +2016-10-20: Version 5.6.126 + + Performance and stability improvements on all platforms. + + +2016-10-20: Version 5.6.125 + + Performance and stability improvements on all platforms. + + +2016-10-20: Version 5.6.124 + + Performance and stability improvements on all platforms. + + +2016-10-20: Version 5.6.123 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.122 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.121 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.120 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.119 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.118 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.117 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.116 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.115 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.114 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.113 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.112 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.111 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.110 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.109 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.108 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.107 + + Performance and stability improvements on all platforms. + + +2016-10-19: Version 5.6.106 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.105 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.104 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.103 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.102 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.101 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.100 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.99 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.98 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.97 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.96 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.95 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.94 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.93 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.92 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.91 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.90 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.89 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.88 + + Performance and stability improvements on all platforms. + + +2016-10-18: Version 5.6.87 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.86 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.85 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.84 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.83 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.82 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.81 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.80 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.79 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.78 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.77 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.76 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.75 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.74 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.73 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.72 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.71 + + Performance and stability improvements on all platforms. + + +2016-10-17: Version 5.6.70 + + Performance and stability improvements on all platforms. + + +2016-10-16: Version 5.6.69 + + Performance and stability improvements on all platforms. + + +2016-10-16: Version 5.6.68 + + Performance and stability improvements on all platforms. + + +2016-10-15: Version 5.6.67 + + Performance and stability improvements on all platforms. + + +2016-10-15: Version 5.6.66 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.65 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.64 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.63 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.62 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.61 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.60 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.59 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.58 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.57 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.56 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.55 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.54 + + Performance and stability improvements on all platforms. + + +2016-10-14: Version 5.6.53 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.52 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.51 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.50 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.49 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.48 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.47 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.46 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.45 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.44 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.43 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.42 + + Performance and stability improvements on all platforms. + + +2016-10-13: Version 5.6.41 + + Performance and stability improvements on all platforms. + + +2016-10-12: Version 5.6.40 + + Performance and stability improvements on all platforms. + + +2016-10-12: Version 5.6.39 + + Performance and stability improvements on all platforms. + + +2016-10-12: Version 5.6.38 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.37 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.36 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.35 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.34 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.33 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.32 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.31 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.30 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.29 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.28 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.27 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.26 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.25 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.24 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.23 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.22 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.21 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.20 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.19 + + Performance and stability improvements on all platforms. + + +2016-10-11: Version 5.6.18 + + Performance and stability improvements on all platforms. + + +2016-10-10: Version 5.6.17 + + Performance and stability improvements on all platforms. + + +2016-10-10: Version 5.6.16 + + Performance and stability improvements on all platforms. + + +2016-10-10: Version 5.6.15 + + Performance and stability improvements on all platforms. + + +2016-10-10: Version 5.6.14 + + Performance and stability improvements on all platforms. + + +2016-10-10: Version 5.6.13 + + Performance and stability improvements on all platforms. + + +2016-10-09: Version 5.6.12 + + Performance and stability improvements on all platforms. + + +2016-10-08: Version 5.6.11 + + Performance and stability improvements on all platforms. + + +2016-10-08: Version 5.6.10 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.9 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.8 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.7 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.6 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.5 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.4 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.3 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.2 + + Performance and stability improvements on all platforms. + + +2016-10-07: Version 5.6.1 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.383 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.382 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.381 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.380 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.379 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.378 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.377 + + Performance and stability improvements on all platforms. + + +2016-10-06: Version 5.5.376 + + Performance and stability improvements on all platforms. + + +2016-10-05: Version 5.5.375 + + Performance and stability improvements on all platforms. + + +2016-10-05: Version 5.5.374 + + Performance and stability improvements on all platforms. + + +2016-10-05: Version 5.5.373 + + Performance and stability improvements on all platforms. + + 2016-10-05: Version 5.5.372 Performance and stability improvements on all platforms. diff --git a/deps/v8/DEPS b/deps/v8/DEPS index 058cd8bea632e2..161015d661a8d1 100644 --- a/deps/v8/DEPS +++ b/deps/v8/DEPS @@ -8,19 +8,17 @@ vars = { deps = { "v8/build": - Var("chromium_url") + "/chromium/src/build.git" + "@" + "475d5b37ded6589c9f8a0d19ced54ddf2e6d14a0", + Var("chromium_url") + "/chromium/src/build.git" + "@" + "a3b623a6eff6dc9d58a03251ae22bccf92f67cb2", "v8/tools/gyp": Var("chromium_url") + "/external/gyp.git" + "@" + "e7079f0e0e14108ab0dba58728ff219637458563", "v8/third_party/icu": - Var("chromium_url") + "/chromium/deps/icu.git" + "@" + "b0bd3ee50bc2e768d7a17cbc60d87f517f024dbe", + Var("chromium_url") + "/chromium/deps/icu.git" + "@" + "c1a237113f525a1561d4b322d7653e1083f79aaa", "v8/third_party/instrumented_libraries": Var("chromium_url") + "/chromium/src/third_party/instrumented_libraries.git" + "@" + "45f5814b1543e41ea0be54c771e3840ea52cca4a", "v8/buildtools": - Var("chromium_url") + "/chromium/buildtools.git" + "@" + "5fd66957f08bb752dca714a591c84587c9d70762", + Var("chromium_url") + "/chromium/buildtools.git" + "@" + "39b1db2ab4aa4b2ccaa263c29bdf63e7c1ee28aa", "v8/base/trace_event/common": - Var("chromium_url") + "/chromium/src/base/trace_event/common.git" + "@" + "e0fa02a02f61430dae2bddfd89a334ea4389f495", - "v8/third_party/WebKit/Source/platform/inspector_protocol": - Var("chromium_url") + "/chromium/src/third_party/WebKit/Source/platform/inspector_protocol.git" + "@" + "3280c57c4c575ce82ccd13e4a403492fb4ca624b", + Var("chromium_url") + "/chromium/src/base/trace_event/common.git" + "@" + "06294c8a4a6f744ef284cd63cfe54dbf61eea290", "v8/third_party/jinja2": Var("chromium_url") + "/chromium/src/third_party/jinja2.git" + "@" + "b61a2c009a579593a259c1b300e0ad02bf48fd78", "v8/third_party/markupsafe": @@ -37,17 +35,19 @@ deps = { Var("chromium_url") + "/v8/deps/third_party/mozilla-tests.git" + "@" + "f6c578a10ea707b1a8ab0b88943fe5115ce2b9be", "v8/test/simdjs/data": Var("chromium_url") + "/external/github.com/tc39/ecmascript_simd.git" + "@" + "baf493985cb9ea7cdbd0d68704860a8156de9556", "v8/test/test262/data": - Var("chromium_url") + "/external/github.com/tc39/test262.git" + "@" + "29c23844494a7cc2fbebc6948d2cb0bcaddb24e7", + Var("chromium_url") + "/external/github.com/tc39/test262.git" + "@" + "fb61ab44eb1bbc2699d714fc00e33af2a19411ce", "v8/test/test262/harness": Var("chromium_url") + "/external/github.com/test262-utils/test262-harness-py.git" + "@" + "cbd968f54f7a95c6556d53ba852292a4c49d11d8", "v8/tools/clang": - Var("chromium_url") + "/chromium/src/tools/clang.git" + "@" + "1f92f999fc374a479e98a189ebdfe25c09484486", + Var("chromium_url") + "/chromium/src/tools/clang.git" + "@" + "75350a858c51ad69e2aae051a8727534542da29f", } deps_os = { "android": { "v8/third_party/android_tools": Var("chromium_url") + "/android_tools.git" + "@" + "25d57ead05d3dfef26e9c19b13ed10b0a69829cf", + "v8/third_party/catapult": + Var('chromium_url') + "/external/github.com/catapult-project/catapult.git" + "@" + "6962f5c0344a79b152bf84460a93e1b2e11ea0f4", }, "win": { "v8/third_party/cygwin": diff --git a/deps/v8/Makefile b/deps/v8/Makefile index a6d4d135da3da1..6eeac09a14875b 100644 --- a/deps/v8/Makefile +++ b/deps/v8/Makefile @@ -163,6 +163,14 @@ endif ifeq ($(goma), on) GYPFLAGS += -Duse_goma=1 endif +# v8_os_page_size=0, when 0 or not specified use build OS page size +ifdef v8_os_page_size + ifneq ($(v8_os_page_size), 0) + ifneq ($(snapshot), off) + GYPFLAGS += -Dv8_os_page_size=$(v8_os_page_size) + endif + endif +endif # arm specific flags. # arm_version= ifneq ($(strip $(arm_version)),) diff --git a/deps/v8/PRESUBMIT.py b/deps/v8/PRESUBMIT.py index 78e7482efbab5d..ad218330b180a4 100644 --- a/deps/v8/PRESUBMIT.py +++ b/deps/v8/PRESUBMIT.py @@ -67,7 +67,6 @@ def _V8PresubmitChecks(input_api, output_api): input_api.PresubmitLocalPath(), 'tools')) from presubmit import CppLintProcessor from presubmit import SourceProcessor - from presubmit import CheckExternalReferenceRegistration from presubmit import CheckAuthorizedAuthor from presubmit import CheckStatusFiles @@ -78,9 +77,6 @@ def _V8PresubmitChecks(input_api, output_api): results.append(output_api.PresubmitError( "Copyright header, trailing whitespaces and two empty lines " \ "between declarations check failed")) - if not CheckExternalReferenceRegistration(input_api.PresubmitLocalPath()): - results.append(output_api.PresubmitError( - "External references registration check failed")) if not CheckStatusFiles(input_api.PresubmitLocalPath()): results.append(output_api.PresubmitError("Status file check failed")) results.extend(CheckAuthorizedAuthor(input_api, output_api)) diff --git a/deps/v8/base/trace_event/common/trace_event_common.h b/deps/v8/base/trace_event/common/trace_event_common.h index 0db92692a0fe2a..e87665b8cdb12b 100644 --- a/deps/v8/base/trace_event/common/trace_event_common.h +++ b/deps/v8/base/trace_event/common/trace_event_common.h @@ -223,49 +223,6 @@ flow_flags, arg1_name, arg1_val, \ arg2_name, arg2_val) -// UNSHIPPED_TRACE_EVENT* are like TRACE_EVENT* except that they are not -// included in official builds. - -#if OFFICIAL_BUILD -#undef TRACING_IS_OFFICIAL_BUILD -#define TRACING_IS_OFFICIAL_BUILD 1 -#elif !defined(TRACING_IS_OFFICIAL_BUILD) -#define TRACING_IS_OFFICIAL_BUILD 0 -#endif - -#if TRACING_IS_OFFICIAL_BUILD -#define UNSHIPPED_TRACE_EVENT0(category_group, name) (void)0 -#define UNSHIPPED_TRACE_EVENT1(category_group, name, arg1_name, arg1_val) \ - (void)0 -#define UNSHIPPED_TRACE_EVENT2(category_group, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - (void)0 -#define UNSHIPPED_TRACE_EVENT_INSTANT0(category_group, name, scope) (void)0 -#define UNSHIPPED_TRACE_EVENT_INSTANT1(category_group, name, scope, arg1_name, \ - arg1_val) \ - (void)0 -#define UNSHIPPED_TRACE_EVENT_INSTANT2(category_group, name, scope, arg1_name, \ - arg1_val, arg2_name, arg2_val) \ - (void)0 -#else -#define UNSHIPPED_TRACE_EVENT0(category_group, name) \ - TRACE_EVENT0(category_group, name) -#define UNSHIPPED_TRACE_EVENT1(category_group, name, arg1_name, arg1_val) \ - TRACE_EVENT1(category_group, name, arg1_name, arg1_val) -#define UNSHIPPED_TRACE_EVENT2(category_group, name, arg1_name, arg1_val, \ - arg2_name, arg2_val) \ - TRACE_EVENT2(category_group, name, arg1_name, arg1_val, arg2_name, arg2_val) -#define UNSHIPPED_TRACE_EVENT_INSTANT0(category_group, name, scope) \ - TRACE_EVENT_INSTANT0(category_group, name, scope) -#define UNSHIPPED_TRACE_EVENT_INSTANT1(category_group, name, scope, arg1_name, \ - arg1_val) \ - TRACE_EVENT_INSTANT1(category_group, name, scope, arg1_name, arg1_val) -#define UNSHIPPED_TRACE_EVENT_INSTANT2(category_group, name, scope, arg1_name, \ - arg1_val, arg2_name, arg2_val) \ - TRACE_EVENT_INSTANT2(category_group, name, scope, arg1_name, arg1_val, \ - arg2_name, arg2_val) -#endif - // Records a single event called "name" immediately, with 0, 1 or 2 // associated arguments. If the category is not enabled, then this // does nothing. @@ -301,16 +258,6 @@ TRACE_EVENT_PHASE_INSTANT, category_group, name, timestamp, \ TRACE_EVENT_FLAG_NONE | scope) -// Syntactic sugars for the sampling tracing in the main thread. -#define TRACE_EVENT_SCOPED_SAMPLING_STATE(category, name) \ - TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET(0, category, name) -#define TRACE_EVENT_GET_SAMPLING_STATE() \ - TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET(0) -#define TRACE_EVENT_SET_SAMPLING_STATE(category, name) \ - TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(0, category, name) -#define TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(category_and_name) \ - TRACE_EVENT_SET_NONCONST_SAMPLING_STATE_FOR_BUCKET(0, category_and_name) - // Records a single BEGIN event called "name" immediately, with 0, 1 or 2 // associated arguments. If the category is not enabled, then this // does nothing. @@ -1006,15 +953,15 @@ INTERNAL_TRACE_EVENT_SCOPED_CONTEXT(category_group, name, context) // Macro to specify that two trace IDs are identical. For example, -// TRACE_BIND_IDS( +// 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_BIND_IDS(category_group, name, id, bind_id) \ - INTERNAL_TRACE_EVENT_ADD_BIND_IDS(category_group, name, id, bind_id); +#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) \ @@ -1081,7 +1028,7 @@ #define TRACE_EVENT_PHASE_CLOCK_SYNC ('c') #define TRACE_EVENT_PHASE_ENTER_CONTEXT ('(') #define TRACE_EVENT_PHASE_LEAVE_CONTEXT (')') -#define TRACE_EVENT_PHASE_BIND_IDS ('=') +#define TRACE_EVENT_PHASE_LINK_IDS ('=') // Flags for changing the behavior of TRACE_EVENT_API_ADD_TRACE_EVENT. #define TRACE_EVENT_FLAG_NONE (static_cast(0)) diff --git a/deps/v8/build_overrides/v8.gni b/deps/v8/build_overrides/v8.gni index 09ea4570b02032..df8320d5d1746d 100644 --- a/deps/v8/build_overrides/v8.gni +++ b/deps/v8/build_overrides/v8.gni @@ -26,7 +26,7 @@ v8_experimental_extra_library_files = declare_args() { # Enable inspector. See include/v8-inspector.h. - v8_enable_inspector = false + v8_enable_inspector = true } v8_enable_inspector_override = v8_enable_inspector diff --git a/deps/v8/gni/isolate.gni b/deps/v8/gni/isolate.gni index 93c828d2cdf0fb..1cc3a38770439f 100644 --- a/deps/v8/gni/isolate.gni +++ b/deps/v8/gni/isolate.gni @@ -3,6 +3,7 @@ # found in the LICENSE file. import("//build/config/sanitizers/sanitizers.gni") +import("//build_overrides/v8.gni") import("//third_party/icu/config.gni") import("v8.gni") @@ -12,11 +13,21 @@ declare_args() { } template("v8_isolate_run") { + forward_variables_from(invoker, + "*", + [ + "deps", + "isolate", + ]) + # Remember target name as within the action scope the target name will be # different. name = target_name - if (name != "" && invoker.isolate != "" && invoker.deps != [] && - v8_test_isolation_mode != "noop") { + + assert(defined(invoker.deps)) + assert(defined(invoker.isolate)) + + if (name != "" && v8_test_isolation_mode != "noop") { action(name + "_run") { testonly = true @@ -86,6 +97,11 @@ template("v8_isolate_run") { } else { icu_use_data_file_flag = "0" } + if (v8_enable_inspector_override) { + enable_inspector = "1" + } else { + enable_inspector = "0" + } if (v8_use_external_startup_data) { use_external_startup_data = "1" } else { @@ -107,7 +123,6 @@ template("v8_isolate_run") { gcmole = "0" } - # Note, all paths will be rebased in isolate_driver.py to be relative to # the isolate file. args = [ @@ -142,6 +157,8 @@ template("v8_isolate_run") { "--config-variable", "icu_use_data_file_flag=$icu_use_data_file_flag", "--config-variable", + "is_gn=1", + "--config-variable", "msan=$msan", "--config-variable", "tsan=$tsan", @@ -154,6 +171,8 @@ template("v8_isolate_run") { "--config-variable", "target_arch=$target_arch", "--config-variable", + "v8_enable_inspector=$enable_inspector", + "--config-variable", "v8_use_external_startup_data=$use_external_startup_data", "--config-variable", "v8_use_snapshot=$use_snapshot", diff --git a/deps/v8/gni/v8.gni b/deps/v8/gni/v8.gni index 7ff7f6fb89ac36..3759572b935157 100644 --- a/deps/v8/gni/v8.gni +++ b/deps/v8/gni/v8.gni @@ -26,6 +26,10 @@ declare_args() { # Use external files for startup data blobs: # the JS builtins sources and the start snapshot. v8_use_external_startup_data = "" + + # Enable ECMAScript Internationalization API. Enabling this feature will + # add a dependency on the ICU library. + v8_enable_i18n_support = true } if (v8_use_external_startup_data == "") { @@ -38,15 +42,17 @@ if (v8_enable_backtrace == "") { v8_enable_backtrace = is_debug && !v8_optimized_debug } -############################################################################### -# Templates -# - # Points to // in v8 stand-alone or to //v8/ in chromium. We need absolute # paths for all configs in templates as they are shared in different # subdirectories. v8_path_prefix = get_path_info("../", "abspath") +v8_inspector_js_protocol = v8_path_prefix + "/src/inspector/js_protocol.json" + +############################################################################### +# Templates +# + # Common configs to remove or add in all v8 targets. v8_remove_configs = [ "//build/config/compiler:chromium_code" ] v8_add_configs = [ @@ -87,7 +93,15 @@ template("v8_source_set") { template("v8_executable") { executable(target_name) { - forward_variables_from(invoker, "*", [ "configs" ]) + forward_variables_from(invoker, + "*", + [ + "configs", + "remove_configs", + ]) + if (defined(invoker.remove_configs)) { + configs -= invoker.remove_configs + } configs += invoker.configs configs -= v8_remove_configs configs += v8_add_configs diff --git a/deps/v8/gypfiles/all.gyp b/deps/v8/gypfiles/all.gyp index 6b4ef82d6906c1..a3f2eedc77d3bd 100644 --- a/deps/v8/gypfiles/all.gyp +++ b/deps/v8/gypfiles/all.gyp @@ -25,6 +25,12 @@ '../test/unittests/unittests.gyp:*', ], }], + ['v8_enable_inspector==1', { + 'dependencies': [ + '../test/debugger/debugger.gyp:*', + '../test/inspector/inspector.gyp:*', + ], + }], ['test_isolation_mode != "noop"', { 'dependencies': [ '../test/bot_default.gyp:*', diff --git a/deps/v8/gypfiles/get_landmines.py b/deps/v8/gypfiles/get_landmines.py index 432dfd7ae5d8a8..e6b6da6c48db4b 100755 --- a/deps/v8/gypfiles/get_landmines.py +++ b/deps/v8/gypfiles/get_landmines.py @@ -30,6 +30,7 @@ def main(): print 'Clobber after Android NDK update.' print 'Clober to fix windows build problems.' print 'Clober again to fix windows build problems.' + print 'Clobber to possibly resolve failure on win-32 bot.' return 0 diff --git a/deps/v8/gypfiles/isolate.gypi b/deps/v8/gypfiles/isolate.gypi index 149818c8d0636f..8f53a153c6222c 100644 --- a/deps/v8/gypfiles/isolate.gypi +++ b/deps/v8/gypfiles/isolate.gypi @@ -74,12 +74,14 @@ '--config-variable', 'gcmole=<(gcmole)', '--config-variable', 'has_valgrind=<(has_valgrind)', '--config-variable', 'icu_use_data_file_flag=<(icu_use_data_file_flag)', + '--config-variable', 'is_gn=0', '--config-variable', 'msan=<(msan)', '--config-variable', 'tsan=<(tsan)', '--config-variable', 'coverage=<(coverage)', '--config-variable', 'sanitizer_coverage=<(sanitizer_coverage)', '--config-variable', 'component=<(component)', '--config-variable', 'target_arch=<(target_arch)', + '--config-variable', 'v8_enable_inspector=<(v8_enable_inspector)', '--config-variable', 'v8_use_external_startup_data=<(v8_use_external_startup_data)', '--config-variable', 'v8_use_snapshot=<(v8_use_snapshot)', ], diff --git a/deps/v8/gypfiles/standalone.gypi b/deps/v8/gypfiles/standalone.gypi index 7e41ce84aef96d..d438a5aeab992e 100644 --- a/deps/v8/gypfiles/standalone.gypi +++ b/deps/v8/gypfiles/standalone.gypi @@ -455,6 +455,7 @@ 'variables': { 'v8_code%': '<(v8_code)', 'clang_warning_flags': [ + '-Wsign-compare', # TODO(thakis): https://crbug.com/604888 '-Wno-undefined-var-template', # TODO(yangguo): issue 5258 @@ -503,7 +504,9 @@ }, 'conditions':[ ['clang==0', { - 'cflags+': ['-Wno-sign-compare',], + 'cflags+': [ + '-Wno-uninitialized', + ], }], ['clang==1 or host_clang==1', { # This is here so that all files get recompiled after a clang roll and diff --git a/deps/v8/gypfiles/toolchain.gypi b/deps/v8/gypfiles/toolchain.gypi index 95eb1d99cbff3f..5105fff0700199 100644 --- a/deps/v8/gypfiles/toolchain.gypi +++ b/deps/v8/gypfiles/toolchain.gypi @@ -989,8 +989,6 @@ # present in VS 2003 and earlier. 'msvs_disabled_warnings': [4351], 'msvs_configuration_attributes': { - 'OutputDirectory': '<(DEPTH)\\build\\$(ConfigurationName)', - 'IntermediateDirectory': '$(OutDir)\\obj\\$(ProjectName)', 'CharacterSet': '1', }, }], diff --git a/deps/v8/include/libplatform/DEPS b/deps/v8/include/libplatform/DEPS index 15e75e6b4ffe50..d8bcf99880d380 100644 --- a/deps/v8/include/libplatform/DEPS +++ b/deps/v8/include/libplatform/DEPS @@ -1,3 +1,7 @@ +include_rules = [ + "+libplatform/libplatform-export.h", +] + specific_include_rules = { "libplatform\.h": [ "+libplatform/v8-tracing.h", diff --git a/deps/v8/include/libplatform/libplatform-export.h b/deps/v8/include/libplatform/libplatform-export.h new file mode 100644 index 00000000000000..15618434977d93 --- /dev/null +++ b/deps/v8/include/libplatform/libplatform-export.h @@ -0,0 +1,29 @@ +// Copyright 2016 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef V8_LIBPLATFORM_LIBPLATFORM_EXPORT_H_ +#define V8_LIBPLATFORM_LIBPLATFORM_EXPORT_H_ + +#if defined(_WIN32) + +#ifdef BUILDING_V8_PLATFORM_SHARED +#define V8_PLATFORM_EXPORT __declspec(dllexport) +#elif USING_V8_PLATFORM_SHARED +#define V8_PLATFORM_EXPORT __declspec(dllimport) +#else +#define V8_PLATFORM_EXPORT +#endif // BUILDING_V8_PLATFORM_SHARED + +#else // defined(_WIN32) + +// Setup for Linux shared library export. +#ifdef BUILDING_V8_PLATFORM_SHARED +#define V8_PLATFORM_EXPORT __attribute__((visibility("default"))) +#else +#define V8_PLATFORM_EXPORT +#endif + +#endif // defined(_WIN32) + +#endif // V8_LIBPLATFORM_LIBPLATFORM_EXPORT_H_ diff --git a/deps/v8/include/libplatform/libplatform.h b/deps/v8/include/libplatform/libplatform.h index 5b5eee651319b5..40f3f668927f4e 100644 --- a/deps/v8/include/libplatform/libplatform.h +++ b/deps/v8/include/libplatform/libplatform.h @@ -5,6 +5,7 @@ #ifndef V8_LIBPLATFORM_LIBPLATFORM_H_ #define V8_LIBPLATFORM_LIBPLATFORM_H_ +#include "libplatform/libplatform-export.h" #include "libplatform/v8-tracing.h" #include "v8-platform.h" // NOLINT(build/include) @@ -19,8 +20,8 @@ namespace platform { * of zero is passed, a suitable default based on the current number of * processors online will be chosen. */ -v8::Platform* CreateDefaultPlatform(int thread_pool_size = 0); - +V8_PLATFORM_EXPORT v8::Platform* CreateDefaultPlatform( + int thread_pool_size = 0); /** * Pumps the message loop for the given isolate. @@ -30,14 +31,15 @@ v8::Platform* CreateDefaultPlatform(int thread_pool_size = 0); * not block if no task is pending. The |platform| has to be created using * |CreateDefaultPlatform|. */ -bool PumpMessageLoop(v8::Platform* platform, v8::Isolate* isolate); +V8_PLATFORM_EXPORT bool PumpMessageLoop(v8::Platform* platform, + v8::Isolate* isolate); /** * Attempts to set the tracing controller for the given platform. * * The |platform| has to be created using |CreateDefaultPlatform|. */ -void SetTracingController( +V8_PLATFORM_EXPORT void SetTracingController( v8::Platform* platform, v8::platform::tracing::TracingController* tracing_controller); diff --git a/deps/v8/include/libplatform/v8-tracing.h b/deps/v8/include/libplatform/v8-tracing.h index e9f49414784da5..902f8ea93dbaa5 100644 --- a/deps/v8/include/libplatform/v8-tracing.h +++ b/deps/v8/include/libplatform/v8-tracing.h @@ -10,6 +10,7 @@ #include #include +#include "libplatform/libplatform-export.h" #include "v8-platform.h" // NOLINT(build/include) namespace v8 { @@ -23,7 +24,7 @@ namespace tracing { const int kTraceMaxNumArgs = 2; -class TraceObject { +class V8_PLATFORM_EXPORT TraceObject { public: union ArgValue { bool as_bool; @@ -103,7 +104,7 @@ class TraceObject { void operator=(const TraceObject&) = delete; }; -class TraceWriter { +class V8_PLATFORM_EXPORT TraceWriter { public: TraceWriter() {} virtual ~TraceWriter() {} @@ -118,7 +119,7 @@ class TraceWriter { void operator=(const TraceWriter&) = delete; }; -class TraceBufferChunk { +class V8_PLATFORM_EXPORT TraceBufferChunk { public: explicit TraceBufferChunk(uint32_t seq); @@ -142,7 +143,7 @@ class TraceBufferChunk { void operator=(const TraceBufferChunk&) = delete; }; -class TraceBuffer { +class V8_PLATFORM_EXPORT TraceBuffer { public: TraceBuffer() {} virtual ~TraceBuffer() {} @@ -178,45 +179,37 @@ enum TraceRecordMode { ECHO_TO_CONSOLE, }; -class TraceConfig { +class V8_PLATFORM_EXPORT TraceConfig { public: typedef std::vector StringList; static TraceConfig* CreateDefaultTraceConfig(); - TraceConfig() - : enable_sampling_(false), - enable_systrace_(false), - enable_argument_filter_(false) {} + TraceConfig() : enable_systrace_(false), enable_argument_filter_(false) {} TraceRecordMode GetTraceRecordMode() const { return record_mode_; } - bool IsSamplingEnabled() const { return enable_sampling_; } bool IsSystraceEnabled() const { return enable_systrace_; } bool IsArgumentFilterEnabled() const { return enable_argument_filter_; } void SetTraceRecordMode(TraceRecordMode mode) { record_mode_ = mode; } - void EnableSampling() { enable_sampling_ = true; } void EnableSystrace() { enable_systrace_ = true; } void EnableArgumentFilter() { enable_argument_filter_ = true; } void AddIncludedCategory(const char* included_category); - void AddExcludedCategory(const char* excluded_category); bool IsCategoryGroupEnabled(const char* category_group) const; private: TraceRecordMode record_mode_; - bool enable_sampling_ : 1; bool enable_systrace_ : 1; bool enable_argument_filter_ : 1; StringList included_categories_; - StringList excluded_categories_; // Disallow copy and assign TraceConfig(const TraceConfig&) = delete; void operator=(const TraceConfig&) = delete; }; -class TracingController { +class V8_PLATFORM_EXPORT TracingController { public: enum Mode { DISABLED = 0, RECORDING_MODE }; diff --git a/deps/v8/include/v8-profiler.h b/deps/v8/include/v8-profiler.h index 6ee0340f3c3d7c..74c0613946d513 100644 --- a/deps/v8/include/v8-profiler.h +++ b/deps/v8/include/v8-profiler.h @@ -48,7 +48,7 @@ namespace v8 { /** * TracingCpuProfiler monitors tracing being enabled/disabled - * and emits CpuProfile trace events once v8.cpu_profile2 tracing category + * and emits CpuProfile trace events once v8.cpu_profiler tracing category * is enabled. It has no overhead unless the category is enabled. */ class V8_EXPORT TracingCpuProfiler { diff --git a/deps/v8/include/v8-util.h b/deps/v8/include/v8-util.h index 99c59fe302963d..8133fdd49dcf4f 100644 --- a/deps/v8/include/v8-util.h +++ b/deps/v8/include/v8-util.h @@ -206,19 +206,14 @@ class PersistentValueMapBase { } /** - * Deprecated. Call V8::RegisterExternallyReferencedObject with the map value - * for given key. - * TODO(hlopko) Remove once migration to reporter is finished. + * Call V8::RegisterExternallyReferencedObject with the map value for given + * key. */ - void RegisterExternallyReferencedObject(K& key) {} - - /** - * Use EmbedderReachableReferenceReporter with the map value for given key. - */ - void RegisterExternallyReferencedObject( - EmbedderReachableReferenceReporter* reporter, K& key) { + void RegisterExternallyReferencedObject(K& key) { DCHECK(Contains(key)); - reporter->ReportExternalReference(FromVal(Traits::Get(&impl_, key))); + V8::RegisterExternallyReferencedObject( + reinterpret_cast(FromVal(Traits::Get(&impl_, key))), + reinterpret_cast(GetIsolate())); } /** diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index b216cf04c30a00..b6949876330a21 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -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 5 -#define V8_MINOR_VERSION 5 -#define V8_BUILD_NUMBER 372 -#define V8_PATCH_LEVEL 40 +#define V8_MINOR_VERSION 6 +#define V8_BUILD_NUMBER 326 +#define V8_PATCH_LEVEL 55 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/include/v8.h b/deps/v8/include/v8.h index 36edf5334a9d27..5348ba7e48b32b 100644 --- a/deps/v8/include/v8.h +++ b/deps/v8/include/v8.h @@ -35,11 +35,6 @@ // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8 // static library or building a program which uses the V8 static library neither // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined. -#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED) -#error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\ - build configuration to ensure that at most one of these is set -#endif - #ifdef BUILDING_V8_SHARED # define V8_EXPORT __declspec(dllexport) #elif USING_V8_SHARED @@ -467,16 +462,6 @@ class WeakCallbackInfo { // possible to request a second pass callback. enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer }; -/** - * A reporter class that embedder will use to report reachable references found - * by EmbedderHeapTracer. - */ -class V8_EXPORT EmbedderReachableReferenceReporter { - public: - virtual void ReportExternalReference(Value* object) = 0; - virtual ~EmbedderReachableReferenceReporter() = default; -}; - /** * An object reference that is independent of any handle scope. Where * a Local handle only lives as long as the HandleScope in which it was @@ -573,19 +558,12 @@ template class PersistentBase { // TODO(dcarney): remove this. V8_INLINE void ClearWeak() { ClearWeak(); } - /** - * Deprecated. - * TODO(hlopko): remove once migration to reporter is finished. - */ - V8_INLINE void RegisterExternalReference(Isolate* isolate) const {} - /** * Allows the embedder to tell the v8 garbage collector that a certain object * is alive. Only allowed when the embedder is asked to trace its heap by * EmbedderHeapTracer. */ - V8_INLINE void RegisterExternalReference( - EmbedderReachableReferenceReporter* reporter) const; + V8_INLINE void RegisterExternalReference(Isolate* isolate) const; /** * Marks the reference to this object independent. Garbage collector is free @@ -595,18 +573,6 @@ template class PersistentBase { */ V8_INLINE void MarkIndependent(); - /** - * Marks the reference to this object partially dependent. Partially dependent - * handles only depend on other partially dependent handles and these - * dependencies are provided through object groups. It provides a way to build - * smaller object groups for young objects that represent only a subset of all - * external dependencies. This mark is automatically cleared after each - * garbage collection. - */ - V8_INLINE V8_DEPRECATED( - "deprecated optimization, do not use partially dependent groups", - void MarkPartiallyDependent()); - /** * Marks the reference to this object as active. The scavenge garbage * collection should not reclaim the objects marked as active. @@ -1106,22 +1072,22 @@ class V8_EXPORT Module { */ Local GetModuleRequest(int i) const; - void SetEmbedderData(Local data); - Local GetEmbedderData() const; + /** + * Returns the identity hash for this object. + */ + int GetIdentityHash() const; typedef MaybeLocal (*ResolveCallback)(Local context, Local specifier, - Local referrer, - Local data); + Local referrer); /** * ModuleDeclarationInstantiation * * Returns false if an exception occurred during instantiation. */ - V8_WARN_UNUSED_RESULT bool Instantiate( - Local context, ResolveCallback callback, - Local callback_data = Local()); + V8_WARN_UNUSED_RESULT bool Instantiate(Local context, + ResolveCallback callback); /** * ModuleEvaluation @@ -1745,6 +1711,19 @@ class V8_EXPORT ValueSerializer { * Nothing() returned. */ virtual Maybe WriteHostObject(Isolate* isolate, Local object); + + /* + * Allocates memory for the buffer of at least the size provided. The actual + * size (which may be greater or equal) is written to |actual_size|. If no + * buffer has been allocated yet, nullptr will be provided. + */ + virtual void* ReallocateBufferMemory(void* old_buffer, size_t size, + size_t* actual_size); + + /* + * Frees a buffer allocated with |ReallocateBufferMemory|. + */ + virtual void FreeBufferMemory(void* buffer); }; explicit ValueSerializer(Isolate* isolate); @@ -1766,7 +1745,15 @@ class V8_EXPORT ValueSerializer { * Returns the stored data. This serializer should not be used once the buffer * is released. The contents are undefined if a previous write has failed. */ - std::vector ReleaseBuffer(); + V8_DEPRECATE_SOON("Use Release()", std::vector ReleaseBuffer()); + + /* + * Returns the stored data (allocated using the delegate's + * AllocateBufferMemory) and its size. This serializer should not be used once + * the buffer is released. The contents are undefined if a previous write has + * failed. + */ + V8_WARN_UNUSED_RESULT std::pair Release(); /* * Marks an ArrayBuffer as havings its contents transferred out of band. @@ -1832,7 +1819,6 @@ class V8_EXPORT ValueDeserializer { * May, for example, reject an invalid or unsupported wire format. */ V8_WARN_UNUSED_RESULT Maybe ReadHeader(Local context); - V8_DEPRECATE_SOON("Use Local version", Maybe ReadHeader()); /* * Deserializes a JavaScript value from the buffer. @@ -3542,7 +3528,7 @@ class PropertyCallbackInfo { /** * \return The receiver. In many cases, this is the object on which the * property access was intercepted. When using - * `Reflect.Get`, `Function.prototype.call`, or similar functions, it is the + * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the * object passed in as receiver or thisArg. * * \code @@ -3607,7 +3593,7 @@ class PropertyCallbackInfo { * \return True if the intercepted function should throw if an error occurs. * Usually, `true` corresponds to `'use strict'`. * - * \note Always `false` when intercepting `Reflect.Set()` + * \note Always `false` when intercepting `Reflect.set()` * independent of the language mode. */ V8_INLINE bool ShouldThrowOnError() const; @@ -3902,13 +3888,29 @@ class V8_EXPORT Proxy : public Object { class V8_EXPORT WasmCompiledModule : public Object { public: typedef std::pair, size_t> SerializedModule; + // A buffer that is owned by the caller. + typedef std::pair CallerOwnedBuffer; + // Get the wasm-encoded bytes that were used to compile this module. + Local GetWasmWireBytes(); + // Serialize the compiled module. The serialized data does not include the + // uncompiled bytes. SerializedModule Serialize(); - static MaybeLocal Deserialize( - Isolate* isolate, const SerializedModule& serialized_data); + + // If possible, deserialize the module, otherwise compile it from the provided + // uncompiled bytes. + static MaybeLocal DeserializeOrCompile( + Isolate* isolate, const CallerOwnedBuffer& serialized_module, + const CallerOwnedBuffer& wire_bytes); V8_INLINE static WasmCompiledModule* Cast(Value* obj); private: + static MaybeLocal Deserialize( + Isolate* isolate, const CallerOwnedBuffer& serialized_module, + const CallerOwnedBuffer& wire_bytes); + static MaybeLocal Compile(Isolate* isolate, + const uint8_t* start, + size_t length); WasmCompiledModule(); static void CheckCast(Value* obj); }; @@ -4623,6 +4625,8 @@ class V8_EXPORT Template : public Data { */ void Set(Local name, Local value, PropertyAttribute attributes = None); + void SetPrivate(Local name, Local value, + PropertyAttribute attributes = None); V8_INLINE void Set(Isolate* isolate, const char* name, Local value); void SetAccessorProperty( @@ -4674,6 +4678,14 @@ class V8_EXPORT Template : public Data { Local signature = Local(), AccessControl settings = DEFAULT); + /** + * Like SetNativeDataProperty, but V8 will replace the native data property + * with a real data property on first access. + */ + void SetLazyDataProperty(Local name, AccessorNameGetterCallback getter, + Local data = Local(), + PropertyAttribute attribute = None); + /** * During template instantiation, sets the value with the intrinsic property * from the correct context. @@ -5095,6 +5107,14 @@ class V8_EXPORT FunctionTemplate : public Template { Local data = Local(), Local signature = Local(), int length = 0); + /** + * Creates a function template backed/cached by a private property. + */ + static Local NewWithCache( + Isolate* isolate, FunctionCallback callback, + Local cache_property, Local data = Local(), + Local signature = Local(), int length = 0); + /** Returns the unique function instance in the current execution context.*/ V8_DEPRECATE_SOON("Use maybe version", Local GetFunction()); V8_WARN_UNUSED_RESULT MaybeLocal GetFunction( @@ -5676,6 +5696,10 @@ class V8_EXPORT ResourceConstraints { void set_code_range_size(size_t limit_in_mb) { code_range_size_ = limit_in_mb; } + size_t max_zone_pool_size() const { return max_zone_pool_size_; } + void set_max_zone_pool_size(const size_t bytes) { + max_zone_pool_size_ = bytes; + } private: int max_semi_space_size_; @@ -5683,6 +5707,7 @@ class V8_EXPORT ResourceConstraints { int max_executable_size_; uint32_t* stack_limit_; size_t code_range_size_; + size_t max_zone_pool_size_; }; @@ -6145,11 +6170,11 @@ class V8_EXPORT PersistentHandleVisitor { // NOLINT enum class MemoryPressureLevel { kNone, kModerate, kCritical }; /** - * Interface for tracing through the embedder heap. During the v8 garbage + * Interface for tracing through the embedder heap. During a v8 garbage * collection, v8 collects hidden fields of all potential wrappers, and at the * end of its marking phase iterates the collection and asks the embedder to - * trace through its heap and use reporter to report each js object reachable - * from any of the given wrappers. + * trace through its heap and use reporter to report each JavaScript object + * reachable from any of the given wrappers. * * Before the first call to the TraceWrappersFrom function TracePrologue will be * called. When the garbage collection cycle is finished, TraceEpilogue will be @@ -6167,30 +6192,26 @@ class V8_EXPORT EmbedderHeapTracer { }; /** - * V8 will call this method with internal fields of found wrappers. The - * embedder is expected to store them in its marking deque and trace - * reachable wrappers from them when called through |AdvanceTracing|. + * Called by v8 to register internal fields of found wrappers. + * + * The embedder is expected to store them somewhere and trace reachable + * wrappers from them when called through |AdvanceTracing|. */ virtual void RegisterV8References( const std::vector >& internal_fields) = 0; /** - * Deprecated. - * TODO(hlopko) Remove once the migration to reporter is finished. - */ - virtual void TracePrologue() {} - - /** - * V8 will call this method at the beginning of a GC cycle. Embedder is - * expected to use EmbedderReachableReferenceReporter for reporting all - * reachable v8 objects. + * Called at the beginning of a GC cycle. */ - virtual void TracePrologue(EmbedderReachableReferenceReporter* reporter) {} + virtual void TracePrologue() = 0; /** - * Embedder is expected to trace its heap starting from wrappers reported by - * RegisterV8References method, and use reporter for all reachable wrappers. - * Embedder is expected to stop tracing by the given deadline. + * Called to to make a tracing step in the embedder. + * + * The embedder is expected to trace its heap starting from wrappers reported + * by RegisterV8References method, and report back all reachable wrappers. + * Furthermore, the embedder is expected to stop tracing by the given + * deadline. * * Returns true if there is still work to do. */ @@ -6198,22 +6219,25 @@ class V8_EXPORT EmbedderHeapTracer { AdvanceTracingActions actions) = 0; /** - * V8 will call this method at the end of a GC cycle. + * Called at the end of a GC cycle. * * Note that allocation is *not* allowed within |TraceEpilogue|. */ virtual void TraceEpilogue() = 0; /** - * Let embedder know v8 entered final marking pause (no more incremental steps - * will follow). + * Called upon entering the final marking pause. No more incremental marking + * steps will follow this call. */ - virtual void EnterFinalPause() {} + virtual void EnterFinalPause() = 0; /** - * Throw away all intermediate data and reset to the initial state. + * Called when tracing is aborted. + * + * The embedder is expected to throw away all intermediate data and reset to + * the initial state. */ - virtual void AbortTracing() {} + virtual void AbortTracing() = 0; /** * Returns the number of wrappers that are still to be traced by the embedder. @@ -6224,6 +6248,19 @@ class V8_EXPORT EmbedderHeapTracer { virtual ~EmbedderHeapTracer() = default; }; +/** + * Callback to the embedder used in SnapshotCreator to handle internal fields. + */ +typedef StartupData (*SerializeInternalFieldsCallback)(Local holder, + int index); + +/** + * Callback to the embedder used to deserialize internal fields. + */ +typedef void (*DeserializeInternalFieldsCallback)(Local holder, + int index, + StartupData payload); + /** * Isolate represents an isolated instance of the V8 engine. V8 isolates have * completely separate states. Objects from one isolate must not be used in @@ -6246,7 +6283,8 @@ class V8_EXPORT Isolate { create_histogram_callback(nullptr), add_histogram_sample_callback(nullptr), array_buffer_allocator(nullptr), - external_references(nullptr) {} + external_references(nullptr), + deserialize_internal_fields_callback(nullptr) {} /** * The optional entry_hook allows the host application to provide the @@ -6302,6 +6340,12 @@ class V8_EXPORT Isolate { * entire lifetime of the isolate. */ intptr_t* external_references; + + /** + * Specifies an optional callback to deserialize internal fields. It + * should match the SerializeInternalFieldCallback used to serialize. + */ + DeserializeInternalFieldsCallback deserialize_internal_fields_callback; }; @@ -7506,6 +7550,9 @@ class V8_EXPORT V8 { int* index); static Local GetEternal(Isolate* isolate, int index); + static void RegisterExternallyReferencedObject(internal::Object** object, + internal::Isolate* isolate); + template friend class PersistentValueMapBase; @@ -7528,7 +7575,7 @@ class V8_EXPORT V8 { /** * Helper class to create a snapshot data blob. */ -class SnapshotCreator { +class V8_EXPORT SnapshotCreator { public: enum class FunctionCodeHandling { kClear, kKeep }; @@ -7567,10 +7614,12 @@ class SnapshotCreator { * This must not be called from within a handle scope. * \param function_code_handling whether to include compiled function code * in the snapshot. + * \param callback to serialize embedder-set internal fields. * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The * caller acquires ownership of the data array in the return value. */ - StartupData CreateBlob(FunctionCodeHandling function_code_handling); + StartupData CreateBlob(FunctionCodeHandling function_code_handling, + SerializeInternalFieldsCallback callback = nullptr); // Disallow copying and assigning. SnapshotCreator(const SnapshotCreator&) = delete; @@ -7824,7 +7873,6 @@ class V8_EXPORT ExtensionConfiguration { const char** names_; }; - /** * A sandboxed execution context with its own set of built-in objects * and functions. @@ -8286,11 +8334,10 @@ class Internals { static const int kNodeStateIsPendingValue = 3; static const int kNodeStateIsNearDeathValue = 4; static const int kNodeIsIndependentShift = 3; - static const int kNodeIsPartiallyDependentShift = 4; static const int kNodeIsActiveShift = 4; - static const int kJSObjectType = 0xb9; - static const int kJSApiObjectType = 0xb8; + static const int kJSObjectType = 0xbc; + static const int kJSApiObjectType = 0xbb; static const int kFirstNonstringType = 0x80; static const int kOddballType = 0x83; static const int kForeignType = 0x87; @@ -8566,10 +8613,11 @@ P* PersistentBase::ClearWeak() { } template -void PersistentBase::RegisterExternalReference( - EmbedderReachableReferenceReporter* reporter) const { +void PersistentBase::RegisterExternalReference(Isolate* isolate) const { if (IsEmpty()) return; - reporter->ReportExternalReference(this->val_); + V8::RegisterExternallyReferencedObject( + reinterpret_cast(this->val_), + reinterpret_cast(isolate)); } template @@ -8581,17 +8629,6 @@ void PersistentBase::MarkIndependent() { I::kNodeIsIndependentShift); } - -template -void PersistentBase::MarkPartiallyDependent() { - typedef internal::Internals I; - if (this->IsEmpty()) return; - I::UpdateNodeFlag(reinterpret_cast(this->val_), - true, - I::kNodeIsPartiallyDependentShift); -} - - template void PersistentBase::MarkActive() { typedef internal::Internals I; diff --git a/deps/v8/infra/config/cq.cfg b/deps/v8/infra/config/cq.cfg index 3c645fd90b2268..e93895f3826335 100644 --- a/deps/v8/infra/config/cq.cfg +++ b/deps/v8/infra/config/cq.cfg @@ -104,7 +104,7 @@ verifiers { } builders { name: "v8_linux64_sanitizer_coverage_rel" - experiment_percentage: 100 + experiment_percentage: 20 } } buckets { diff --git a/deps/v8/infra/mb/mb_config.pyl b/deps/v8/infra/mb/mb_config.pyl index 2747be59093f10..d6a2a2dc4abe50 100644 --- a/deps/v8/infra/mb/mb_config.pyl +++ b/deps/v8/infra/mb/mb_config.pyl @@ -40,7 +40,7 @@ 'V8 Linux - shared': 'gn_release_x86_shared_verify_heap', 'V8 Linux - noi18n - debug': 'gn_debug_x86_no_i18n', # Linux64. - 'V8 Linux64 - builder': 'gn_release_x64', + 'V8 Linux64 - builder': 'gn_release_x64_valgrind', 'V8 Linux64 - debug builder': 'gn_debug_x64_valgrind', 'V8 Linux64 - custom snapshot - debug builder': 'gn_debug_x64_custom', 'V8 Linux64 - internal snapshot': 'gn_release_x64_internal', @@ -156,7 +156,7 @@ 'v8_linux_nosnap_dbg': 'gn_debug_x86_no_snap_trybot', 'v8_linux_gcc_compile_rel': 'gn_release_x86_gcc_minimal_symbols', 'v8_linux_gcc_rel': 'gn_release_x86_gcc_minimal_symbols', - 'v8_linux64_rel_ng': 'gn_release_x64_trybot', + 'v8_linux64_rel_ng': 'gn_release_x64_valgrind_trybot', 'v8_linux64_gyp_rel_ng': 'gyp_release_x64', 'v8_linux64_avx2_rel_ng': 'gn_release_x64_trybot', 'v8_linux64_avx2_dbg': 'gn_debug_x64_trybot', @@ -296,6 +296,10 @@ 'gn', 'release_bot', 'x64', 'tsan', 'swarming'], 'gn_release_x64_tsan_minimal_symbols': [ 'gn', 'release_bot', 'x64', 'tsan', 'minimal_symbols', 'swarming'], + 'gn_release_x64_valgrind': [ + 'gn', 'release_bot', 'x64', 'swarming', 'valgrind'], + 'gn_release_x64_valgrind_trybot': [ + 'gn', 'release_trybot', 'x64', 'swarming', 'valgrind'], # GN debug configs for x64. 'gn_debug_x64': [ @@ -317,7 +321,8 @@ 'gn_debug_x86_minimal_symbols': [ 'gn', 'debug_bot', 'x86', 'minimal_symbols', 'swarming'], 'gn_debug_x86_no_i18n': [ - 'gn', 'debug_bot', 'x86', 'v8_no_i18n'], + 'gn', 'debug_bot', 'x86', 'swarming', 'v8_disable_inspector', + 'v8_no_i18n'], 'gn_debug_x86_no_snap': [ 'gn', 'debug_bot', 'x86', 'swarming', 'v8_snapshot_none'], 'gn_debug_x86_no_snap_trybot': [ @@ -339,7 +344,8 @@ 'gn_release_x86_minimal_symbols': [ 'gn', 'release_bot', 'x86', 'minimal_symbols', 'swarming'], 'gn_release_x86_no_i18n_trybot': [ - 'gn', 'release_trybot', 'x86', 'swarming', 'v8_no_i18n'], + 'gn', 'release_trybot', 'x86', 'swarming', 'v8_disable_inspector', + 'v8_no_i18n'], 'gn_release_x86_no_snap': [ 'gn', 'release_bot', 'x86', 'swarming', 'v8_snapshot_none'], 'gn_release_x86_no_snap_shared_minimal_symbols': [ @@ -354,7 +360,8 @@ # Gyp debug configs for simulators. 'gyp_debug_simulate_x87_no_snap': [ - 'gyp', 'debug_bot', 'simulate_x87', 'swarming', 'v8_snapshot_none'], + 'gyp', 'debug_bot_static', 'simulate_x87', 'swarming', + 'v8_snapshot_none'], # Gyp debug configs for x86. 'gyp_debug_x86': [ @@ -461,6 +468,12 @@ 'v8_optimized_debug'], }, + 'debug_bot_static': { + 'mixins': [ + 'debug', 'static', 'goma', 'v8_enable_slow_dchecks', + 'v8_optimized_debug'], + }, + 'debug_trybot': { 'mixins': ['debug_bot', 'minimal_symbols'], }, @@ -613,6 +626,11 @@ 'gyp_defines': 'v8_enable_i18n_support=0 icu_use_data_file_flag=0', }, + 'v8_disable_inspector': { + 'gn_args': 'v8_enable_inspector=false', + 'gyp_defines': 'v8_enable_inspector=0 ', + }, + 'v8_enable_disassembler': { 'gn_args': 'v8_enable_disassembler=true', 'gyp_defines': 'v8_enable_disassembler=1', diff --git a/deps/v8/samples/samples.gyp b/deps/v8/samples/samples.gyp index e5e9ef0f8ccb20..e7c26cf2629d21 100644 --- a/deps/v8/samples/samples.gyp +++ b/deps/v8/samples/samples.gyp @@ -36,6 +36,7 @@ 'type': 'executable', 'dependencies': [ '../src/v8.gyp:v8', + '../src/v8.gyp:v8_libbase', '../src/v8.gyp:v8_libplatform', ], 'include_dirs': [ diff --git a/deps/v8/src/DEPS b/deps/v8/src/DEPS index b1c428d5d79845..9114669a6d5e77 100644 --- a/deps/v8/src/DEPS +++ b/deps/v8/src/DEPS @@ -8,6 +8,7 @@ include_rules = [ "-src/heap", "+src/heap/heap.h", "+src/heap/heap-inl.h", + "-src/inspector", "-src/interpreter", "+src/interpreter/bytecode-array-iterator.h", "+src/interpreter/bytecode-decoder.h", diff --git a/deps/v8/src/accessors.cc b/deps/v8/src/accessors.cc index da44151b3edbdd..9ec24b84c7c586 100644 --- a/deps/v8/src/accessors.cc +++ b/deps/v8/src/accessors.cc @@ -19,13 +19,9 @@ namespace v8 { namespace internal { - Handle Accessors::MakeAccessor( - Isolate* isolate, - Handle name, - AccessorNameGetterCallback getter, - AccessorNameSetterCallback setter, - PropertyAttributes attributes) { + Isolate* isolate, Handle name, AccessorNameGetterCallback getter, + AccessorNameBooleanSetterCallback setter, PropertyAttributes attributes) { Factory* factory = isolate->factory(); Handle info = factory->NewAccessorInfo(); info->set_property_attributes(attributes); @@ -33,6 +29,7 @@ Handle Accessors::MakeAccessor( info->set_all_can_write(false); info->set_is_special_data_property(true); info->set_is_sloppy(false); + info->set_replace_on_access(false); name = factory->InternalizeName(name); info->set_name(*name); Handle get = v8::FromCData(isolate, getter); @@ -106,7 +103,7 @@ MUST_USE_RESULT MaybeHandle ReplaceAccessorWithDataProperty( void Accessors::ReconfigureToDataProperty( v8::Local key, v8::Local val, - const v8::PropertyCallbackInfo& info) { + const v8::PropertyCallbackInfo& info) { i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); HandleScope scope(isolate); Handle receiver = Utils::OpenHandle(*info.This()); @@ -116,7 +113,11 @@ void Accessors::ReconfigureToDataProperty( Handle value = Utils::OpenHandle(*val); MaybeHandle result = ReplaceAccessorWithDataProperty(isolate, receiver, holder, name, value); - if (result.is_null()) isolate->OptionalRescheduleException(false); + if (result.is_null()) { + isolate->OptionalRescheduleException(false); + } else { + info.GetReturnValue().Set(true); + } } // @@ -151,6 +152,8 @@ void Accessors::ArrayLengthGetter( v8::Local name, const v8::PropertyCallbackInfo& info) { i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); + RuntimeCallTimerScope timer( + isolate, &RuntimeCallStats::AccessorNameGetterCallback_ArrayLength); DisallowHeapAllocation no_allocation; HandleScope scope(isolate); JSArray* holder = JSArray::cast(*Utils::OpenHandle(*info.Holder())); @@ -158,11 +161,9 @@ void Accessors::ArrayLengthGetter( info.GetReturnValue().Set(Utils::ToLocal(Handle(result, isolate))); } - void Accessors::ArrayLengthSetter( - v8::Local name, - v8::Local val, - const v8::PropertyCallbackInfo& info) { + v8::Local name, v8::Local val, + const v8::PropertyCallbackInfo& info) { i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); HandleScope scope(isolate); @@ -178,17 +179,21 @@ void Accessors::ArrayLengthSetter( JSArray::SetLength(array, length); - if (info.ShouldThrowOnError()) { - uint32_t actual_new_len = 0; - CHECK(array->length()->ToArrayLength(&actual_new_len)); - // Throw TypeError if there were non-deletable elements. - if (actual_new_len != length) { + uint32_t actual_new_len = 0; + CHECK(array->length()->ToArrayLength(&actual_new_len)); + // Fail if there were non-deletable elements. + if (actual_new_len != length) { + if (info.ShouldThrowOnError()) { Factory* factory = isolate->factory(); isolate->Throw(*factory->NewTypeError( MessageTemplate::kStrictDeleteProperty, factory->NewNumberFromUint(actual_new_len - 1), array)); isolate->OptionalRescheduleException(false); + } else { + info.GetReturnValue().Set(false); } + } else { + info.GetReturnValue().Set(true); } } @@ -202,6 +207,50 @@ Handle Accessors::ArrayLengthInfo( attributes); } +// +// Accessors::ModuleNamespaceEntry +// + +void Accessors::ModuleNamespaceEntryGetter( + v8::Local name, const v8::PropertyCallbackInfo& info) { + i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); + HandleScope scope(isolate); + JSModuleNamespace* holder = + JSModuleNamespace::cast(*Utils::OpenHandle(*info.Holder())); + Handle result; + if (!holder->GetExport(Handle::cast(Utils::OpenHandle(*name))) + .ToHandle(&result)) { + isolate->OptionalRescheduleException(false); + } else { + info.GetReturnValue().Set(Utils::ToLocal(result)); + } +} + +void Accessors::ModuleNamespaceEntrySetter( + v8::Local name, v8::Local val, + const v8::PropertyCallbackInfo& info) { + i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); + HandleScope scope(isolate); + Factory* factory = isolate->factory(); + Handle holder = + Handle::cast(Utils::OpenHandle(*info.Holder())); + + if (info.ShouldThrowOnError()) { + isolate->Throw(*factory->NewTypeError( + MessageTemplate::kStrictReadOnlyProperty, Utils::OpenHandle(*name), + i::Object::TypeOf(isolate, holder), holder)); + isolate->OptionalRescheduleException(false); + } else { + info.GetReturnValue().Set(false); + } +} + +Handle Accessors::ModuleNamespaceEntryInfo( + Isolate* isolate, Handle name, PropertyAttributes attributes) { + return MakeAccessor(isolate, name, &ModuleNamespaceEntryGetter, + &ModuleNamespaceEntrySetter, attributes); +} + // // Accessors::StringLength @@ -211,6 +260,8 @@ void Accessors::StringLengthGetter( v8::Local name, const v8::PropertyCallbackInfo& info) { i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); + RuntimeCallTimerScope timer( + isolate, &RuntimeCallStats::AccessorNameGetterCallback_StringLength); DisallowHeapAllocation no_allocation; HandleScope scope(isolate); @@ -417,40 +468,6 @@ Handle Accessors::ScriptCompilationTypeInfo( } -// -// Accessors::ScriptGetLineEnds -// - - -void Accessors::ScriptLineEndsGetter( - v8::Local name, - const v8::PropertyCallbackInfo& info) { - i::Isolate* isolate = reinterpret_cast(info.GetIsolate()); - HandleScope scope(isolate); - Handle object = Utils::OpenHandle(*info.Holder()); - Handle - +

I C E

Your IC-Explorer. + +
+
+ 0 uninitialized
+ . premonomorphic
+ 1 monomorphic
+ ^ recompute handler
+ P polymorphic
+ N megamorphic
+ G generic +
+
+

Usage

Run your script with --trace_ic and upload on this page:
/path/to/d8 --trace_ic your_script.js > trace.txt

Data

diff --git a/deps/v8/tools/ignition/linux_perf_report.py b/deps/v8/tools/ignition/linux_perf_report.py index eaf85b3f91efd2..69db37cbae4b27 100755 --- a/deps/v8/tools/ignition/linux_perf_report.py +++ b/deps/v8/tools/ignition/linux_perf_report.py @@ -52,6 +52,8 @@ COMPILER_SYMBOLS_RE = re.compile( r"v8::internal::(?:\(anonymous namespace\)::)?Compile|v8::internal::Parser") +JIT_CODE_SYMBOLS_RE = re.compile( + r"(LazyCompile|Compile|Eval|Script):(\*|~)") def strip_function_parameters(symbol): @@ -70,7 +72,8 @@ def strip_function_parameters(symbol): return symbol[:-pos] -def collapsed_callchains_generator(perf_stream, show_all=False, +def collapsed_callchains_generator(perf_stream, hide_other=False, + hide_compiler=False, hide_jit=False, show_full_signatures=False): current_chain = [] skip_until_end_of_chain = False @@ -85,7 +88,8 @@ def collapsed_callchains_generator(perf_stream, show_all=False, # Empty line signals the end of the callchain. if not line: - if not skip_until_end_of_chain and current_chain and show_all: + if (not skip_until_end_of_chain and current_chain + and not hide_other): current_chain.append("[other]") yield current_chain # Reset parser status. @@ -101,14 +105,26 @@ def collapsed_callchains_generator(perf_stream, show_all=False, symbol = line.split(" ", 1)[1].split("+", 1)[0] if not show_full_signatures: symbol = strip_function_parameters(symbol) + + # Avoid chains of [unknown] + if (symbol == "[unknown]" and current_chain and + current_chain[-1] == "[unknown]"): + continue + current_chain.append(symbol) if symbol.startswith("BytecodeHandler:"): + current_chain.append("[interpreter]") yield current_chain skip_until_end_of_chain = True + elif JIT_CODE_SYMBOLS_RE.match(symbol): + if not hide_jit: + current_chain.append("[jit]") + yield current_chain + skip_until_end_of_chain = True elif symbol == "Stub:CEntryStub" and compiler_symbol_in_chain: - if show_all: - current_chain[-1] = "[compiler]" + if not hide_compiler: + current_chain.append("[compiler]") yield current_chain skip_until_end_of_chain = True elif COMPILER_SYMBOLS_RE.match(symbol): @@ -181,8 +197,18 @@ def parse_command_line(): dest="output_flamegraph" ) command_line_parser.add_argument( - "--show-all", "-a", - help="show samples outside Ignition bytecode handlers", + "--hide-other", + help="Hide other samples", + action="store_true" + ) + command_line_parser.add_argument( + "--hide-compiler", + help="Hide samples during compilation", + action="store_true" + ) + command_line_parser.add_argument( + "--hide-jit", + help="Hide samples from JIT code execution", action="store_true" ) command_line_parser.add_argument( @@ -210,8 +236,8 @@ def main(): stdout=subprocess.PIPE) callchains = collapsed_callchains_generator( - perf.stdout, program_options.show_all, - program_options.show_full_signatures) + perf.stdout, program_options.hide_other, program_options.hide_compiler, + program_options.hide_jit, program_options.show_full_signatures) if program_options.output_flamegraph: write_flamegraph_input_file(program_options.output_stream, callchains) diff --git a/deps/v8/tools/ignition/linux_perf_report_test.py b/deps/v8/tools/ignition/linux_perf_report_test.py index d9cef75dfff275..9d163c8adbfe64 100644 --- a/deps/v8/tools/ignition/linux_perf_report_test.py +++ b/deps/v8/tools/ignition/linux_perf_report_test.py @@ -40,6 +40,9 @@ 11111111 Builtin:InterpreterEntryTrampoline 22222222 bar + 00000000 hello + 11111111 LazyCompile:~Foo + 11111111 Builtin:InterpreterEntryTrampoline 22222222 bar """ @@ -50,22 +53,26 @@ def test_collapsed_callchains_generator(self): perf_stream = StringIO.StringIO(PERF_SCRIPT_OUTPUT) callchains = list(ipr.collapsed_callchains_generator(perf_stream)) self.assertListEqual(callchains, [ - ["foo", "BytecodeHandler:bar"], - ["foo", "BytecodeHandler:bar"], - ["beep", "BytecodeHandler:bar"], + ['firstSymbol', 'secondSymbol', '[other]'], + ["foo", "BytecodeHandler:bar", "[interpreter]"], + ["foo", "BytecodeHandler:bar", "[interpreter]"], + ["beep", "BytecodeHandler:bar", "[interpreter]"], + ["hello", "v8::internal::Compiler", "Stub:CEntryStub", "[compiler]"], + ["Lost", "[misattributed]"], + ["hello", "LazyCompile:~Foo", "[jit]"], ["[entry trampoline]"], ]) - def test_collapsed_callchains_generator_show_other(self): + def test_collapsed_callchains_generator_hide_other(self): perf_stream = StringIO.StringIO(PERF_SCRIPT_OUTPUT) callchains = list(ipr.collapsed_callchains_generator(perf_stream, - show_all=True)) + hide_other=True, + hide_compiler=True, + hide_jit=True)) self.assertListEqual(callchains, [ - ['firstSymbol', 'secondSymbol', '[other]'], - ["foo", "BytecodeHandler:bar"], - ["foo", "BytecodeHandler:bar"], - ["beep", "BytecodeHandler:bar"], - ["hello", "v8::internal::Compiler", "[compiler]"], + ["foo", "BytecodeHandler:bar", "[interpreter]"], + ["foo", "BytecodeHandler:bar", "[interpreter]"], + ["beep", "BytecodeHandler:bar", "[interpreter]"], ["Lost", "[misattributed]"], ["[entry trampoline]"], ]) @@ -125,7 +132,7 @@ def test_multiple_handlers(self): """) callchains = list(ipr.collapsed_callchains_generator(perf_stream, False)) self.assertListEqual(callchains, [ - ["foo", "BytecodeHandler:first"], + ["foo", "BytecodeHandler:first", "[interpreter]"], ]) def test_compiler_symbols_regex(self): @@ -137,6 +144,15 @@ def test_compiler_symbols_regex(self): for compiler_symbol in compiler_symbols: self.assertTrue(ipr.COMPILER_SYMBOLS_RE.match(compiler_symbol)) + def test_jit_code_symbols_regex(self): + jit_code_symbols = [ + "LazyCompile:~Foo blah.js", + "Eval:*", + "Script:*Bar tmp.js", + ] + for jit_code_symbol in jit_code_symbols: + self.assertTrue(ipr.JIT_CODE_SYMBOLS_RE.match(jit_code_symbol)) + def test_strip_function_parameters(self): def should_match(signature, name): self.assertEqual(ipr.strip_function_parameters(signature), name) @@ -145,3 +161,6 @@ def should_match(signature, name): should_match("Foo(foomatic::(anonymous)::bar(baz))", "Foo"), should_match("v8::(anonymous ns)::bar(baz, poe)", "v8::(anonymous ns)::bar") + +if __name__ == '__main__': + unittest.main() diff --git a/deps/v8/tools/parser-shell.cc b/deps/v8/tools/parser-shell.cc index 43d25781659e5c..0517bbf0e69e88 100644 --- a/deps/v8/tools/parser-shell.cc +++ b/deps/v8/tools/parser-shell.cc @@ -93,9 +93,8 @@ std::pair RunBaselineParser( i::ScriptData* cached_data_impl = NULL; // First round of parsing (produce data to cache). { - Zone zone(reinterpret_cast(isolate)->allocator()); + Zone zone(reinterpret_cast(isolate)->allocator(), ZONE_NAME); ParseInfo info(&zone, script); - info.set_global(); info.set_cached_data(&cached_data_impl); info.set_compile_options(v8::ScriptCompiler::kProduceParserCache); v8::base::ElapsedTimer timer; @@ -111,9 +110,8 @@ std::pair RunBaselineParser( } // Second round of parsing (consume cached data). { - Zone zone(reinterpret_cast(isolate)->allocator()); + Zone zone(reinterpret_cast(isolate)->allocator(), ZONE_NAME); ParseInfo info(&zone, script); - info.set_global(); info.set_cached_data(&cached_data_impl); info.set_compile_options(v8::ScriptCompiler::kConsumeParserCache); v8::base::ElapsedTimer timer; diff --git a/deps/v8/tools/parser-shell.gyp b/deps/v8/tools/parser-shell.gyp index 4ef1a82d719572..9b94888edfd7a0 100644 --- a/deps/v8/tools/parser-shell.gyp +++ b/deps/v8/tools/parser-shell.gyp @@ -37,6 +37,7 @@ 'type': 'executable', 'dependencies': [ '../src/v8.gyp:v8', + '../src/v8.gyp:v8_libbase', '../src/v8.gyp:v8_libplatform', ], 'conditions': [ diff --git a/deps/v8/tools/presubmit.py b/deps/v8/tools/presubmit.py index 3be9caf0613bbe..f9ae2bdea46584 100755 --- a/deps/v8/tools/presubmit.py +++ b/deps/v8/tools/presubmit.py @@ -396,13 +396,6 @@ def ProcessFiles(self, files, path): print "Total violating files: %s" % violations return success - -def CheckExternalReferenceRegistration(workspace): - code = subprocess.call( - [sys.executable, join(workspace, "tools", "external-reference-check.py")]) - return code == 0 - - def _CheckStatusFileForDuplicateKeys(filepath): comma_space_bracket = re.compile(", *]") lines = [] @@ -503,7 +496,6 @@ def Main(): print "Running copyright header, trailing whitespaces and " \ "two empty lines between declarations check..." success &= SourceProcessor().Run(workspace) - success &= CheckExternalReferenceRegistration(workspace) success &= CheckStatusFiles(workspace) if success: return 0 diff --git a/deps/v8/tools/profviz/composer.js b/deps/v8/tools/profviz/composer.js index 108911de696037..ce625addca8f3b 100644 --- a/deps/v8/tools/profviz/composer.js +++ b/deps/v8/tools/profviz/composer.js @@ -106,8 +106,6 @@ function PlotScriptComposer(kResX, kResY, error_output) { new TimerEvent("recompile async", "#CC4499", false, 1), 'V8.CompileEvalMicroSeconds': new TimerEvent("compile eval", "#CC4400", true, 0), - 'V8.IcMiss': - new TimerEvent("ic miss", "#CC9900", false, 0), 'V8.ParseMicroSeconds': new TimerEvent("parse", "#00CC00", true, 0), 'V8.PreParseMicroSeconds': diff --git a/deps/v8/tools/profviz/stdio.js b/deps/v8/tools/profviz/stdio.js index 5a8311dfb28357..8ba12e3ce758a0 100644 --- a/deps/v8/tools/profviz/stdio.js +++ b/deps/v8/tools/profviz/stdio.js @@ -30,10 +30,10 @@ var distortion_per_entry = 0; var range_start_override = undefined; var range_end_override = undefined; -if (!processor.parse()) processor.printUsageAndExit();; +if (!processor.parse()) processor.printUsageAndExit(); var result = processor.result(); var distortion = parseInt(result.distortion); -if (isNaN(distortion)) processor.printUsageAndExit();; +if (isNaN(distortion)) processor.printUsageAndExit(); // Convert picoseconds to milliseconds. distortion_per_entry = distortion / 1000000; var rangelimits = result.range.split(","); @@ -43,7 +43,7 @@ if (!isNaN(range_start)) range_start_override = range_start; if (!isNaN(range_end)) range_end_override = range_end; var kResX = 1600; -var kResY = 700; +var kResY = 600; function log_error(text) { print(text); quit(1); diff --git a/deps/v8/tools/release/auto_roll.py b/deps/v8/tools/release/auto_roll.py index c1a99e8d11c52e..d1a3f48cf8c36d 100755 --- a/deps/v8/tools/release/auto_roll.py +++ b/deps/v8/tools/release/auto_roll.py @@ -20,7 +20,7 @@ https://v8-roll.appspot.com/ This only works with a Google account. -CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_precise_blink_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel""") +CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel""") class Preparation(Step): MESSAGE = "Preparation." diff --git a/deps/v8/tools/release/test_scripts.py b/deps/v8/tools/release/test_scripts.py index ab92e89f3a05ca..a344376628ebdf 100644 --- a/deps/v8/tools/release/test_scripts.py +++ b/deps/v8/tools/release/test_scripts.py @@ -1044,7 +1044,7 @@ def CheckVersionCommit(): https://v8-roll.appspot.com/ This only works with a Google account. -CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_precise_blink_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel +CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel TBR=reviewer@chromium.org""" diff --git a/deps/v8/tools/run-tests.py b/deps/v8/tools/run-tests.py index f248dff5cc3eb4..e94f59939f7dec 100755 --- a/deps/v8/tools/run-tests.py +++ b/deps/v8/tools/run-tests.py @@ -67,6 +67,8 @@ "bot_default": [ "mjsunit", "cctest", + "debugger", + "inspector", "webkit", "fuzzer", "message", @@ -78,6 +80,8 @@ "default": [ "mjsunit", "cctest", + "debugger", + "inspector", "fuzzer", "message", "preparser", @@ -88,6 +92,8 @@ "optimize_for_size": [ "mjsunit", "cctest", + "debugger", + "inspector", "webkit", "intl", ], @@ -255,6 +261,9 @@ def BuildOptions(): result.add_option("--download-data-only", help="Deprecated", default=False, action="store_true") + result.add_option("--enable-inspector", + help="Indicates a build with inspector support", + default=False, action="store_true") result.add_option("--extra-flags", help="Additional flags to pass to each test command", default="") @@ -447,8 +456,13 @@ def ProcessOptions(options): print(">>> Latest GN build found is %s" % latest_config) options.outdir = os.path.join(DEFAULT_OUT_GN, latest_config) - build_config_path = os.path.join( - BASE_DIR, options.outdir, "v8_build_config.json") + if options.buildbot: + build_config_path = os.path.join( + BASE_DIR, options.outdir, options.mode, "v8_build_config.json") + else: + build_config_path = os.path.join( + BASE_DIR, options.outdir, "v8_build_config.json") + if os.path.exists(build_config_path): try: with open(build_config_path) as f: @@ -459,6 +473,10 @@ def ProcessOptions(options): return False options.auto_detect = True + # In auto-detect mode the outdir is always where we found the build config. + # This ensures that we'll also take the build products from there. + options.outdir = os.path.dirname(build_config_path) + options.arch_and_mode = None options.arch = build_config["v8_target_cpu"] if options.arch == 'x86': @@ -466,6 +484,7 @@ def ProcessOptions(options): options.arch = 'ia32' options.asan = build_config["is_asan"] options.dcheck_always_on = build_config["dcheck_always_on"] + options.enable_inspector = build_config["v8_enable_inspector"] options.mode = 'debug' if build_config["is_debug"] else 'release' options.msan = build_config["is_msan"] options.no_i18n = not build_config["v8_enable_i18n_support"] @@ -592,6 +611,13 @@ def CheckTestMode(name, option): if options.no_i18n: TEST_MAP["bot_default"].remove("intl") TEST_MAP["default"].remove("intl") + if not options.enable_inspector: + TEST_MAP["default"].remove("inspector") + TEST_MAP["bot_default"].remove("inspector") + TEST_MAP["optimize_for_size"].remove("inspector") + TEST_MAP["default"].remove("debugger") + TEST_MAP["bot_default"].remove("debugger") + TEST_MAP["optimize_for_size"].remove("debugger") return True @@ -702,15 +728,15 @@ def Execute(arch, mode, args, options, suites): shell_dir = options.shell_dir if not shell_dir: - if options.buildbot: + if options.auto_detect: + # If an output dir with a build was passed, test directly in that + # directory. + shell_dir = os.path.join(BASE_DIR, options.outdir) + elif options.buildbot: # TODO(machenbach): Get rid of different output folder location on # buildbot. Currently this is capitalized Release and Debug. shell_dir = os.path.join(BASE_DIR, options.outdir, mode) mode = BuildbotToV8Mode(mode) - elif options.auto_detect: - # If an output dir with a build was passed, test directly in that - # directory. - shell_dir = os.path.join(BASE_DIR, options.outdir) else: shell_dir = os.path.join( BASE_DIR, @@ -733,14 +759,8 @@ def Execute(arch, mode, args, options, suites): # Predictable mode is slower. options.timeout *= 2 - # TODO(machenbach): Remove temporary verbose output on windows after - # debugging driver-hung-up on XP. - verbose_output = ( - options.verbose or - utils.IsWindows() and options.progress == "verbose" - ) ctx = context.Context(arch, MODES[mode]["execution_mode"], shell_dir, - mode_flags, verbose_output, + mode_flags, options.verbose, options.timeout, options.isolates, options.command_prefix, @@ -851,7 +871,7 @@ def iter_seed_flags(): run_networked = not options.no_network if not run_networked: - if verbose_output: + if options.verbose: print("Network distribution disabled, running tests locally.") elif utils.GuessOS() != "linux": print("Network distribution is only supported on Linux, sorry!") diff --git a/deps/v8/tools/sanitizers/sancov_merger.py b/deps/v8/tools/sanitizers/sancov_merger.py index a4cfec1b0c49c7..867f8b42582167 100755 --- a/deps/v8/tools/sanitizers/sancov_merger.py +++ b/deps/v8/tools/sanitizers/sancov_merger.py @@ -7,7 +7,7 @@ When merging test runner output, the sancov files are expected to be located in one directory with the file-name pattern: -.test..sancov +.test...sancov For each executable, this script writes a new file: .result.sancov @@ -48,7 +48,7 @@ # Regexp to find sancov file as output by the v8 test runner. Also grabs the # executable name in group 1. -SANCOV_FILE_RE = re.compile(r'^(.*)\.test\.\d+\.sancov$') +SANCOV_FILE_RE = re.compile(r'^(.*)\.test\.\d+\.\d+\.sancov$') # Regexp to find sancov result files as returned from swarming. SANCOV_RESULTS_FILE_RE = re.compile(r'^.*\.result\.sancov$') diff --git a/deps/v8/tools/sanitizers/sancov_merger_test.py b/deps/v8/tools/sanitizers/sancov_merger_test.py index 93b89eb8a7b2fd..899c716a5a4e40 100644 --- a/deps/v8/tools/sanitizers/sancov_merger_test.py +++ b/deps/v8/tools/sanitizers/sancov_merger_test.py @@ -11,19 +11,19 @@ # executable name -> file list. FILE_MAP = { 'd8': [ - 'd8.test.1.sancov', - 'd8.test.2.sancov', - 'd8.test.3.sancov', - 'd8.test.4.sancov', - 'd8.test.5.sancov', - 'd8.test.6.sancov', - 'd8.test.7.sancov', + 'd8.test.1.1.sancov', + 'd8.test.2.1.sancov', + 'd8.test.3.1.sancov', + 'd8.test.4.1.sancov', + 'd8.test.5.1.sancov', + 'd8.test.5.2.sancov', + 'd8.test.6.1.sancov', ], 'cctest': [ - 'cctest.test.1.sancov', - 'cctest.test.2.sancov', - 'cctest.test.3.sancov', - 'cctest.test.4.sancov', + 'cctest.test.1.1.sancov', + 'cctest.test.2.1.sancov', + 'cctest.test.3.1.sancov', + 'cctest.test.4.1.sancov', ], } @@ -32,42 +32,42 @@ # (flag, path, executable name, intermediate result index, file list). EXPECTED_INPUTS_2 = [ (False, '/some/path', 'cctest', 0, [ - 'cctest.test.1.sancov', - 'cctest.test.2.sancov']), + 'cctest.test.1.1.sancov', + 'cctest.test.2.1.sancov']), (False, '/some/path', 'cctest', 1, [ - 'cctest.test.3.sancov', - 'cctest.test.4.sancov']), + 'cctest.test.3.1.sancov', + 'cctest.test.4.1.sancov']), (False, '/some/path', 'd8', 0, [ - 'd8.test.1.sancov', - 'd8.test.2.sancov', - 'd8.test.3.sancov', - 'd8.test.4.sancov']), + 'd8.test.1.1.sancov', + 'd8.test.2.1.sancov', + 'd8.test.3.1.sancov', + 'd8.test.4.1.sancov']), (False, '/some/path', 'd8', 1, [ - 'd8.test.5.sancov', - 'd8.test.6.sancov', - 'd8.test.7.sancov']), + 'd8.test.5.1.sancov', + 'd8.test.5.2.sancov', + 'd8.test.6.1.sancov']), ] # The same for 4 cpus. EXPECTED_INPUTS_4 = [ (True, '/some/path', 'cctest', 0, [ - 'cctest.test.1.sancov', - 'cctest.test.2.sancov']), + 'cctest.test.1.1.sancov', + 'cctest.test.2.1.sancov']), (True, '/some/path', 'cctest', 1, [ - 'cctest.test.3.sancov', - 'cctest.test.4.sancov']), + 'cctest.test.3.1.sancov', + 'cctest.test.4.1.sancov']), (True, '/some/path', 'd8', 0, [ - 'd8.test.1.sancov', - 'd8.test.2.sancov']), + 'd8.test.1.1.sancov', + 'd8.test.2.1.sancov']), (True, '/some/path', 'd8', 1, [ - 'd8.test.3.sancov', - 'd8.test.4.sancov']), + 'd8.test.3.1.sancov', + 'd8.test.4.1.sancov']), (True, '/some/path', 'd8', 2, [ - 'd8.test.5.sancov', - 'd8.test.6.sancov']), + 'd8.test.5.1.sancov', + 'd8.test.5.2.sancov']), (True, '/some/path', 'd8', 3, [ - 'd8.test.7.sancov'])] + 'd8.test.6.1.sancov'])] class MergerTests(unittest.TestCase): diff --git a/deps/v8/tools/testrunner/local/execution.py b/deps/v8/tools/testrunner/local/execution.py index f3d11a8b5cf377..4cb9e45a035ec2 100644 --- a/deps/v8/tools/testrunner/local/execution.py +++ b/deps/v8/tools/testrunner/local/execution.py @@ -149,8 +149,9 @@ def _rename_coverage_data(self, output, context): Rename files with PIDs to files with unique test IDs, because the number of tests might be higher than pid_max. E.g.: - d8.1234.sancov -> d8.test.1.sancov, where 1234 was the process' PID - and 1 is the test ID. + d8.1234.sancov -> d8.test.42.1.sancov, where 1234 was the process' PID, + 42 is the test ID and 1 is the attempt (the same test might be rerun on + failures). """ if context.sancov_dir and output.pid is not None: sancov_file = os.path.join( @@ -160,7 +161,10 @@ def _rename_coverage_data(self, output, context): if os.path.exists(sancov_file): parts = sancov_file.split(".") new_sancov_file = ".".join( - parts[:-2] + ["test", str(self.test.id)] + parts[-1:]) + parts[:-2] + + ["test", str(self.test.id), str(self.test.run)] + + parts[-1:] + ) assert not os.path.exists(new_sancov_file) os.rename(sancov_file, new_sancov_file) diff --git a/deps/v8/tools/testrunner/testrunner.isolate b/deps/v8/tools/testrunner/testrunner.isolate index 1e8e9dccb99663..533ef68c8feef8 100644 --- a/deps/v8/tools/testrunner/testrunner.isolate +++ b/deps/v8/tools/testrunner/testrunner.isolate @@ -20,5 +20,12 @@ ], }, }], + ['is_gn==1', { + 'variables': { + 'files': [ + '<(PRODUCT_DIR)/v8_build_config.json', + ], + }, + }], ], } diff --git a/deps/v8/tools/turbolizer/schedule-view.js b/deps/v8/tools/turbolizer/schedule-view.js index 2cd49c991fdd5d..ef4789211d3c48 100644 --- a/deps/v8/tools/turbolizer/schedule-view.js +++ b/deps/v8/tools/turbolizer/schedule-view.js @@ -77,7 +77,7 @@ class ScheduleView extends TextView { // Parse opcode including [] [ [/^[A-Za-z0-9_]+(\[.*\])?$/, NODE_STYLE, -1], - [/^[A-Za-z0-9_]+(\[.*\])?/, NODE_STYLE, 3] + [/^[A-Za-z0-9_]+(\[(\[.*?\]|.)*?\])?/, NODE_STYLE, 3] ], // Parse optional parameters [ diff --git a/deps/v8/tools/update-wasm-fuzzers.sh b/deps/v8/tools/update-wasm-fuzzers.sh index 3652829c8d84fd..a58681f6826807 100755 --- a/deps/v8/tools/update-wasm-fuzzers.sh +++ b/deps/v8/tools/update-wasm-fuzzers.sh @@ -12,30 +12,30 @@ cd ${TOOLS_DIR}/.. rm -rf test/fuzzer/wasm rm -rf test/fuzzer/wasm_asmjs -make x64.debug -j +make x64.release -j mkdir -p test/fuzzer/wasm mkdir -p test/fuzzer/wasm_asmjs # asm.js ./tools/run-tests.py -j8 --variants=default --timeout=10 --arch=x64 \ - --mode=debug --no-presubmit --extra-flags="--dump-wasm-module \ + --mode=release --no-presubmit --extra-flags="--dump-wasm-module \ --dump-wasm-module-path=./test/fuzzer/wasm_asmjs/" mjsunit/wasm/asm* ./tools/run-tests.py -j8 --variants=default --timeout=10 --arch=x64 \ - --mode=debug --no-presubmit --extra-flags="--dump-wasm-module \ + --mode=release --no-presubmit --extra-flags="--dump-wasm-module \ --dump-wasm-module-path=./test/fuzzer/wasm_asmjs/" mjsunit/asm/* ./tools/run-tests.py -j8 --variants=default --timeout=10 --arch=x64 \ - --mode=debug --no-presubmit --extra-flags="--dump-wasm-module \ + --mode=release --no-presubmit --extra-flags="--dump-wasm-module \ --dump-wasm-module-path=./test/fuzzer/wasm_asmjs/" mjsunit/regress/asm/* # WASM ./tools/run-tests.py -j8 --variants=default --timeout=10 --arch=x64 \ - --mode=debug --no-presubmit --extra-flags="--dump-wasm-module \ + --mode=release --no-presubmit --extra-flags="--dump-wasm-module \ --dump-wasm-module-path=./test/fuzzer/wasm/" unittests ./tools/run-tests.py -j8 --variants=default --timeout=10 --arch=x64 \ - --mode=debug --no-presubmit --extra-flags="--dump-wasm-module \ + --mode=release --no-presubmit --extra-flags="--dump-wasm-module \ --dump-wasm-module-path=./test/fuzzer/wasm/" mjsunit/wasm/* ./tools/run-tests.py -j8 --variants=default --timeout=10 --arch=x64 \ - --mode=debug --no-presubmit --extra-flags="--dump-wasm-module \ + --mode=release --no-presubmit --extra-flags="--dump-wasm-module \ --dump-wasm-module-path=./test/fuzzer/wasm/" \ $(cd test/; ls cctest/wasm/test-*.cc | \ sed -es/wasm\\///g | sed -es/[.]cc/\\/\\*/g) diff --git a/deps/v8/tools/whitespace.txt b/deps/v8/tools/whitespace.txt index 2229d87d53dd65..0f4384f4e3185a 100644 --- a/deps/v8/tools/whitespace.txt +++ b/deps/v8/tools/whitespace.txt @@ -6,4 +6,4 @@ A Smi balks into a war and says: "I'm so deoptimized today!" The doubles heard this and started to unbox. The Smi looked at them when a crazy v8-autoroll account showed up...... -The autoroller bought a round of Himbeerbrause. Suddenly ... +The autoroller bought a round of Himbeerbrause. Suddenly ....... diff --git a/deps/v8_inspector/README.md b/deps/v8_inspector/README.md deleted file mode 100644 index 2ea180ca63a906..00000000000000 --- a/deps/v8_inspector/README.md +++ /dev/null @@ -1,12 +0,0 @@ -V8 Inspector support for Node.js -================================ - -This repository is an intermediate repository that gathers the dependencies for -Node.js support for the [Chrome Debug Protocol][https://developer.chrome.com/devtools/docs/debugger-protocol]. - -* include: vendored from v8/include -* src/inspector: vendored from v8/src/inspector -* third_party/WebKit/platform/inspector_protocol: vendored from https://chromium.googlesource.com/chromium/src/third_party/WebKit/Source/platform/inspector_protocol -* third_party/jinja2: vendored from https://github.com/mitsuhiko/jinja2 - * The `tests/` directory `ext/jinja.el` file have been deleted. -* third_party/markupsafe: vendored from https://github.com/mitsuhiko/markupsafe diff --git a/deps/v8_inspector/include/v8-inspector-protocol.h b/deps/v8_inspector/include/v8-inspector-protocol.h deleted file mode 100644 index 612a2ebc3911f5..00000000000000 --- a/deps/v8_inspector/include/v8-inspector-protocol.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_V8_INSPECTOR_PROTOCOL_H_ -#define V8_V8_INSPECTOR_PROTOCOL_H_ - -#include "inspector/Debugger.h" // NOLINT(build/include) -#include "inspector/Runtime.h" // NOLINT(build/include) -#include "inspector/Schema.h" // NOLINT(build/include) -#include "v8-inspector.h" // NOLINT(build/include) - -#endif // V8_V8_INSPECTOR_PROTOCOL_H_ diff --git a/deps/v8_inspector/include/v8-inspector.h b/deps/v8_inspector/include/v8-inspector.h deleted file mode 100644 index 0855ac101b74ef..00000000000000 --- a/deps/v8_inspector/include/v8-inspector.h +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_V8_INSPECTOR_H_ -#define V8_V8_INSPECTOR_H_ - -#include -#include - -#include - -#include "v8.h" // NOLINT(build/include) - -namespace v8_inspector { - -namespace protocol { -namespace Debugger { -namespace API { -class SearchMatch; -} -} -namespace Runtime { -namespace API { -class RemoteObject; -class StackTrace; -} -} -namespace Schema { -namespace API { -class Domain; -} -} -} // namespace protocol - -class V8_EXPORT StringView { - public: - StringView() : m_is8Bit(true), m_length(0), m_characters8(nullptr) {} - - StringView(const uint8_t* characters, size_t length) - : m_is8Bit(true), m_length(length), m_characters8(characters) {} - - StringView(const uint16_t* characters, size_t length) - : m_is8Bit(false), m_length(length), m_characters16(characters) {} - - bool is8Bit() const { return m_is8Bit; } - size_t length() const { return m_length; } - - // TODO(dgozman): add DCHECK(m_is8Bit) to accessors once platform can be used - // here. - const uint8_t* characters8() const { return m_characters8; } - const uint16_t* characters16() const { return m_characters16; } - - private: - bool m_is8Bit; - size_t m_length; - union { - const uint8_t* m_characters8; - const uint16_t* m_characters16; - }; -}; - -class V8_EXPORT StringBuffer { - public: - virtual ~StringBuffer() {} - virtual const StringView& string() = 0; - // This method copies contents. - static std::unique_ptr create(const StringView&); -}; - -class V8_EXPORT V8ContextInfo { - public: - V8ContextInfo(v8::Local context, int contextGroupId, - const StringView& humanReadableName) - : context(context), - contextGroupId(contextGroupId), - humanReadableName(humanReadableName), - hasMemoryOnConsole(false) {} - - v8::Local context; - // Each v8::Context is a part of a group. The group id must be non-zero. - int contextGroupId; - StringView humanReadableName; - StringView origin; - StringView auxData; - bool hasMemoryOnConsole; - - private: - // Disallow copying and allocating this one. - enum NotNullTagEnum { NotNullLiteral }; - void* operator new(size_t) = delete; - void* operator new(size_t, NotNullTagEnum, void*) = delete; - void* operator new(size_t, void*) = delete; - V8ContextInfo(const V8ContextInfo&) = delete; - V8ContextInfo& operator=(const V8ContextInfo&) = delete; -}; - -class V8_EXPORT V8StackTrace { - public: - virtual bool isEmpty() const = 0; - virtual StringView topSourceURL() const = 0; - virtual int topLineNumber() const = 0; - virtual int topColumnNumber() const = 0; - virtual StringView topScriptId() const = 0; - virtual StringView topFunctionName() const = 0; - - virtual ~V8StackTrace() {} - virtual std::unique_ptr - buildInspectorObject() const = 0; - virtual std::unique_ptr toString() const = 0; - - // Safe to pass between threads, drops async chain. - virtual std::unique_ptr clone() = 0; -}; - -class V8_EXPORT V8InspectorSession { - public: - virtual ~V8InspectorSession() {} - - // Cross-context inspectable values (DOM nodes in different worlds, etc.). - class V8_EXPORT Inspectable { - public: - virtual v8::Local get(v8::Local) = 0; - virtual ~Inspectable() {} - }; - virtual void addInspectedObject(std::unique_ptr) = 0; - - // Dispatching protocol messages. - static bool canDispatchMethod(const StringView& method); - virtual void dispatchProtocolMessage(const StringView& message) = 0; - virtual std::unique_ptr stateJSON() = 0; - virtual std::vector> - supportedDomains() = 0; - - // Debugger actions. - virtual void schedulePauseOnNextStatement(const StringView& breakReason, - const StringView& breakDetails) = 0; - virtual void cancelPauseOnNextStatement() = 0; - virtual void breakProgram(const StringView& breakReason, - const StringView& breakDetails) = 0; - virtual void setSkipAllPauses(bool) = 0; - virtual void resume() = 0; - virtual void stepOver() = 0; - virtual std::vector> - searchInTextByLines(const StringView& text, const StringView& query, - bool caseSensitive, bool isRegex) = 0; - - // Remote objects. - virtual std::unique_ptr wrapObject( - v8::Local, v8::Local, - const StringView& groupName) = 0; - virtual bool unwrapObject(std::unique_ptr* error, - const StringView& objectId, v8::Local*, - v8::Local*, - std::unique_ptr* objectGroup) = 0; - virtual void releaseObjectGroup(const StringView&) = 0; -}; - -enum class V8ConsoleAPIType { kClear, kDebug, kLog, kInfo, kWarning, kError }; - -class V8_EXPORT V8InspectorClient { - public: - virtual ~V8InspectorClient() {} - - virtual void runMessageLoopOnPause(int contextGroupId) {} - virtual void quitMessageLoopOnPause() {} - virtual void runIfWaitingForDebugger(int contextGroupId) {} - - virtual void muteMetrics(int contextGroupId) {} - virtual void unmuteMetrics(int contextGroupId) {} - - virtual void beginUserGesture() {} - virtual void endUserGesture() {} - - virtual std::unique_ptr valueSubtype(v8::Local) { - return nullptr; - } - virtual bool formatAccessorsAsProperties(v8::Local) { - return false; - } - virtual bool isInspectableHeapObject(v8::Local) { return true; } - - virtual v8::Local ensureDefaultContextInGroup( - int contextGroupId) { - return v8::Local(); - } - virtual void beginEnsureAllContextsInGroup(int contextGroupId) {} - virtual void endEnsureAllContextsInGroup(int contextGroupId) {} - - virtual void installAdditionalCommandLineAPI(v8::Local, - v8::Local) {} - virtual void consoleAPIMessage(int contextGroupId, V8ConsoleAPIType, - const StringView& message, - const StringView& url, unsigned lineNumber, - unsigned columnNumber, V8StackTrace*) {} - virtual v8::MaybeLocal memoryInfo(v8::Isolate*, - v8::Local) { - return v8::MaybeLocal(); - } - - virtual void consoleTime(const StringView& title) {} - virtual void consoleTimeEnd(const StringView& title) {} - virtual void consoleTimeStamp(const StringView& title) {} - virtual double currentTimeMS() { return 0; } - typedef void (*TimerCallback)(void*); - virtual void startRepeatingTimer(double, TimerCallback, void* data) {} - virtual void cancelTimer(void* data) {} - - // TODO(dgozman): this was added to support service worker shadow page. We - // should not connect at all. - virtual bool canExecuteScripts(int contextGroupId) { return true; } -}; - -class V8_EXPORT V8Inspector { - public: - static std::unique_ptr create(v8::Isolate*, V8InspectorClient*); - virtual ~V8Inspector() {} - - // Contexts instrumentation. - virtual void contextCreated(const V8ContextInfo&) = 0; - virtual void contextDestroyed(v8::Local) = 0; - virtual void resetContextGroup(int contextGroupId) = 0; - - // Various instrumentation. - virtual void willExecuteScript(v8::Local, int scriptId) = 0; - virtual void didExecuteScript(v8::Local) = 0; - virtual void idleStarted() = 0; - virtual void idleFinished() = 0; - - // Async stack traces instrumentation. - virtual void asyncTaskScheduled(const StringView& taskName, void* task, - bool recurring) = 0; - virtual void asyncTaskCanceled(void* task) = 0; - virtual void asyncTaskStarted(void* task) = 0; - virtual void asyncTaskFinished(void* task) = 0; - virtual void allAsyncTasksCanceled() = 0; - - // Exceptions instrumentation. - virtual unsigned exceptionThrown( - v8::Local, const StringView& message, - v8::Local exception, const StringView& detailedMessage, - const StringView& url, unsigned lineNumber, unsigned columnNumber, - std::unique_ptr, int scriptId) = 0; - virtual void exceptionRevoked(v8::Local, unsigned exceptionId, - const StringView& message) = 0; - - // Connection. - class V8_EXPORT Channel { - public: - virtual ~Channel() {} - virtual void sendProtocolResponse(int callId, - const StringView& message) = 0; - virtual void sendProtocolNotification(const StringView& message) = 0; - virtual void flushProtocolNotifications() = 0; - }; - virtual std::unique_ptr connect( - int contextGroupId, Channel*, const StringView& state) = 0; - - // API methods. - virtual std::unique_ptr createStackTrace( - v8::Local) = 0; - virtual std::unique_ptr captureStackTrace(bool fullStack) = 0; -}; - -} // namespace v8_inspector - -#endif // V8_V8_INSPECTOR_H_ diff --git a/deps/v8_inspector/src/inspector/BUILD.gn b/deps/v8_inspector/src/inspector/BUILD.gn deleted file mode 100644 index 15c090ff2218b5..00000000000000 --- a/deps/v8_inspector/src/inspector/BUILD.gn +++ /dev/null @@ -1,189 +0,0 @@ -# Copyright 2016 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("../../gni/v8.gni") - -_inspector_protocol = "//third_party/WebKit/Source/platform/inspector_protocol" -import("$_inspector_protocol/inspector_protocol.gni") - -_protocol_generated = [ - "protocol/Forward.h", - "protocol/Protocol.cpp", - "protocol/Protocol.h", - "protocol/Console.cpp", - "protocol/Console.h", - "protocol/Debugger.cpp", - "protocol/Debugger.h", - "protocol/HeapProfiler.cpp", - "protocol/HeapProfiler.h", - "protocol/Profiler.cpp", - "protocol/Profiler.h", - "protocol/Runtime.cpp", - "protocol/Runtime.h", - "protocol/Schema.cpp", - "protocol/Schema.h", - "../../include/inspector/Debugger.h", - "../../include/inspector/Runtime.h", - "../../include/inspector/Schema.h", -] - -action("protocol_compatibility") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - script = "$_inspector_protocol/CheckProtocolCompatibility.py" - inputs = [ - "js_protocol.json", - ] - _stamp = "$target_gen_dir/js_protocol.stamp" - outputs = [ - _stamp, - ] - args = [ - "--stamp", - rebase_path(_stamp, root_build_dir), - rebase_path("js_protocol.json", root_build_dir), - ] -} - -inspector_protocol_generate("protocol_generated_sources") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - deps = [ - ":protocol_compatibility", - ] - - out_dir = target_gen_dir - config_file = "inspector_protocol_config.json" - inputs = [ - "js_protocol.json", - "inspector_protocol_config.json", - ] - outputs = _protocol_generated -} - -action("inspector_injected_script") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - script = "build/xxd.py" - inputs = [ - "injected-script-source.js", - ] - outputs = [ - "$target_gen_dir/injected-script-source.h", - ] - args = [ - "InjectedScriptSource_js", - rebase_path("injected-script-source.js", root_build_dir), - rebase_path("$target_gen_dir/injected-script-source.h", root_build_dir), - ] -} - -action("inspector_debugger_script") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - script = "build/xxd.py" - inputs = [ - "debugger-script.js", - ] - outputs = [ - "$target_gen_dir/debugger-script.h", - ] - args = [ - "DebuggerScript_js", - rebase_path("debugger-script.js", root_build_dir), - rebase_path("$target_gen_dir/debugger-script.h", root_build_dir), - ] -} - -config("inspector_config") { - visibility = [ ":*" ] # Only targets in this file can depend on this. - cflags = [] - if (is_win) { - cflags += [ - "/wd4267", # Truncation from size_t to int. - "/wd4305", # Truncation from 'type1' to 'type2'. - "/wd4324", # Struct padded due to declspec(align). - "/wd4714", # Function marked forceinline not inlined. - "/wd4800", # Value forced to bool. - "/wd4996", # Deprecated function call. - ] - } - if (is_component_build) { - defines = [ "BUILDING_V8_SHARED" ] - } -} - -v8_source_set("inspector") { - deps = [ - ":inspector_debugger_script", - ":inspector_injected_script", - ":protocol_generated_sources", - ] - configs = [ ":inspector_config" ] - include_dirs = [ - "../..", - "../../include", - "$target_gen_dir/../..", - "$target_gen_dir/../../include", - ] - sources = rebase_path(_protocol_generated, ".", target_gen_dir) - sources += [ - "../../include/v8-inspector-protocol.h", - "../../include/v8-inspector.h", - ] - sources += get_target_outputs(":inspector_injected_script") - sources += get_target_outputs(":inspector_debugger_script") - sources += [ - "injected-script-native.cc", - "injected-script-native.h", - "injected-script.cc", - "injected-script.h", - "inspected-context.cc", - "inspected-context.h", - "java-script-call-frame.cc", - "java-script-call-frame.h", - "protocol-platform.h", - "remote-object-id.cc", - "remote-object-id.h", - "script-breakpoint.h", - "search-util.cc", - "search-util.h", - "string-16.cc", - "string-16.h", - "string-util.cc", - "string-util.h", - "v8-console-agent-impl.cc", - "v8-console-agent-impl.h", - "v8-console-message.cc", - "v8-console-message.h", - "v8-console.cc", - "v8-console.h", - "v8-debugger-agent-impl.cc", - "v8-debugger-agent-impl.h", - "v8-debugger-script.cc", - "v8-debugger-script.h", - "v8-debugger.cc", - "v8-debugger.h", - "v8-function-call.cc", - "v8-function-call.h", - "v8-heap-profiler-agent-impl.cc", - "v8-heap-profiler-agent-impl.h", - "v8-injected-script-host.cc", - "v8-injected-script-host.h", - "v8-inspector-impl.cc", - "v8-inspector-impl.h", - "v8-inspector-session-impl.cc", - "v8-inspector-session-impl.h", - "v8-internal-value-type.cc", - "v8-internal-value-type.h", - "v8-profiler-agent-impl.cc", - "v8-profiler-agent-impl.h", - "v8-regex.cc", - "v8-regex.h", - "v8-runtime-agent-impl.cc", - "v8-runtime-agent-impl.h", - "v8-schema-agent-impl.cc", - "v8-schema-agent-impl.h", - "v8-stack-trace-impl.cc", - "v8-stack-trace-impl.h", - "v8-value-copier.cc", - "v8-value-copier.h", - ] -} diff --git a/deps/v8_inspector/src/inspector/DEPS b/deps/v8_inspector/src/inspector/DEPS deleted file mode 100644 index 4486204d74ec76..00000000000000 --- a/deps/v8_inspector/src/inspector/DEPS +++ /dev/null @@ -1,8 +0,0 @@ -include_rules = [ - "-src", - "+src/inspector", - "+src/base/atomicops.h", - "+src/base/macros.h", - "+src/base/logging.h", - "+src/base/platform/platform.h", -] diff --git a/deps/v8_inspector/src/inspector/OWNERS b/deps/v8_inspector/src/inspector/OWNERS deleted file mode 100644 index 2c4bd8d24bc92a..00000000000000 --- a/deps/v8_inspector/src/inspector/OWNERS +++ /dev/null @@ -1,15 +0,0 @@ -set noparent - -alph@chromium.org -caseq@chromium.org -dgozman@chromium.org -jochen@chromium.org -kozyatinskiy@chromium.org -pfeldman@chromium.org -yangguo@chromium.org - -# Changes to remote debugging protocol require devtools review to -# ensure backwards compatibility and committment to maintain. -per-file js_protocol.json=set noparent -per-file js_protocol.json=dgozman@chromium.org -per-file js_protocol.json=pfeldman@chromium.org diff --git a/deps/v8_inspector/src/inspector/PRESUBMIT.py b/deps/v8_inspector/src/inspector/PRESUBMIT.py deleted file mode 100644 index 491564b2d9fc68..00000000000000 --- a/deps/v8_inspector/src/inspector/PRESUBMIT.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2016 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. - -"""v8_inspect presubmit script - -See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts -for more details about the presubmit API built into gcl. -""" - -compile_note = "Be sure to run your patch by the compile-scripts.py script prior to committing!" - - -def _CompileScripts(input_api, output_api): - local_paths = [f.LocalPath() for f in input_api.AffectedFiles()] - - compilation_related_files = [ - "js_protocol.json" - "compile-scripts.js", - "injected-script-source.js", - "debugger_script_externs.js", - "injected_script_externs.js", - "check_injected_script_source.js", - "debugger-script.js" - ] - - for file in compilation_related_files: - if (any(file in path for path in local_paths)): - script_path = input_api.os_path.join(input_api.PresubmitLocalPath(), - "build", "compile-scripts.py") - proc = input_api.subprocess.Popen( - [input_api.python_executable, script_path], - stdout=input_api.subprocess.PIPE, - stderr=input_api.subprocess.STDOUT) - out, _ = proc.communicate() - if "ERROR" in out or "WARNING" in out or proc.returncode: - return [output_api.PresubmitError(out)] - if "NOTE" in out: - return [output_api.PresubmitPromptWarning(out + compile_note)] - return [] - return [] - - -def CheckChangeOnUpload(input_api, output_api): - results = [] - results.extend(_CompileScripts(input_api, output_api)) - return results - - -def CheckChangeOnCommit(input_api, output_api): - results = [] - results.extend(_CompileScripts(input_api, output_api)) - return results diff --git a/deps/v8_inspector/src/inspector/build/check_injected_script_source.py b/deps/v8_inspector/src/inspector/build/check_injected_script_source.py deleted file mode 100644 index 0f2509cd8c5cac..00000000000000 --- a/deps/v8_inspector/src/inspector/build/check_injected_script_source.py +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2014 Google Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -# -# Copied from blink: -# WebKit/Source/devtools/scripts/check_injected_script_source.py -# - -import re -import sys -import os - - -def validate_injected_script(fileName): - f = open(fileName, "r") - lines = f.readlines() - f.close() - - proto_functions = "|".join([ - # Array.prototype.* - "concat", "every", "filter", "forEach", "indexOf", "join", "lastIndexOf", "map", "pop", - "push", "reduce", "reduceRight", "reverse", "shift", "slice", "some", "sort", "splice", "toLocaleString", "toString", "unshift", - # Function.prototype.* - "apply", "bind", "call", "isGenerator", "toSource", - # Object.prototype.* - "toString", - ]) - - global_functions = "|".join([ - "eval", "uneval", "isFinite", "isNaN", "parseFloat", "parseInt", "decodeURI", "decodeURIComponent", - "encodeURI", "encodeURIComponent", "escape", "unescape", "Map", "Set" - ]) - - # Black list: - # - instanceof, since e.g. "obj instanceof Error" may throw if Error is overridden and is not a function - # - Object.prototype.toString() - # - Array.prototype.* - # - Function.prototype.* - # - Math.* - # - Global functions - black_list_call_regex = re.compile(r"\sinstanceof\s+\w*|\bMath\.\w+\(|(?= java_required_major and minor >= java_required_minor - if is_ok: - exec_command = [java_path, '-Xms1024m', '-server', - '-XX:+TieredCompilation'] - check_server_proc = popen(exec_command + ['-version']) - check_server_proc.communicate() - if check_server_proc.returncode != 0: - # Not all Java installs have server JVMs. - exec_command = exec_command.remove('-server') - has_server_jvm = False - - if not is_ok: - print 'NOTE: Java executable version %d.%d or above not found in $PATH.' % (java_required_major, java_required_minor) - sys.exit(0) - print 'Java executable: %s%s' % (java_path, '' if has_server_jvm else ' (no server JVM)') - return exec_command - -java_exec = find_java() - -spawned_compiler_command = java_exec + [ - '-jar', - closure_compiler_jar -] + common_closure_args - -print 'Compiling injected-script-source.js...' - -command = spawned_compiler_command + [ - '--externs', injected_script_externs_file, - '--externs', protocol_externs_file, - '--js', injected_script_source_name -] - -injected_script_compile_proc = popen(command) - -print 'Compiling debugger-script.js...' - -command = spawned_compiler_command + [ - '--externs', debugger_script_externs_file, - '--js', debugger_script_source_name, - '--new_type_inf' -] - -debugger_script_compile_proc = popen(command) - -print 'Validating injected-script-source.js...' -injectedscript_check_script_path = path.join(v8_inspector_path, 'build', - 'check_injected_script_source.py') -validate_injected_script_proc = popen([sys.executable, - injectedscript_check_script_path, injected_script_source_name]) - -print - -(injected_script_compile_out, _) = injected_script_compile_proc.communicate() -print 'injected-script-source.js compilation output:%s' % os.linesep -print injected_script_compile_out -errors_found |= has_errors(injected_script_compile_out) - -(debugger_script_compiler_out, _) = debugger_script_compile_proc.communicate() -print 'debugger-script.js compilation output:%s' % os.linesep -print debugger_script_compiler_out -errors_found |= has_errors(debugger_script_compiler_out) - -(validate_injected_script_out, _) = validate_injected_script_proc.communicate() -print 'Validate injected-script-source.js output:%s' % os.linesep -print validate_injected_script_out if validate_injected_script_out else '' -errors_found |= has_errors(validate_injected_script_out) - -os.remove(protocol_externs_file) - -if errors_found: - print 'ERRORS DETECTED' - sys.exit(1) diff --git a/deps/v8_inspector/src/inspector/build/generate_protocol_externs.py b/deps/v8_inspector/src/inspector/build/generate_protocol_externs.py deleted file mode 100755 index c2ba2c5b84e5d6..00000000000000 --- a/deps/v8_inspector/src/inspector/build/generate_protocol_externs.py +++ /dev/null @@ -1,246 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2011 Google Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -import os -import re -import json - -type_traits = { - "any": "*", - "string": "string", - "integer": "number", - "number": "number", - "boolean": "boolean", - "array": "!Array.<*>", - "object": "!Object", -} - -promisified_domains = { - "Accessibility", - "Animation", - "CSS", - "Emulation", - "Profiler" -} - -ref_types = {} - -def full_qualified_type_id(domain_name, type_id): - if type_id.find(".") == -1: - return "%s.%s" % (domain_name, type_id) - return type_id - - -def fix_camel_case(name): - prefix = "" - if name[0] == "-": - prefix = "Negative" - name = name[1:] - refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name) - refined = to_title_case(refined) - return prefix + re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined) - - -def to_title_case(name): - return name[:1].upper() + name[1:] - - -def generate_enum(name, json): - enum_members = [] - for member in json["enum"]: - enum_members.append(" %s: \"%s\"" % (fix_camel_case(member), member)) - return "\n/** @enum {string} */\n%s = {\n%s\n};\n" % (name, (",\n".join(enum_members))) - - -def param_type(domain_name, param): - if "type" in param: - if param["type"] == "array": - items = param["items"] - return "!Array.<%s>" % param_type(domain_name, items) - else: - return type_traits[param["type"]] - if "$ref" in param: - type_id = full_qualified_type_id(domain_name, param["$ref"]) - if type_id in ref_types: - return ref_types[type_id] - else: - print "Type not found: " + type_id - return "!! Type not found: " + type_id - - -def load_schema(file, domains): - input_file = open(file, "r") - json_string = input_file.read() - parsed_json = json.loads(json_string) - domains.extend(parsed_json["domains"]) - - -def generate_protocol_externs(output_path, file1): - domains = [] - load_schema(file1, domains) - output_file = open(output_path, "w") - - output_file.write( -""" -var InspectorBackend = {} - -var Protocol = {}; -/** @typedef {string}*/ -Protocol.Error; -""") - - for domain in domains: - domain_name = domain["domain"] - if "types" in domain: - for type in domain["types"]: - type_id = full_qualified_type_id(domain_name, type["id"]) - ref_types[type_id] = "%sAgent.%s" % (domain_name, type["id"]) - - for domain in domains: - domain_name = domain["domain"] - promisified = domain_name in promisified_domains - - output_file.write("\n\n/**\n * @constructor\n*/\n") - output_file.write("Protocol.%sAgent = function(){};\n" % domain_name) - - if "commands" in domain: - for command in domain["commands"]: - output_file.write("\n/**\n") - params = [] - has_return_value = "returns" in command - explicit_parameters = promisified and has_return_value - if ("parameters" in command): - for in_param in command["parameters"]: - # All parameters are not optional in case of promisified domain with return value. - if (not explicit_parameters and "optional" in in_param): - params.append("opt_%s" % in_param["name"]) - output_file.write(" * @param {%s=} opt_%s\n" % (param_type(domain_name, in_param), in_param["name"])) - else: - params.append(in_param["name"]) - output_file.write(" * @param {%s} %s\n" % (param_type(domain_name, in_param), in_param["name"])) - returns = [] - returns.append("?Protocol.Error") - if ("error" in command): - returns.append("%s=" % param_type(domain_name, command["error"])) - if (has_return_value): - for out_param in command["returns"]: - if ("optional" in out_param): - returns.append("%s=" % param_type(domain_name, out_param)) - else: - returns.append("%s" % param_type(domain_name, out_param)) - callback_return_type = "void=" - if explicit_parameters: - callback_return_type = "T" - elif promisified: - callback_return_type = "T=" - output_file.write(" * @param {function(%s):%s} opt_callback\n" % (", ".join(returns), callback_return_type)) - if (promisified): - output_file.write(" * @return {!Promise.}\n") - output_file.write(" * @template T\n") - params.append("opt_callback") - - output_file.write(" */\n") - output_file.write("Protocol.%sAgent.prototype.%s = function(%s) {}\n" % (domain_name, command["name"], ", ".join(params))) - output_file.write("/** @param {function(%s):void=} opt_callback */\n" % ", ".join(returns)) - output_file.write("Protocol.%sAgent.prototype.invoke_%s = function(obj, opt_callback) {}\n" % (domain_name, command["name"])) - - output_file.write("\n\n\nvar %sAgent = function(){};\n" % domain_name) - - if "types" in domain: - for type in domain["types"]: - if type["type"] == "object": - typedef_args = [] - if "properties" in type: - for property in type["properties"]: - suffix = "" - if ("optional" in property): - suffix = "|undefined" - if "enum" in property: - enum_name = "%sAgent.%s%s" % (domain_name, type["id"], to_title_case(property["name"])) - output_file.write(generate_enum(enum_name, property)) - typedef_args.append("%s:(%s%s)" % (property["name"], enum_name, suffix)) - else: - typedef_args.append("%s:(%s%s)" % (property["name"], param_type(domain_name, property), suffix)) - if (typedef_args): - output_file.write("\n/** @typedef {!{%s}} */\n%sAgent.%s;\n" % (", ".join(typedef_args), domain_name, type["id"])) - else: - output_file.write("\n/** @typedef {!Object} */\n%sAgent.%s;\n" % (domain_name, type["id"])) - elif type["type"] == "string" and "enum" in type: - output_file.write(generate_enum("%sAgent.%s" % (domain_name, type["id"]), type)) - elif type["type"] == "array": - output_file.write("\n/** @typedef {!Array.} */\n%sAgent.%s;\n" % (param_type(domain_name, type["items"]), domain_name, type["id"])) - else: - output_file.write("\n/** @typedef {%s} */\n%sAgent.%s;\n" % (type_traits[type["type"]], domain_name, type["id"])) - - output_file.write("/** @interface */\n") - output_file.write("%sAgent.Dispatcher = function() {};\n" % domain_name) - if "events" in domain: - for event in domain["events"]: - params = [] - if ("parameters" in event): - output_file.write("/**\n") - for param in event["parameters"]: - if ("optional" in param): - params.append("opt_%s" % param["name"]) - output_file.write(" * @param {%s=} opt_%s\n" % (param_type(domain_name, param), param["name"])) - else: - params.append(param["name"]) - output_file.write(" * @param {%s} %s\n" % (param_type(domain_name, param), param["name"])) - output_file.write(" */\n") - output_file.write("%sAgent.Dispatcher.prototype.%s = function(%s) {};\n" % (domain_name, event["name"], ", ".join(params))) - - output_file.write("\n/** @constructor\n * @param {!Object.} agentsMap\n */\n") - output_file.write("Protocol.Agents = function(agentsMap){this._agentsMap;};\n") - output_file.write("/**\n * @param {string} domain\n * @param {!Object} dispatcher\n */\n") - output_file.write("Protocol.Agents.prototype.registerDispatcher = function(domain, dispatcher){};\n") - for domain in domains: - domain_name = domain["domain"] - uppercase_length = 0 - while uppercase_length < len(domain_name) and domain_name[uppercase_length].isupper(): - uppercase_length += 1 - - output_file.write("/** @return {!Protocol.%sAgent}*/\n" % domain_name) - output_file.write("Protocol.Agents.prototype.%s = function(){};\n" % (domain_name[:uppercase_length].lower() + domain_name[uppercase_length:] + "Agent")) - - output_file.write("/**\n * @param {!%sAgent.Dispatcher} dispatcher\n */\n" % domain_name) - output_file.write("Protocol.Agents.prototype.register%sDispatcher = function(dispatcher) {}\n" % domain_name) - - - output_file.close() - -if __name__ == "__main__": - import sys - import os.path - program_name = os.path.basename(__file__) - if len(sys.argv) < 4 or sys.argv[1] != "-o": - sys.stderr.write("Usage: %s -o OUTPUT_FILE INPUT_FILE\n" % program_name) - exit(1) - output_path = sys.argv[2] - input_path = sys.argv[3] - generate_protocol_externs(output_path, input_path) diff --git a/deps/v8_inspector/src/inspector/build/rjsmin.py b/deps/v8_inspector/src/inspector/build/rjsmin.py deleted file mode 100755 index 8357a6dcc10e57..00000000000000 --- a/deps/v8_inspector/src/inspector/build/rjsmin.py +++ /dev/null @@ -1,295 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2011 - 2013 -# Andr\xe9 Malo or his licensors, as applicable -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -r""" -===================== - Javascript Minifier -===================== - -rJSmin is a javascript minifier written in python. - -The minifier is based on the semantics of `jsmin.c by Douglas Crockford`_\. - -The module is a re-implementation aiming for speed, so it can be used at -runtime (rather than during a preprocessing step). Usually it produces the -same results as the original ``jsmin.c``. It differs in the following ways: - -- there is no error detection: unterminated string, regex and comment - literals are treated as regular javascript code and minified as such. -- Control characters inside string and regex literals are left untouched; they - are not converted to spaces (nor to \n) -- Newline characters are not allowed inside string and regex literals, except - for line continuations in string literals (ECMA-5). -- "return /regex/" is recognized correctly. -- "+ +" and "- -" sequences are not collapsed to '++' or '--' -- Newlines before ! operators are removed more sensibly -- rJSmin does not handle streams, but only complete strings. (However, the - module provides a "streamy" interface). - -Since most parts of the logic are handled by the regex engine it's way -faster than the original python port of ``jsmin.c`` by Baruch Even. The speed -factor varies between about 6 and 55 depending on input and python version -(it gets faster the more compressed the input already is). Compared to the -speed-refactored python port by Dave St.Germain the performance gain is less -dramatic but still between 1.2 and 7. See the docs/BENCHMARKS file for -details. - -rjsmin.c is a reimplementation of rjsmin.py in C and speeds it up even more. - -Both python 2 and python 3 are supported. - -.. _jsmin.c by Douglas Crockford: - http://www.crockford.com/javascript/jsmin.c -""" -__author__ = "Andr\xe9 Malo" -__author__ = getattr(__author__, 'decode', lambda x: __author__)('latin-1') -__docformat__ = "restructuredtext en" -__license__ = "Apache License, Version 2.0" -__version__ = '1.0.7' -__all__ = ['jsmin'] - -import re as _re - - -def _make_jsmin(python_only=False): - """ - Generate JS minifier based on `jsmin.c by Douglas Crockford`_ - - .. _jsmin.c by Douglas Crockford: - http://www.crockford.com/javascript/jsmin.c - - :Parameters: - `python_only` : ``bool`` - Use only the python variant. If true, the c extension is not even - tried to be loaded. - - :Return: Minifier - :Rtype: ``callable`` - """ - # pylint: disable = R0912, R0914, W0612 - if not python_only: - try: - import _rjsmin - except ImportError: - pass - else: - return _rjsmin.jsmin - try: - xrange - except NameError: - xrange = range # pylint: disable = W0622 - - space_chars = r'[\000-\011\013\014\016-\040]' - - line_comment = r'(?://[^\r\n]*)' - space_comment = r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)' - string1 = \ - r'(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|\r)[^\047\\\r\n]*)*\047)' - string2 = r'(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|\r)[^"\\\r\n]*)*")' - strings = r'(?:%s|%s)' % (string1, string2) - - charclass = r'(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]*)*\])' - nospecial = r'[^/\\\[\r\n]' - regex = r'(?:/(?![\r\n/*])%s*(?:(?:\\[^\r\n]|%s)%s*)*/)' % ( - nospecial, charclass, nospecial) - space = r'(?:%s|%s)' % (space_chars, space_comment) - newline = r'(?:%s?[\r\n])' % line_comment - - def fix_charclass(result): - """ Fixup string of chars to fit into a regex char class """ - pos = result.find('-') - if pos >= 0: - result = r'%s%s-' % (result[:pos], result[pos + 1:]) - - def sequentize(string): - """ - Notate consecutive characters as sequence - - (1-4 instead of 1234) - """ - first, last, result = None, None, [] - for char in map(ord, string): - if last is None: - first = last = char - elif last + 1 == char: - last = char - else: - result.append((first, last)) - first = last = char - if last is not None: - result.append((first, last)) - return ''.join(['%s%s%s' % ( - chr(first), - last > first + 1 and '-' or '', - last != first and chr(last) or '') for first, last in result]) - - return _re.sub(r'([\000-\040\047])', # for better portability - lambda m: '\\%03o' % ord(m.group(1)), (sequentize(result) - .replace('\\', '\\\\') - .replace('[', '\\[') - .replace(']', '\\]'))) - - def id_literal_(what): - """ Make id_literal like char class """ - match = _re.compile(what).match - result = ''.join([chr(c) for c in xrange(127) if not match(chr(c))]) - return '[^%s]' % fix_charclass(result) - - def not_id_literal_(keep): - """ Make negated id_literal like char class """ - match = _re.compile(id_literal_(keep)).match - result = ''.join([chr(c) for c in xrange(127) if not match(chr(c))]) - return r'[%s]' % fix_charclass(result) - - not_id_literal = not_id_literal_(r'[a-zA-Z0-9_$]') - preregex1 = r'[(,=:\[!&|?{};\r\n]' - preregex2 = r'%(not_id_literal)sreturn' % locals() - - id_literal = id_literal_(r'[a-zA-Z0-9_$]') - id_literal_open = id_literal_(r'[a-zA-Z0-9_${\[(!+-]') - id_literal_close = id_literal_(r'[a-zA-Z0-9_$}\])"\047+-]') - - dull = r'[^\047"/\000-\040]' - - space_sub = _re.compile(( - r'(%(dull)s+)' - r'|(%(strings)s%(dull)s*)' - r'|(?<=%(preregex1)s)' - r'%(space)s*(?:%(newline)s%(space)s*)*' - r'(%(regex)s%(dull)s*)' - r'|(?<=%(preregex2)s)' - r'%(space)s*(?:%(newline)s%(space)s)*' - r'(%(regex)s%(dull)s*)' - r'|(?<=%(id_literal_close)s)' - r'%(space)s*(?:(%(newline)s)%(space)s*)+' - r'(?=%(id_literal_open)s)' - r'|(?<=%(id_literal)s)(%(space)s)+(?=%(id_literal)s)' - r'|(?<=\+)(%(space)s)+(?=\+)' - r'|(?<=-)(%(space)s)+(?=-)' - r'|%(space)s+' - r'|(?:%(newline)s%(space)s*)+') % locals()).sub - #print space_sub.__self__.pattern - - def space_subber(match): - """ Substitution callback """ - # pylint: disable = C0321, R0911 - groups = match.groups() - if groups[0]: - return groups[0] - elif groups[1]: - return groups[1] - elif groups[2]: - return groups[2] - elif groups[3]: - return groups[3] - elif groups[4]: - return '\n' - elif groups[5] or groups[6] or groups[7]: - return ' ' - else: - return '' - - def jsmin(script): # pylint: disable = W0621 - r""" - Minify javascript based on `jsmin.c by Douglas Crockford`_\. - - Instead of parsing the stream char by char, it uses a regular - expression approach which minifies the whole script with one big - substitution regex. - - .. _jsmin.c by Douglas Crockford: - http://www.crockford.com/javascript/jsmin.c - - :Parameters: - `script` : ``str`` - Script to minify - - :Return: Minified script - :Rtype: ``str`` - """ - return space_sub(space_subber, '\n%s\n' % script).strip() - - return jsmin - -jsmin = _make_jsmin() - - -def jsmin_for_posers(script): - r""" - Minify javascript based on `jsmin.c by Douglas Crockford`_\. - - Instead of parsing the stream char by char, it uses a regular - expression approach which minifies the whole script with one big - substitution regex. - - .. _jsmin.c by Douglas Crockford: - http://www.crockford.com/javascript/jsmin.c - - :Warning: This function is the digest of a _make_jsmin() call. It just - utilizes the resulting regex. It's just for fun here and may - vanish any time. Use the `jsmin` function instead. - - :Parameters: - `script` : ``str`` - Script to minify - - :Return: Minified script - :Rtype: ``str`` - """ - def subber(match): - """ Substitution callback """ - groups = match.groups() - return ( - groups[0] or - groups[1] or - groups[2] or - groups[3] or - (groups[4] and '\n') or - (groups[5] and ' ') or - (groups[6] and ' ') or - (groups[7] and ' ') or - '') - - return _re.sub( - r'([^\047"/\000-\040]+)|((?:(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?' - r'\n|\r)[^\047\\\r\n]*)*\047)|(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|' - r'\r)[^"\\\r\n]*)*"))[^\047"/\000-\040]*)|(?<=[(,=:\[!&|?{};\r\n])(?' - r':[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*' - r'(?:(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:/\*' - r'[^*]*\*+(?:[^/*][^*]*\*+)*/))*)*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?:(' - r'?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/\\\[' - r'\r\n]*)*/)[^\047"/\000-\040]*)|(?<=[\000-#%-,./:-@\[-^`{-~-]return' - r')(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/' - r'))*(?:(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:' - r'/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?' - r':(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/' - r'\\\[\r\n]*)*/)[^\047"/\000-\040]*)|(?<=[^\000-!#%&(*,./:-@\[\\^`{|' - r'~])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)' - r'*/))*(?:((?:(?://[^\r\n]*)?[\r\n]))(?:[\000-\011\013\014\016-\040]' - r'|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*)+(?=[^\000-\040"#%-\047)*,./' - r':-@\\-^`|-~])|(?<=[^\000-#%-,./:-@\[-^`{-~-])((?:[\000-\011\013\01' - r'4\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=[^\000-#%-,./:' - r'-@\[-^`{-~-])|(?<=\+)((?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*' - r'\*+(?:[^/*][^*]*\*+)*/)))+(?=\+)|(?<=-)((?:[\000-\011\013\014\016-' - r'\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=-)|(?:[\000-\011\013' - r'\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))+|(?:(?:(?://[^' - r'\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^' - r'/*][^*]*\*+)*/))*)+', subber, '\n%s\n' % script).strip() - - -if __name__ == '__main__': - import sys as _sys - _sys.stdout.write(jsmin(_sys.stdin.read())) diff --git a/deps/v8_inspector/src/inspector/build/xxd.py b/deps/v8_inspector/src/inspector/build/xxd.py deleted file mode 100644 index 5a63a7cb8d0381..00000000000000 --- a/deps/v8_inspector/src/inspector/build/xxd.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright 2016 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. - -"""Represent a file as a C++ constant string. - -Usage: -python xxd.py VAR SOURCE DEST -""" - - -import sys -import rjsmin - - -def main(): - variable_name, input_filename, output_filename = sys.argv[1:] - with open(input_filename) as input_file: - input_text = input_file.read() - input_text = rjsmin.jsmin(input_text) - hex_values = ['0x{0:02x}'.format(ord(char)) for char in input_text] - const_declaration = 'const char %s[] = {\n%s\n};\n' % ( - variable_name, ', '.join(hex_values)) - with open(output_filename, 'w') as output_file: - output_file.write(const_declaration) - -if __name__ == '__main__': - sys.exit(main()) diff --git a/deps/v8_inspector/src/inspector/debugger-script.js b/deps/v8_inspector/src/inspector/debugger-script.js deleted file mode 100644 index 98910d69df7167..00000000000000 --- a/deps/v8_inspector/src/inspector/debugger-script.js +++ /dev/null @@ -1,712 +0,0 @@ -/* - * Copyright (C) 2010 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -"use strict"; - -(function () { - -var DebuggerScript = {}; - -/** @enum */ -const PauseOnExceptionsState = { - DontPauseOnExceptions: 0, - PauseOnAllExceptions: 1, - PauseOnUncaughtExceptions: 2 -}; -DebuggerScript.PauseOnExceptionsState = PauseOnExceptionsState; - -DebuggerScript._pauseOnExceptionsState = DebuggerScript.PauseOnExceptionsState.DontPauseOnExceptions; -Debug.clearBreakOnException(); -Debug.clearBreakOnUncaughtException(); - -/** - * @param {?CompileEvent} eventData - */ -DebuggerScript.getAfterCompileScript = function(eventData) -{ - var script = eventData.script().value(); - if (!script.is_debugger_script) - return DebuggerScript._formatScript(eventData.script().value()); - return null; -} - -/** @type {!Map} */ -DebuggerScript._scopeTypeNames = new Map(); -DebuggerScript._scopeTypeNames.set(ScopeType.Global, "global"); -DebuggerScript._scopeTypeNames.set(ScopeType.Local, "local"); -DebuggerScript._scopeTypeNames.set(ScopeType.With, "with"); -DebuggerScript._scopeTypeNames.set(ScopeType.Closure, "closure"); -DebuggerScript._scopeTypeNames.set(ScopeType.Catch, "catch"); -DebuggerScript._scopeTypeNames.set(ScopeType.Block, "block"); -DebuggerScript._scopeTypeNames.set(ScopeType.Script, "script"); - -/** - * @param {function()} fun - * @return {?Array} - */ -DebuggerScript.getFunctionScopes = function(fun) -{ - var mirror = MakeMirror(fun); - if (!mirror.isFunction()) - return null; - var functionMirror = /** @type {!FunctionMirror} */(mirror); - var count = functionMirror.scopeCount(); - if (count == 0) - return null; - var result = []; - for (var i = 0; i < count; i++) { - var scopeDetails = functionMirror.scope(i).details(); - var scopeObject = DebuggerScript._buildScopeObject(scopeDetails.type(), scopeDetails.object()); - if (!scopeObject) - continue; - result.push({ - type: /** @type {string} */(DebuggerScript._scopeTypeNames.get(scopeDetails.type())), - object: scopeObject, - name: scopeDetails.name() || "" - }); - } - return result; -} - -/** - * @param {Object} object - * @return {?RawLocation} - */ -DebuggerScript.getGeneratorObjectLocation = function(object) -{ - var mirror = MakeMirror(object, true /* transient */); - if (!mirror.isGenerator()) - return null; - var generatorMirror = /** @type {!GeneratorMirror} */(mirror); - var funcMirror = generatorMirror.func(); - if (!funcMirror.resolved()) - return null; - var location = generatorMirror.sourceLocation() || funcMirror.sourceLocation(); - var script = funcMirror.script(); - if (script && location) { - return { - scriptId: "" + script.id(), - lineNumber: location.line, - columnNumber: location.column - }; - } - return null; -} - -/** - * @param {Object} object - * @return {!Array|undefined} - */ -DebuggerScript.getCollectionEntries = function(object) -{ - var mirror = MakeMirror(object, true /* transient */); - if (mirror.isMap()) - return /** @type {!MapMirror} */(mirror).entries(); - if (mirror.isSet() || mirror.isIterator()) { - var result = []; - var values = mirror.isSet() ? /** @type {!SetMirror} */(mirror).values() : /** @type {!IteratorMirror} */(mirror).preview(); - for (var i = 0; i < values.length; ++i) - result.push({ value: values[i] }); - return result; - } -} - -/** - * @param {string|undefined} contextData - * @return {number} - */ -DebuggerScript._executionContextId = function(contextData) -{ - if (!contextData) - return 0; - var match = contextData.match(/^[^,]*,([^,]*),.*$/); - if (!match) - return 0; - return parseInt(match[1], 10) || 0; -} - -/** - * @param {string|undefined} contextData - * @return {string} - */ -DebuggerScript._executionContextAuxData = function(contextData) -{ - if (!contextData) - return ""; - var match = contextData.match(/^[^,]*,[^,]*,(.*)$/); - return match ? match[1] : ""; -} - -/** - * @param {string} contextGroupId - * @return {!Array} - */ -DebuggerScript.getScripts = function(contextGroupId) -{ - var result = []; - var scripts = Debug.scripts(); - var contextDataPrefix = null; - if (contextGroupId) - contextDataPrefix = contextGroupId + ","; - for (var i = 0; i < scripts.length; ++i) { - var script = scripts[i]; - if (contextDataPrefix) { - if (!script.context_data) - continue; - // Context data is a string in the following format: - // ,, - if (script.context_data.indexOf(contextDataPrefix) !== 0) - continue; - } - if (script.is_debugger_script) - continue; - result.push(DebuggerScript._formatScript(script)); - } - return result; -} - -/** - * @param {!Script} script - * @return {!FormattedScript} - */ -DebuggerScript._formatScript = function(script) -{ - var lineEnds = script.line_ends; - var lineCount = lineEnds.length; - var endLine = script.line_offset + lineCount - 1; - var endColumn; - // V8 will not count last line if script source ends with \n. - if (script.source[script.source.length - 1] === '\n') { - endLine += 1; - endColumn = 0; - } else { - if (lineCount === 1) - endColumn = script.source.length + script.column_offset; - else - endColumn = script.source.length - (lineEnds[lineCount - 2] + 1); - } - return { - id: script.id, - name: script.nameOrSourceURL(), - sourceURL: script.source_url, - sourceMappingURL: script.source_mapping_url, - source: script.source, - startLine: script.line_offset, - startColumn: script.column_offset, - endLine: endLine, - endColumn: endColumn, - executionContextId: DebuggerScript._executionContextId(script.context_data), - // Note that we cannot derive aux data from context id because of compilation cache. - executionContextAuxData: DebuggerScript._executionContextAuxData(script.context_data) - }; -} - -/** - * @param {!ExecutionState} execState - * @param {!BreakpointInfo} info - * @return {string|undefined} - */ -DebuggerScript.setBreakpoint = function(execState, info) -{ - var breakId = Debug.setScriptBreakPointById(info.sourceID, info.lineNumber, info.columnNumber, info.condition, undefined, Debug.BreakPositionAlignment.Statement); - var locations = Debug.findBreakPointActualLocations(breakId); - if (!locations.length) - return undefined; - info.lineNumber = locations[0].line; - info.columnNumber = locations[0].column; - return breakId.toString(); -} - -/** - * @param {!ExecutionState} execState - * @param {!{breakpointId: number}} info - */ -DebuggerScript.removeBreakpoint = function(execState, info) -{ - Debug.findBreakPoint(info.breakpointId, true); -} - -/** - * @return {number} - */ -DebuggerScript.pauseOnExceptionsState = function() -{ - return DebuggerScript._pauseOnExceptionsState; -} - -/** - * @param {number} newState - */ -DebuggerScript.setPauseOnExceptionsState = function(newState) -{ - DebuggerScript._pauseOnExceptionsState = newState; - - if (DebuggerScript.PauseOnExceptionsState.PauseOnAllExceptions === newState) - Debug.setBreakOnException(); - else - Debug.clearBreakOnException(); - - if (DebuggerScript.PauseOnExceptionsState.PauseOnUncaughtExceptions === newState) - Debug.setBreakOnUncaughtException(); - else - Debug.clearBreakOnUncaughtException(); -} - -/** - * @param {!ExecutionState} execState - * @param {number} limit - * @return {!Array} - */ -DebuggerScript.currentCallFrames = function(execState, limit) -{ - var frames = []; - for (var i = 0; i < execState.frameCount() && (!limit || i < limit); ++i) - frames.push(DebuggerScript._frameMirrorToJSCallFrame(execState.frame(i))); - return frames; -} - -/** - * @param {!ExecutionState} execState - */ -DebuggerScript.stepIntoStatement = function(execState) -{ - execState.prepareStep(Debug.StepAction.StepIn); -} - -/** - * @param {!ExecutionState} execState - */ -DebuggerScript.stepFrameStatement = function(execState) -{ - execState.prepareStep(Debug.StepAction.StepFrame); -} - -/** - * @param {!ExecutionState} execState - */ -DebuggerScript.stepOverStatement = function(execState) -{ - execState.prepareStep(Debug.StepAction.StepNext); -} - -/** - * @param {!ExecutionState} execState - */ -DebuggerScript.stepOutOfFunction = function(execState) -{ - execState.prepareStep(Debug.StepAction.StepOut); -} - -DebuggerScript.clearStepping = function() -{ - Debug.clearStepping(); -} - -// Returns array in form: -// [ 0, ] in case of success -// or [ 1, , , , ] in case of compile error, numbers are 1-based. -// or throws exception with message. -/** - * @param {number} scriptId - * @param {string} newSource - * @param {boolean} preview - * @return {!Array<*>} - */ -DebuggerScript.liveEditScriptSource = function(scriptId, newSource, preview) -{ - var scripts = Debug.scripts(); - var scriptToEdit = null; - for (var i = 0; i < scripts.length; i++) { - if (scripts[i].id == scriptId) { - scriptToEdit = scripts[i]; - break; - } - } - if (!scriptToEdit) - throw("Script not found"); - - var changeLog = []; - try { - var result = Debug.LiveEdit.SetScriptSource(scriptToEdit, newSource, preview, changeLog); - return [0, result.stack_modified]; - } catch (e) { - if (e instanceof Debug.LiveEdit.Failure && "details" in e) { - var details = /** @type {!LiveEditErrorDetails} */(e.details); - if (details.type === "liveedit_compile_error") { - var startPosition = details.position.start; - return [1, String(e), String(details.syntaxErrorMessage), Number(startPosition.line), Number(startPosition.column)]; - } - } - throw e; - } -} - -/** - * @param {!ExecutionState} execState - */ -DebuggerScript.clearBreakpoints = function(execState) -{ - Debug.clearAllBreakPoints(); -} - -/** - * @param {!ExecutionState} execState - * @param {!{enabled: boolean}} info - */ -DebuggerScript.setBreakpointsActivated = function(execState, info) -{ - Debug.debuggerFlags().breakPointsActive.setValue(info.enabled); -} - -/** - * @param {!BreakEvent} eventData - */ -DebuggerScript.getBreakpointNumbers = function(eventData) -{ - var breakpoints = eventData.breakPointsHit(); - var numbers = []; - if (!breakpoints) - return numbers; - - for (var i = 0; i < breakpoints.length; i++) { - var breakpoint = breakpoints[i]; - var scriptBreakPoint = breakpoint.script_break_point(); - numbers.push(scriptBreakPoint ? scriptBreakPoint.number() : breakpoint.number()); - } - return numbers; -} - -// NOTE: This function is performance critical, as it can be run on every -// statement that generates an async event (like addEventListener) to support -// asynchronous call stacks. Thus, when possible, initialize the data lazily. -/** - * @param {!FrameMirror} frameMirror - * @return {!JavaScriptCallFrame} - */ -DebuggerScript._frameMirrorToJSCallFrame = function(frameMirror) -{ - // Stuff that can not be initialized lazily (i.e. valid while paused with a valid break_id). - // The frameMirror and scopeMirror can be accessed only while paused on the debugger. - var frameDetails = frameMirror.details(); - - var funcObject = frameDetails.func(); - var sourcePosition = frameDetails.sourcePosition(); - var thisObject = frameDetails.receiver(); - - var isAtReturn = !!frameDetails.isAtReturn(); - var returnValue = isAtReturn ? frameDetails.returnValue() : undefined; - - var scopeMirrors = frameMirror.allScopes(false); - /** @type {!Array} */ - var scopeTypes = new Array(scopeMirrors.length); - /** @type {?Array} */ - var scopeObjects = new Array(scopeMirrors.length); - /** @type {!Array} */ - var scopeNames = new Array(scopeMirrors.length); - /** @type {?Array} */ - var scopeStartPositions = new Array(scopeMirrors.length); - /** @type {?Array} */ - var scopeEndPositions = new Array(scopeMirrors.length); - /** @type {?Array} */ - var scopeFunctions = new Array(scopeMirrors.length); - for (var i = 0; i < scopeMirrors.length; ++i) { - var scopeDetails = scopeMirrors[i].details(); - scopeTypes[i] = scopeDetails.type(); - scopeObjects[i] = scopeDetails.object(); - scopeNames[i] = scopeDetails.name(); - scopeStartPositions[i] = scopeDetails.startPosition ? scopeDetails.startPosition() : 0; - scopeEndPositions[i] = scopeDetails.endPosition ? scopeDetails.endPosition() : 0; - scopeFunctions[i] = scopeDetails.func ? scopeDetails.func() : null; - } - - // Calculated lazily. - var scopeChain; - var funcMirror; - var location; - /** @type {!Array} */ - var scopeStartLocations; - /** @type {!Array} */ - var scopeEndLocations; - var details; - - /** - * @param {!ScriptMirror|undefined} script - * @param {number} pos - * @return {?RawLocation} - */ - function createLocation(script, pos) - { - if (!script) - return null; - - var location = script.locationFromPosition(pos, true); - return { - "lineNumber": location.line, - "columnNumber": location.column, - "scriptId": String(script.id()) - } - } - - /** - * @return {!Array} - */ - function ensureScopeChain() - { - if (!scopeChain) { - scopeChain = []; - scopeStartLocations = []; - scopeEndLocations = []; - for (var i = 0, j = 0; i < scopeObjects.length; ++i) { - var scopeObject = DebuggerScript._buildScopeObject(scopeTypes[i], scopeObjects[i]); - if (scopeObject) { - scopeTypes[j] = scopeTypes[i]; - scopeNames[j] = scopeNames[i]; - scopeChain[j] = scopeObject; - - var funcMirror = scopeFunctions ? MakeMirror(scopeFunctions[i]) : null; - if (!funcMirror || !funcMirror.isFunction()) - funcMirror = new UnresolvedFunctionMirror(funcObject); - - var script = /** @type {!FunctionMirror} */(funcMirror).script(); - scopeStartLocations[j] = createLocation(script, scopeStartPositions[i]); - scopeEndLocations[j] = createLocation(script, scopeEndPositions[i]); - ++j; - } - } - scopeTypes.length = scopeChain.length; - scopeNames.length = scopeChain.length; - scopeObjects = null; // Free for GC. - scopeFunctions = null; - scopeStartPositions = null; - scopeEndPositions = null; - } - return scopeChain; - } - - /** - * @return {!JavaScriptCallFrameDetails} - */ - function lazyDetails() - { - if (!details) { - var scopeObjects = ensureScopeChain(); - var script = ensureFuncMirror().script(); - /** @type {!Array} */ - var scopes = []; - for (var i = 0; i < scopeObjects.length; ++i) { - var scope = { - "type": /** @type {string} */(DebuggerScript._scopeTypeNames.get(scopeTypes[i])), - "object": scopeObjects[i], - }; - if (scopeNames[i]) - scope.name = scopeNames[i]; - if (scopeStartLocations[i]) - scope.startLocation = /** @type {!RawLocation} */(scopeStartLocations[i]); - if (scopeEndLocations[i]) - scope.endLocation = /** @type {!RawLocation} */(scopeEndLocations[i]); - scopes.push(scope); - } - details = { - "functionName": ensureFuncMirror().debugName(), - "location": { - "lineNumber": line(), - "columnNumber": column(), - "scriptId": String(script.id()) - }, - "this": thisObject, - "scopeChain": scopes - }; - var functionLocation = ensureFuncMirror().sourceLocation(); - if (functionLocation) { - details.functionLocation = { - "lineNumber": functionLocation.line, - "columnNumber": functionLocation.column, - "scriptId": String(script.id()) - }; - } - if (isAtReturn) - details.returnValue = returnValue; - } - return details; - } - - /** - * @return {!FunctionMirror} - */ - function ensureFuncMirror() - { - if (!funcMirror) { - funcMirror = MakeMirror(funcObject); - if (!funcMirror.isFunction()) - funcMirror = new UnresolvedFunctionMirror(funcObject); - } - return /** @type {!FunctionMirror} */(funcMirror); - } - - /** - * @return {!{line: number, column: number}} - */ - function ensureLocation() - { - if (!location) { - var script = ensureFuncMirror().script(); - if (script) - location = script.locationFromPosition(sourcePosition, true); - if (!location) - location = { line: 0, column: 0 }; - } - return location; - } - - /** - * @return {number} - */ - function line() - { - return ensureLocation().line; - } - - /** - * @return {number} - */ - function column() - { - return ensureLocation().column; - } - - /** - * @return {number} - */ - function contextId() - { - var mirror = ensureFuncMirror(); - // Old V8 do not have context() function on these objects - if (!mirror.context) - return DebuggerScript._executionContextId(mirror.script().value().context_data); - var context = mirror.context(); - if (context) - return DebuggerScript._executionContextId(context.data()); - return 0; - } - - /** - * @return {number|undefined} - */ - function sourceID() - { - var script = ensureFuncMirror().script(); - return script && script.id(); - } - - /** - * @param {string} expression - * @return {*} - */ - function evaluate(expression) - { - return frameMirror.evaluate(expression, false).value(); - } - - /** @return {undefined} */ - function restart() - { - return frameMirror.restart(); - } - - /** - * @param {number} scopeNumber - * @param {string} variableName - * @param {*} newValue - */ - function setVariableValue(scopeNumber, variableName, newValue) - { - var scopeMirror = frameMirror.scope(scopeNumber); - if (!scopeMirror) - throw new Error("Incorrect scope index"); - scopeMirror.setVariableValue(variableName, newValue); - } - - return { - "sourceID": sourceID, - "line": line, - "column": column, - "contextId": contextId, - "thisObject": thisObject, - "evaluate": evaluate, - "restart": restart, - "setVariableValue": setVariableValue, - "isAtReturn": isAtReturn, - "details": lazyDetails - }; -} - -/** - * @param {number} scopeType - * @param {!Object} scopeObject - * @return {!Object|undefined} - */ -DebuggerScript._buildScopeObject = function(scopeType, scopeObject) -{ - var result; - switch (scopeType) { - case ScopeType.Local: - case ScopeType.Closure: - case ScopeType.Catch: - case ScopeType.Block: - case ScopeType.Script: - // For transient objects we create a "persistent" copy that contains - // the same properties. - // Reset scope object prototype to null so that the proto properties - // don't appear in the local scope section. - var properties = /** @type {!ObjectMirror} */(MakeMirror(scopeObject, true /* transient */)).properties(); - // Almost always Script scope will be empty, so just filter out that noise. - // Also drop empty Block scopes, should we get any. - if (!properties.length && (scopeType === ScopeType.Script || scopeType === ScopeType.Block)) - break; - result = { __proto__: null }; - for (var j = 0; j < properties.length; j++) { - var name = properties[j].name(); - if (name.length === 0 || name.charAt(0) === ".") - continue; // Skip internal variables like ".arguments" and variables with empty name - result[name] = properties[j].value_; - } - break; - case ScopeType.Global: - case ScopeType.With: - result = scopeObject; - break; - } - return result; -} - -// We never resolve Mirror by its handle so to avoid memory leaks caused by Mirrors in the cache we disable it. -ToggleMirrorCache(false); - -return DebuggerScript; -})(); diff --git a/deps/v8_inspector/src/inspector/debugger_script_externs.js b/deps/v8_inspector/src/inspector/debugger_script_externs.js deleted file mode 100644 index c7df61f3f49550..00000000000000 --- a/deps/v8_inspector/src/inspector/debugger_script_externs.js +++ /dev/null @@ -1,522 +0,0 @@ -// Copyright 2016 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. - -/** @typedef {{ - type: string, - object: !Object, - name: (string|undefined), - startLocation: (!RawLocation|undefined), - endLocation: (!RawLocation|undefined) - }} */ -var Scope; - -/** @typedef {{ - scriptId: string, - lineNumber: number, - columnNumber: number - }} */ -var RawLocation; - -/** @typedef {{ - id: number, - name: string, - sourceURL: (string|undefined), - sourceMappingURL: (string|undefined), - source: string, - startLine: number, - endLine: number, - startColumn: number, - endColumn: number, - executionContextId: number, - executionContextAuxData: string - }} */ -var FormattedScript; - -/** @typedef {{ - functionName: string, - location: !RawLocation, - this: !Object, - scopeChain: !Array, - functionLocation: (RawLocation|undefined), - returnValue: (*|undefined) - }} */ -var JavaScriptCallFrameDetails; - -/** @typedef {{ - sourceID: function():(number|undefined), - line: function():number, - column: function():number, - thisObject: !Object, - evaluate: function(string):*, - restart: function():undefined, - setVariableValue: function(number, string, *):undefined, - isAtReturn: boolean, - details: function():!JavaScriptCallFrameDetails - }} */ -var JavaScriptCallFrame; - -/** - * @const - */ -var Debug = {}; - -Debug.setBreakOnException = function() {} - -Debug.clearBreakOnException = function() {} - -Debug.setBreakOnUncaughtException = function() {} - -/** - * @return {undefined} - */ -Debug.clearBreakOnUncaughtException = function() {} - -Debug.clearStepping = function() {} - -Debug.clearAllBreakPoints = function() {} - -/** @return {!Array} */ -Debug.scripts = function() {} - -/** - * @param {number} scriptId - * @param {number=} line - * @param {number=} column - * @param {string=} condition - * @param {string=} groupId - * @param {Debug.BreakPositionAlignment=} positionAlignment - */ -Debug.setScriptBreakPointById = function(scriptId, line, column, condition, groupId, positionAlignment) {} - -/** - * @param {number} breakId - * @return {!Array} - */ -Debug.findBreakPointActualLocations = function(breakId) {} - -/** - * @param {number} breakId - * @param {boolean} remove - * @return {!BreakPoint|undefined} - */ -Debug.findBreakPoint = function(breakId, remove) {} - -/** @return {!DebuggerFlags} */ -Debug.debuggerFlags = function() {} - - -/** @enum */ -const BreakPositionAlignment = { - Statement: 0, - BreakPosition: 1 -}; -Debug.BreakPositionAlignment = BreakPositionAlignment; - -/** @enum */ -Debug.StepAction = { StepOut: 0, - StepNext: 1, - StepIn: 2, - StepFrame: 3 }; - -/** @enum */ -const ScriptCompilationType = { Host: 0, - Eval: 1, - JSON: 2 }; -Debug.ScriptCompilationType = ScriptCompilationType; - - -/** @interface */ -function DebuggerFlag() {} - -/** @param {boolean} value */ -DebuggerFlag.prototype.setValue = function(value) {} - - -/** @typedef {{ - * breakPointsActive: !DebuggerFlag - * }} - */ -var DebuggerFlags; - -/** @const */ -var LiveEdit = {} - -/** - * @param {!Script} script - * @param {string} newSource - * @param {boolean} previewOnly - * @return {!{stack_modified: (boolean|undefined)}} - */ -LiveEdit.SetScriptSource = function(script, newSource, previewOnly, change_log) {} - -/** @constructor */ -function Failure() {} -LiveEdit.Failure = Failure; - -Debug.LiveEdit = LiveEdit; - -/** @typedef {{ - * type: string, - * syntaxErrorMessage: string, - * position: !{start: !{line: number, column: number}}, - * }} - */ -var LiveEditErrorDetails; - -/** @typedef {{ - * breakpointId: number, - * sourceID: number, - * lineNumber: (number|undefined), - * columnNumber: (number|undefined), - * condition: (string|undefined), - * interstatementLocation: (boolean|undefined), - * }} - */ -var BreakpointInfo; - - -/** @interface */ -function BreakPoint() {} - -/** @return {!BreakPoint|undefined} */ -BreakPoint.prototype.script_break_point = function() {} - -/** @return {number} */ -BreakPoint.prototype.number = function() {} - - -/** @interface */ -function CompileEvent() {} - -/** @return {!ScriptMirror} */ -CompileEvent.prototype.script = function() {} - - -/** @interface */ -function BreakEvent() {} - -/** @return {!Array|undefined} */ -BreakEvent.prototype.breakPointsHit = function() {} - - -/** @interface */ -function ExecutionState() {} - -/** @param {!Debug.StepAction} action */ -ExecutionState.prototype.prepareStep = function(action) {} - -/** - * @param {string} source - * @param {boolean} disableBreak - * @param {*=} additionalContext - */ -ExecutionState.prototype.evaluateGlobal = function(source, disableBreak, additionalContext) {} - -/** @return {number} */ -ExecutionState.prototype.frameCount = function() {} - -/** - * @param {number} index - * @return {!FrameMirror} - */ -ExecutionState.prototype.frame = function(index) {} - -/** @param {number} index */ -ExecutionState.prototype.setSelectedFrame = function(index) {} - -/** @return {number} */ -ExecutionState.prototype.selectedFrame = function() {} - - -/** @enum */ -var ScopeType = { Global: 0, - Local: 1, - With: 2, - Closure: 3, - Catch: 4, - Block: 5, - Script: 6 }; - - -/** @typedef {{ - * script: number, - * position: number, - * line: number, - * column:number, - * start: number, - * end: number, - * }} - */ -var SourceLocation; - -/** @typedef{{ - * id: number, - * context_data: (string|undefined), - * source_url: (string|undefined), - * source_mapping_url: (string|undefined), - * is_debugger_script: boolean, - * source: string, - * line_ends: !Array, - * line_offset: number, - * column_offset: number, - * nameOrSourceURL: function():string, - * compilationType: function():!ScriptCompilationType, - * }} - */ -var Script; - -/** @interface */ -function ScopeDetails() {} - -/** @return {!Object} */ -ScopeDetails.prototype.object = function() {} - -/** @return {string|undefined} */ -ScopeDetails.prototype.name = function() {} - -/** @return {number} */ -ScopeDetails.prototype.type = function() {} - - -/** @interface */ -function FrameDetails() {} - -/** @return {!Object} */ -FrameDetails.prototype.receiver = function() {} - -/** @return {function()} */ -FrameDetails.prototype.func = function() {} - -/** @return {boolean} */ -FrameDetails.prototype.isAtReturn = function() {} - -/** @return {number} */ -FrameDetails.prototype.sourcePosition = function() {} - -/** @return {*} */ -FrameDetails.prototype.returnValue = function() {} - -/** @return {number} */ -FrameDetails.prototype.scopeCount = function() {} - - -/** @param {boolean} value */ -function ToggleMirrorCache(value) {} - -/** - * @param {*} value - * @param {boolean=} transient - * @return {!Mirror} - */ -function MakeMirror(value, transient) {} - - -/** @interface */ -function Mirror() {} - -/** @return {boolean} */ -Mirror.prototype.isFunction = function() {} - -/** @return {boolean} */ -Mirror.prototype.isGenerator = function() {} - -/** @return {boolean} */ -Mirror.prototype.isMap = function() {} - -/** @return {boolean} */ -Mirror.prototype.isSet = function() {} - -/** @return {boolean} */ -Mirror.prototype.isIterator = function() {} - - -/** - * @interface - * @extends {Mirror} - */ -function ObjectMirror() {} - -/** @return {!Array} */ -ObjectMirror.prototype.properties = function() {} - - -/** - * @interface - * @extends {ObjectMirror} - */ -function FunctionMirror () {} - -/** @return {number} */ -FunctionMirror.prototype.scopeCount = function() {} - -/** - * @param {number} index - * @return {!ScopeMirror|undefined} - */ -FunctionMirror.prototype.scope = function(index) {} - -/** @return {boolean} */ -FunctionMirror.prototype.resolved = function() {} - -/** @return {function()} */ -FunctionMirror.prototype.value = function() {} - -/** @return {string} */ -FunctionMirror.prototype.debugName = function() {} - -/** @return {!ScriptMirror|undefined} */ -FunctionMirror.prototype.script = function() {} - -/** @return {!SourceLocation|undefined} */ -FunctionMirror.prototype.sourceLocation = function() {} - -/** @return {!ContextMirror|undefined} */ -FunctionMirror.prototype.context = function() {} - -/** - * @constructor - * @param {*} value - */ -function UnresolvedFunctionMirror(value) {} - - -/** - * @interface - * @extends {ObjectMirror} - */ -function MapMirror () {} - -/** - * @param {number=} limit - * @return {!Array} - */ -MapMirror.prototype.entries = function(limit) {} - - -/** - * @interface - * @extends {ObjectMirror} - */ -function SetMirror () {} - -/** - * @param {number=} limit - * @return {!Array<*>} - */ -SetMirror.prototype.values = function(limit) {} - - -/** - * @interface - * @extends {ObjectMirror} - */ -function IteratorMirror () {} - -/** - * @param {number=} limit - * @return {!Array<*>} - */ -IteratorMirror.prototype.preview = function(limit) {} - - -/** - * @interface - * @extends {ObjectMirror} - */ -function GeneratorMirror () {} - -/** @return {string} */ -GeneratorMirror.prototype.status = function() {} - -/** @return {!SourceLocation|undefined} */ -GeneratorMirror.prototype.sourceLocation = function() {} - -/** @return {!FunctionMirror} */ -GeneratorMirror.prototype.func = function() {} - - -/** - * @interface - * @extends {Mirror} - */ -function PropertyMirror() {} - -/** @return {!Mirror} */ -PropertyMirror.prototype.value = function() {} - -/** @return {string} */ -PropertyMirror.prototype.name = function() {} - -/** @type {*} */ -PropertyMirror.prototype.value_; - -/** - * @interface - * @extends {Mirror} - */ -function FrameMirror() {} - -/** - * @param {boolean=} ignoreNestedScopes - * @return {!Array} - */ -FrameMirror.prototype.allScopes = function(ignoreNestedScopes) {} - -/** @return {!FrameDetails} */ -FrameMirror.prototype.details = function() {} - -/** - * @param {string} source - * @param {boolean} disableBreak - */ -FrameMirror.prototype.evaluate = function(source, disableBreak) {} - -FrameMirror.prototype.restart = function() {} - -/** @param {number} index */ -FrameMirror.prototype.scope = function(index) {} - - -/** - * @interface - * @extends {Mirror} - */ -function ScriptMirror() {} - -/** @return {!Script} */ -ScriptMirror.prototype.value = function() {} - -/** @return {number} */ -ScriptMirror.prototype.id = function() {} - -/** - * @param {number} position - * @param {boolean=} includeResourceOffset - */ -ScriptMirror.prototype.locationFromPosition = function(position, includeResourceOffset) {} - - -/** - * @interface - * @extends {Mirror} - */ -function ScopeMirror() {} - -/** @return {!ScopeDetails} */ -ScopeMirror.prototype.details = function() {} - -/** - * @param {string} name - * @param {*} newValue - */ -ScopeMirror.prototype.setVariableValue = function(name, newValue) {} - -/** - * @interface - * @extends {Mirror} - */ -function ContextMirror() {} - -/** @return {string|undefined} */ -ContextMirror.prototype.data = function() {} diff --git a/deps/v8_inspector/src/inspector/injected-script-native.cc b/deps/v8_inspector/src/inspector/injected-script-native.cc deleted file mode 100644 index fcf2ead94b3faa..00000000000000 --- a/deps/v8_inspector/src/inspector/injected-script-native.cc +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2015 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. - -#include "src/inspector/injected-script-native.h" - -namespace v8_inspector { - -InjectedScriptNative::InjectedScriptNative(v8::Isolate* isolate) - : m_lastBoundObjectId(1), m_isolate(isolate) {} - -static const char privateKeyName[] = "v8-inspector#injectedScript"; - -InjectedScriptNative::~InjectedScriptNative() {} - -void InjectedScriptNative::setOnInjectedScriptHost( - v8::Local injectedScriptHost) { - v8::HandleScope handleScope(m_isolate); - v8::Local external = v8::External::New(m_isolate, this); - v8::Local privateKey = v8::Private::ForApi( - m_isolate, v8::String::NewFromUtf8(m_isolate, privateKeyName, - v8::NewStringType::kInternalized) - .ToLocalChecked()); - injectedScriptHost->SetPrivate(m_isolate->GetCurrentContext(), privateKey, - external); -} - -InjectedScriptNative* InjectedScriptNative::fromInjectedScriptHost( - v8::Isolate* isolate, v8::Local injectedScriptObject) { - v8::HandleScope handleScope(isolate); - v8::Local context = isolate->GetCurrentContext(); - v8::Local privateKey = v8::Private::ForApi( - isolate, v8::String::NewFromUtf8(isolate, privateKeyName, - v8::NewStringType::kInternalized) - .ToLocalChecked()); - v8::Local value = - injectedScriptObject->GetPrivate(context, privateKey).ToLocalChecked(); - DCHECK(value->IsExternal()); - v8::Local external = value.As(); - return static_cast(external->Value()); -} - -int InjectedScriptNative::bind(v8::Local value, - const String16& groupName) { - if (m_lastBoundObjectId <= 0) m_lastBoundObjectId = 1; - int id = m_lastBoundObjectId++; - m_idToWrappedObject[id] = - wrapUnique(new v8::Global(m_isolate, value)); - addObjectToGroup(id, groupName); - return id; -} - -void InjectedScriptNative::unbind(int id) { - m_idToWrappedObject.erase(id); - m_idToObjectGroupName.erase(id); -} - -v8::Local InjectedScriptNative::objectForId(int id) { - auto iter = m_idToWrappedObject.find(id); - return iter != m_idToWrappedObject.end() ? iter->second->Get(m_isolate) - : v8::Local(); -} - -void InjectedScriptNative::addObjectToGroup(int objectId, - const String16& groupName) { - if (groupName.isEmpty()) return; - if (objectId <= 0) return; - m_idToObjectGroupName[objectId] = groupName; - m_nameToObjectGroup[groupName].push_back( - objectId); // Creates an empty vector if key is not there -} - -void InjectedScriptNative::releaseObjectGroup(const String16& groupName) { - if (groupName.isEmpty()) return; - NameToObjectGroup::iterator groupIt = m_nameToObjectGroup.find(groupName); - if (groupIt == m_nameToObjectGroup.end()) return; - for (int id : groupIt->second) unbind(id); - m_nameToObjectGroup.erase(groupIt); -} - -String16 InjectedScriptNative::groupName(int objectId) const { - if (objectId <= 0) return String16(); - IdToObjectGroupName::const_iterator iterator = - m_idToObjectGroupName.find(objectId); - return iterator != m_idToObjectGroupName.end() ? iterator->second - : String16(); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/injected-script-native.h b/deps/v8_inspector/src/inspector/injected-script-native.h deleted file mode 100644 index 3bdf24709dcd2a..00000000000000 --- a/deps/v8_inspector/src/inspector/injected-script-native.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2015 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_INJECTEDSCRIPTNATIVE_H_ -#define V8_INSPECTOR_INJECTEDSCRIPTNATIVE_H_ - -#include - -#include "src/inspector/protocol/Protocol.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class InjectedScriptNative final { - public: - explicit InjectedScriptNative(v8::Isolate*); - ~InjectedScriptNative(); - - void setOnInjectedScriptHost(v8::Local); - static InjectedScriptNative* fromInjectedScriptHost(v8::Isolate* isolate, - v8::Local); - - int bind(v8::Local, const String16& groupName); - void unbind(int id); - v8::Local objectForId(int id); - - void releaseObjectGroup(const String16& groupName); - String16 groupName(int objectId) const; - - private: - void addObjectToGroup(int objectId, const String16& groupName); - - int m_lastBoundObjectId; - v8::Isolate* m_isolate; - protocol::HashMap>> - m_idToWrappedObject; - typedef protocol::HashMap IdToObjectGroupName; - IdToObjectGroupName m_idToObjectGroupName; - typedef protocol::HashMap> NameToObjectGroup; - NameToObjectGroup m_nameToObjectGroup; -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_INJECTEDSCRIPTNATIVE_H_ diff --git a/deps/v8_inspector/src/inspector/injected-script-source.js b/deps/v8_inspector/src/inspector/injected-script-source.js deleted file mode 100644 index 39c6c9c1e84b0d..00000000000000 --- a/deps/v8_inspector/src/inspector/injected-script-source.js +++ /dev/null @@ -1,1076 +0,0 @@ -/* - * Copyright (C) 2007 Apple Inc. All rights reserved. - * Copyright (C) 2013 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -"use strict"; - -/** - * @param {!InjectedScriptHostClass} InjectedScriptHost - * @param {!Window|!WorkerGlobalScope} inspectedGlobalObject - * @param {number} injectedScriptId - * @suppress {uselessCode} - */ -(function (InjectedScriptHost, inspectedGlobalObject, injectedScriptId) { - -/** - * Protect against Object overwritten by the user code. - * @suppress {duplicate} - */ -var Object = /** @type {function(new:Object, *=)} */ ({}.constructor); - -/** - * @param {!Array.} array - * @param {...} var_args - * @template T - */ -function push(array, var_args) -{ - for (var i = 1; i < arguments.length; ++i) - array[array.length] = arguments[i]; -} - -/** - * @param {*} obj - * @return {string} - * @suppress {uselessCode} - */ -function toString(obj) -{ - // We don't use String(obj) because String could be overridden. - // Also the ("" + obj) expression may throw. - try { - return "" + obj; - } catch (e) { - var name = InjectedScriptHost.internalConstructorName(obj) || InjectedScriptHost.subtype(obj) || (typeof obj); - return "#<" + name + ">"; - } -} - -/** - * @param {*} obj - * @return {string} - */ -function toStringDescription(obj) -{ - if (typeof obj === "number" && obj === 0 && 1 / obj < 0) - return "-0"; // Negative zero. - return toString(obj); -} - -/** - * @param {T} obj - * @return {T} - * @template T - */ -function nullifyObjectProto(obj) -{ - if (obj && typeof obj === "object") - obj.__proto__ = null; - return obj; -} - -/** - * @param {number|string} obj - * @return {boolean} - */ -function isUInt32(obj) -{ - if (typeof obj === "number") - return obj >>> 0 === obj && (obj > 0 || 1 / obj > 0); - return "" + (obj >>> 0) === obj; -} - -/** - * FireBug's array detection. - * @param {*} obj - * @return {boolean} - */ -function isArrayLike(obj) -{ - if (typeof obj !== "object") - return false; - try { - if (typeof obj.splice === "function") { - if (!InjectedScriptHost.objectHasOwnProperty(/** @type {!Object} */ (obj), "length")) - return false; - var len = obj.length; - return typeof len === "number" && isUInt32(len); - } - } catch (e) { - } - return false; -} - -/** - * @param {number} a - * @param {number} b - * @return {number} - */ -function max(a, b) -{ - return a > b ? a : b; -} - -/** - * FIXME: Remove once ES6 is supported natively by JS compiler. - * @param {*} obj - * @return {boolean} - */ -function isSymbol(obj) -{ - var type = typeof obj; - return (type === "symbol"); -} - -/** - * DOM Attributes which have observable side effect on getter, in the form of - * {interfaceName1: {attributeName1: true, - * attributeName2: true, - * ...}, - * interfaceName2: {...}, - * ...} - * @type {!Object>} - * @const - */ -var domAttributesWithObservableSideEffectOnGet = nullifyObjectProto({}); -domAttributesWithObservableSideEffectOnGet["Request"] = nullifyObjectProto({}); -domAttributesWithObservableSideEffectOnGet["Request"]["body"] = true; -domAttributesWithObservableSideEffectOnGet["Response"] = nullifyObjectProto({}); -domAttributesWithObservableSideEffectOnGet["Response"]["body"] = true; - -/** - * @param {!Object} object - * @param {string} attribute - * @return {boolean} - */ -function doesAttributeHaveObservableSideEffectOnGet(object, attribute) -{ - for (var interfaceName in domAttributesWithObservableSideEffectOnGet) { - var interfaceFunction = inspectedGlobalObject[interfaceName]; - // Call to instanceOf looks safe after typeof check. - var isInstance = typeof interfaceFunction === "function" && /* suppressBlacklist */ object instanceof interfaceFunction; - if (isInstance) - return attribute in domAttributesWithObservableSideEffectOnGet[interfaceName]; - } - return false; -} - -/** - * @constructor - */ -var InjectedScript = function() -{ -} - -/** - * @type {!Object.} - * @const - */ -InjectedScript.primitiveTypes = { - "undefined": true, - "boolean": true, - "number": true, - "string": true, - __proto__: null -} - -/** - * @type {!Object} - * @const - */ -InjectedScript.closureTypes = { __proto__: null }; -InjectedScript.closureTypes["local"] = "Local"; -InjectedScript.closureTypes["closure"] = "Closure"; -InjectedScript.closureTypes["catch"] = "Catch"; -InjectedScript.closureTypes["block"] = "Block"; -InjectedScript.closureTypes["script"] = "Script"; -InjectedScript.closureTypes["with"] = "With Block"; -InjectedScript.closureTypes["global"] = "Global"; - -InjectedScript.prototype = { - /** - * @param {*} object - * @return {boolean} - */ - isPrimitiveValue: function(object) - { - // FIXME(33716): typeof document.all is always 'undefined'. - return InjectedScript.primitiveTypes[typeof object] && !this._isHTMLAllCollection(object); - }, - - /** - * @param {*} object - * @return {boolean} - */ - _shouldPassByValue: function(object) - { - return typeof object === "object" && InjectedScriptHost.subtype(object) === "internal#location"; - }, - - /** - * @param {*} object - * @param {string} groupName - * @param {boolean} forceValueType - * @param {boolean} generatePreview - * @return {!RuntimeAgent.RemoteObject} - */ - wrapObject: function(object, groupName, forceValueType, generatePreview) - { - return this._wrapObject(object, groupName, forceValueType, generatePreview); - }, - - /** - * @param {!Array} array - * @param {string} property - * @param {string} groupName - * @param {boolean} forceValueType - * @param {boolean} generatePreview - */ - wrapPropertyInArray: function(array, property, groupName, forceValueType, generatePreview) - { - for (var i = 0; i < array.length; ++i) { - if (typeof array[i] === "object" && property in array[i]) - array[i][property] = this.wrapObject(array[i][property], groupName, forceValueType, generatePreview); - } - }, - - /** - * @param {!Array<*>} array - * @param {string} groupName - * @param {boolean} forceValueType - * @param {boolean} generatePreview - */ - wrapObjectsInArray: function(array, groupName, forceValueType, generatePreview) - { - for (var i = 0; i < array.length; ++i) - array[i] = this.wrapObject(array[i], groupName, forceValueType, generatePreview); - }, - - /** - * @param {!Object} table - * @param {!Array.|string|boolean} columns - * @return {!RuntimeAgent.RemoteObject} - */ - wrapTable: function(table, columns) - { - var columnNames = null; - if (typeof columns === "string") - columns = [columns]; - if (InjectedScriptHost.subtype(columns) === "array") { - columnNames = []; - for (var i = 0; i < columns.length; ++i) - columnNames[i] = toString(columns[i]); - } - return this._wrapObject(table, "console", false, true, columnNames, true); - }, - - /** - * This method cannot throw. - * @param {*} object - * @param {string=} objectGroupName - * @param {boolean=} forceValueType - * @param {boolean=} generatePreview - * @param {?Array.=} columnNames - * @param {boolean=} isTable - * @param {boolean=} doNotBind - * @param {*=} customObjectConfig - * @return {!RuntimeAgent.RemoteObject} - * @suppress {checkTypes} - */ - _wrapObject: function(object, objectGroupName, forceValueType, generatePreview, columnNames, isTable, doNotBind, customObjectConfig) - { - try { - return new InjectedScript.RemoteObject(object, objectGroupName, doNotBind, forceValueType, generatePreview, columnNames, isTable, undefined, customObjectConfig); - } catch (e) { - try { - var description = injectedScript._describe(e); - } catch (ex) { - var description = ""; - } - return new InjectedScript.RemoteObject(description); - } - }, - - /** - * @param {!Object|symbol} object - * @param {string=} objectGroupName - * @return {string} - */ - _bind: function(object, objectGroupName) - { - var id = InjectedScriptHost.bind(object, objectGroupName || ""); - return "{\"injectedScriptId\":" + injectedScriptId + ",\"id\":" + id + "}"; - }, - - /** - * @param {!Object} object - * @param {string} objectGroupName - * @param {boolean} ownProperties - * @param {boolean} accessorPropertiesOnly - * @param {boolean} generatePreview - * @return {!Array|boolean} - */ - getProperties: function(object, objectGroupName, ownProperties, accessorPropertiesOnly, generatePreview) - { - var subtype = this._subtype(object); - if (subtype === "internal#scope") { - // Internally, scope contains object with scope variables and additional information like type, - // we use additional information for preview and would like to report variables as scope - // properties. - object = object.object; - } - - var descriptors = []; - var iter = this._propertyDescriptors(object, ownProperties, accessorPropertiesOnly, undefined); - // Go over properties, wrap object values. - for (var descriptor of iter) { - if (subtype === "internal#scopeList" && descriptor.name === "length") - continue; - if ("get" in descriptor) - descriptor.get = this._wrapObject(descriptor.get, objectGroupName); - if ("set" in descriptor) - descriptor.set = this._wrapObject(descriptor.set, objectGroupName); - if ("value" in descriptor) - descriptor.value = this._wrapObject(descriptor.value, objectGroupName, false, generatePreview); - if (!("configurable" in descriptor)) - descriptor.configurable = false; - if (!("enumerable" in descriptor)) - descriptor.enumerable = false; - if ("symbol" in descriptor) - descriptor.symbol = this._wrapObject(descriptor.symbol, objectGroupName); - push(descriptors, descriptor); - } - return descriptors; - }, - - /** - * @param {!Object} object - * @return {?Object} - */ - _objectPrototype: function(object) - { - if (InjectedScriptHost.subtype(object) === "proxy") - return null; - try { - return Object.getPrototypeOf(object); - } catch (e) { - return null; - } - }, - - /** - * @param {!Object} object - * @param {boolean=} ownProperties - * @param {boolean=} accessorPropertiesOnly - * @param {?Array.=} propertyNamesOnly - */ - _propertyDescriptors: function*(object, ownProperties, accessorPropertiesOnly, propertyNamesOnly) - { - var propertyProcessed = { __proto__: null }; - - /** - * @param {?Object} o - * @param {!Iterable|!Array} properties - */ - function* process(o, properties) - { - for (var property of properties) { - var name; - if (isSymbol(property)) - name = /** @type {string} */ (injectedScript._describe(property)); - else - name = typeof property === "number" ? ("" + property) : /** @type {string} */(property); - - if (propertyProcessed[property]) - continue; - - try { - propertyProcessed[property] = true; - var descriptor = nullifyObjectProto(Object.getOwnPropertyDescriptor(o, property)); - if (descriptor) { - if (accessorPropertiesOnly && !("get" in descriptor || "set" in descriptor)) - continue; - if ("get" in descriptor && "set" in descriptor && name != "__proto__" && InjectedScriptHost.formatAccessorsAsProperties(object, descriptor.get) && !doesAttributeHaveObservableSideEffectOnGet(object, name)) { - descriptor.value = object[property]; - descriptor.isOwn = true; - delete descriptor.get; - delete descriptor.set; - } - } else { - // Not all bindings provide proper descriptors. Fall back to the writable, configurable property. - if (accessorPropertiesOnly) - continue; - try { - descriptor = { name: name, value: o[property], writable: false, configurable: false, enumerable: false, __proto__: null }; - if (o === object) - descriptor.isOwn = true; - yield descriptor; - } catch (e) { - // Silent catch. - } - continue; - } - } catch (e) { - if (accessorPropertiesOnly) - continue; - var descriptor = { __proto__: null }; - descriptor.value = e; - descriptor.wasThrown = true; - } - - descriptor.name = name; - if (o === object) - descriptor.isOwn = true; - if (isSymbol(property)) - descriptor.symbol = property; - yield descriptor; - } - } - - if (propertyNamesOnly) { - for (var i = 0; i < propertyNamesOnly.length; ++i) { - var name = propertyNamesOnly[i]; - for (var o = object; this._isDefined(o); o = this._objectPrototype(o)) { - if (InjectedScriptHost.objectHasOwnProperty(o, name)) { - for (var descriptor of process(o, [name])) - yield descriptor; - break; - } - if (ownProperties) - break; - } - } - return; - } - - /** - * @param {number} length - */ - function* arrayIndexNames(length) - { - for (var i = 0; i < length; ++i) - yield "" + i; - } - - var skipGetOwnPropertyNames; - try { - skipGetOwnPropertyNames = InjectedScriptHost.subtype(object) === "typedarray" && object.length > 500000; - } catch (e) { - } - - for (var o = object; this._isDefined(o); o = this._objectPrototype(o)) { - if (InjectedScriptHost.subtype(o) === "proxy") - continue; - if (skipGetOwnPropertyNames && o === object) { - // Avoid OOM crashes from getting all own property names of a large TypedArray. - for (var descriptor of process(o, arrayIndexNames(o.length))) - yield descriptor; - } else { - // First call Object.keys() to enforce ordering of the property descriptors. - for (var descriptor of process(o, Object.keys(/** @type {!Object} */ (o)))) - yield descriptor; - for (var descriptor of process(o, Object.getOwnPropertyNames(/** @type {!Object} */ (o)))) - yield descriptor; - } - if (Object.getOwnPropertySymbols) { - for (var descriptor of process(o, Object.getOwnPropertySymbols(/** @type {!Object} */ (o)))) - yield descriptor; - } - if (ownProperties) { - var proto = this._objectPrototype(o); - if (proto && !accessorPropertiesOnly) - yield { name: "__proto__", value: proto, writable: true, configurable: true, enumerable: false, isOwn: true, __proto__: null }; - break; - } - } - }, - - /** - * @param {string|undefined} objectGroupName - * @param {*} jsonMLObject - * @throws {string} error message - */ - _substituteObjectTagsInCustomPreview: function(objectGroupName, jsonMLObject) - { - var maxCustomPreviewRecursionDepth = 20; - this._customPreviewRecursionDepth = (this._customPreviewRecursionDepth || 0) + 1 - try { - if (this._customPreviewRecursionDepth >= maxCustomPreviewRecursionDepth) - throw new Error("Too deep hierarchy of inlined custom previews"); - - if (!isArrayLike(jsonMLObject)) - return; - - if (jsonMLObject[0] === "object") { - var attributes = jsonMLObject[1]; - var originObject = attributes["object"]; - var config = attributes["config"]; - if (typeof originObject === "undefined") - throw new Error("Illegal format: obligatory attribute \"object\" isn't specified"); - - jsonMLObject[1] = this._wrapObject(originObject, objectGroupName, false, false, null, false, false, config); - return; - } - - for (var i = 0; i < jsonMLObject.length; ++i) - this._substituteObjectTagsInCustomPreview(objectGroupName, jsonMLObject[i]); - } finally { - this._customPreviewRecursionDepth--; - } - }, - - /** - * @param {*} object - * @return {boolean} - */ - _isDefined: function(object) - { - return !!object || this._isHTMLAllCollection(object); - }, - - /** - * @param {*} object - * @return {boolean} - */ - _isHTMLAllCollection: function(object) - { - // document.all is reported as undefined, but we still want to process it. - return (typeof object === "undefined") && !!InjectedScriptHost.subtype(object); - }, - - /** - * @param {*} obj - * @return {?string} - */ - _subtype: function(obj) - { - if (obj === null) - return "null"; - - if (this.isPrimitiveValue(obj)) - return null; - - var subtype = InjectedScriptHost.subtype(obj); - if (subtype) - return subtype; - - if (isArrayLike(obj)) - return "array"; - - // If owning frame has navigated to somewhere else window properties will be undefined. - return null; - }, - - /** - * @param {*} obj - * @return {?string} - */ - _describe: function(obj) - { - if (this.isPrimitiveValue(obj)) - return null; - - var subtype = this._subtype(obj); - - if (subtype === "regexp") - return toString(obj); - - if (subtype === "date") - return toString(obj); - - if (subtype === "node") { - var description = ""; - if (obj.nodeName) - description = obj.nodeName.toLowerCase(); - else if (obj.constructor) - description = obj.constructor.name.toLowerCase(); - - switch (obj.nodeType) { - case 1 /* Node.ELEMENT_NODE */: - description += obj.id ? "#" + obj.id : ""; - var className = obj.className; - description += (className && typeof className === "string") ? "." + className.trim().replace(/\s+/g, ".") : ""; - break; - case 10 /*Node.DOCUMENT_TYPE_NODE */: - description = ""; - break; - } - return description; - } - - if (subtype === "proxy") - return "Proxy"; - - var className = InjectedScriptHost.internalConstructorName(obj); - if (subtype === "array" || subtype === "typedarray") { - if (typeof obj.length === "number") - className += "[" + obj.length + "]"; - return className; - } - - if (typeof obj === "function") - return toString(obj); - - if (isSymbol(obj)) { - try { - // It isn't safe, because Symbol.prototype.toString can be overriden. - return /* suppressBlacklist */ obj.toString() || "Symbol"; - } catch (e) { - return "Symbol"; - } - } - - if (InjectedScriptHost.subtype(obj) === "error") { - try { - var stack = obj.stack; - var message = obj.message && obj.message.length ? ": " + obj.message : ""; - var firstCallFrame = /^\s+at\s/m.exec(stack); - var stackMessageEnd = firstCallFrame ? firstCallFrame.index : -1; - if (stackMessageEnd !== -1) { - var stackTrace = stack.substr(stackMessageEnd); - return className + message + "\n" + stackTrace; - } - return className + message; - } catch(e) { - } - } - - if (subtype === "internal#entry") { - if ("key" in obj) - return "{" + this._describeIncludingPrimitives(obj.key) + " => " + this._describeIncludingPrimitives(obj.value) + "}"; - return this._describeIncludingPrimitives(obj.value); - } - - if (subtype === "internal#scopeList") - return "Scopes[" + obj.length + "]"; - - if (subtype === "internal#scope") - return (InjectedScript.closureTypes[obj.type] || "Unknown") + (obj.name ? " (" + obj.name + ")" : ""); - - return className; - }, - - /** - * @param {*} value - * @return {string} - */ - _describeIncludingPrimitives: function(value) - { - if (typeof value === "string") - return "\"" + value.replace(/\n/g, "\u21B5") + "\""; - if (value === null) - return "" + value; - return this.isPrimitiveValue(value) ? toStringDescription(value) : (this._describe(value) || ""); - }, - - /** - * @param {boolean} enabled - */ - setCustomObjectFormatterEnabled: function(enabled) - { - this._customObjectFormatterEnabled = enabled; - } -} - -/** - * @type {!InjectedScript} - * @const - */ -var injectedScript = new InjectedScript(); - -/** - * @constructor - * @param {*} object - * @param {string=} objectGroupName - * @param {boolean=} doNotBind - * @param {boolean=} forceValueType - * @param {boolean=} generatePreview - * @param {?Array.=} columnNames - * @param {boolean=} isTable - * @param {boolean=} skipEntriesPreview - * @param {*=} customObjectConfig - */ -InjectedScript.RemoteObject = function(object, objectGroupName, doNotBind, forceValueType, generatePreview, columnNames, isTable, skipEntriesPreview, customObjectConfig) -{ - this.type = typeof object; - if (this.type === "undefined" && injectedScript._isHTMLAllCollection(object)) - this.type = "object"; - - if (injectedScript.isPrimitiveValue(object) || object === null || forceValueType) { - // We don't send undefined values over JSON. - if (this.type !== "undefined") - this.value = object; - - // Null object is object with 'null' subtype. - if (object === null) - this.subtype = "null"; - - // Provide user-friendly number values. - if (this.type === "number") { - this.description = toStringDescription(object); - switch (this.description) { - case "NaN": - case "Infinity": - case "-Infinity": - case "-0": - delete this.value; - this.unserializableValue = this.description; - break; - } - } - - return; - } - - if (injectedScript._shouldPassByValue(object)) { - this.value = object; - this.subtype = injectedScript._subtype(object); - this.description = injectedScript._describeIncludingPrimitives(object); - return; - } - - object = /** @type {!Object} */ (object); - - if (!doNotBind) - this.objectId = injectedScript._bind(object, objectGroupName); - var subtype = injectedScript._subtype(object); - if (subtype) - this.subtype = subtype; - var className = InjectedScriptHost.internalConstructorName(object); - if (className) - this.className = className; - this.description = injectedScript._describe(object); - - if (generatePreview && this.type === "object") { - if (this.subtype === "proxy") - this.preview = this._generatePreview(InjectedScriptHost.proxyTargetValue(object), undefined, columnNames, isTable, skipEntriesPreview); - else if (this.subtype !== "node") - this.preview = this._generatePreview(object, undefined, columnNames, isTable, skipEntriesPreview); - } - - if (injectedScript._customObjectFormatterEnabled) { - var customPreview = this._customPreview(object, objectGroupName, customObjectConfig); - if (customPreview) - this.customPreview = customPreview; - } -} - -InjectedScript.RemoteObject.prototype = { - - /** - * @param {*} object - * @param {string=} objectGroupName - * @param {*=} customObjectConfig - * @return {?RuntimeAgent.CustomPreview} - */ - _customPreview: function(object, objectGroupName, customObjectConfig) - { - /** - * @param {!Error} error - */ - function logError(error) - { - // We use user code to generate custom output for object, we can use user code for reporting error too. - Promise.resolve().then(/* suppressBlacklist */ inspectedGlobalObject.console.error.bind(inspectedGlobalObject.console, "Custom Formatter Failed: " + error.message)); - } - - /** - * @param {*} object - * @param {*=} customObjectConfig - * @return {*} - */ - function wrap(object, customObjectConfig) - { - return injectedScript._wrapObject(object, objectGroupName, false, false, null, false, false, customObjectConfig); - } - - try { - var formatters = inspectedGlobalObject["devtoolsFormatters"]; - if (!formatters || !isArrayLike(formatters)) - return null; - - for (var i = 0; i < formatters.length; ++i) { - try { - var formatted = formatters[i].header(object, customObjectConfig); - if (!formatted) - continue; - - var hasBody = formatters[i].hasBody(object, customObjectConfig); - injectedScript._substituteObjectTagsInCustomPreview(objectGroupName, formatted); - var formatterObjectId = injectedScript._bind(formatters[i], objectGroupName); - var bindRemoteObjectFunctionId = injectedScript._bind(wrap, objectGroupName); - var result = {header: JSON.stringify(formatted), hasBody: !!hasBody, formatterObjectId: formatterObjectId, bindRemoteObjectFunctionId: bindRemoteObjectFunctionId}; - if (customObjectConfig) - result["configObjectId"] = injectedScript._bind(customObjectConfig, objectGroupName); - return result; - } catch (e) { - logError(e); - } - } - } catch (e) { - logError(e); - } - return null; - }, - - /** - * @return {!RuntimeAgent.ObjectPreview} preview - */ - _createEmptyPreview: function() - { - var preview = { - type: /** @type {!RuntimeAgent.ObjectPreviewType.} */ (this.type), - description: this.description || toStringDescription(this.value), - overflow: false, - properties: [], - __proto__: null - }; - if (this.subtype) - preview.subtype = /** @type {!RuntimeAgent.ObjectPreviewSubtype.} */ (this.subtype); - return preview; - }, - - /** - * @param {!Object} object - * @param {?Array.=} firstLevelKeys - * @param {?Array.=} secondLevelKeys - * @param {boolean=} isTable - * @param {boolean=} skipEntriesPreview - * @return {!RuntimeAgent.ObjectPreview} preview - */ - _generatePreview: function(object, firstLevelKeys, secondLevelKeys, isTable, skipEntriesPreview) - { - var preview = this._createEmptyPreview(); - var firstLevelKeysCount = firstLevelKeys ? firstLevelKeys.length : 0; - - var propertiesThreshold = { - properties: isTable ? 1000 : max(5, firstLevelKeysCount), - indexes: isTable ? 1000 : max(100, firstLevelKeysCount), - __proto__: null - }; - - try { - var descriptors = injectedScript._propertyDescriptors(object, undefined, undefined, firstLevelKeys); - - this._appendPropertyDescriptors(preview, descriptors, propertiesThreshold, secondLevelKeys, isTable); - if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) - return preview; - - // Add internal properties to preview. - var rawInternalProperties = InjectedScriptHost.getInternalProperties(object) || []; - var internalProperties = []; - var entries = null; - for (var i = 0; i < rawInternalProperties.length; i += 2) { - if (rawInternalProperties[i] === "[[Entries]]") { - entries = /** @type {!Array<*>} */(rawInternalProperties[i + 1]); - continue; - } - push(internalProperties, { - name: rawInternalProperties[i], - value: rawInternalProperties[i + 1], - isOwn: true, - enumerable: true, - __proto__: null - }); - } - this._appendPropertyDescriptors(preview, internalProperties, propertiesThreshold, secondLevelKeys, isTable); - - if (this.subtype === "map" || this.subtype === "set" || this.subtype === "iterator") - this._appendEntriesPreview(entries, preview, skipEntriesPreview); - - } catch (e) {} - - return preview; - }, - - /** - * @param {!RuntimeAgent.ObjectPreview} preview - * @param {!Array.<*>|!Iterable.<*>} descriptors - * @param {!Object} propertiesThreshold - * @param {?Array.=} secondLevelKeys - * @param {boolean=} isTable - */ - _appendPropertyDescriptors: function(preview, descriptors, propertiesThreshold, secondLevelKeys, isTable) - { - for (var descriptor of descriptors) { - if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) - break; - if (!descriptor || descriptor.wasThrown) - continue; - - var name = descriptor.name; - - // Ignore __proto__ property. - if (name === "__proto__") - continue; - - // Ignore length property of array. - if ((this.subtype === "array" || this.subtype === "typedarray") && name === "length") - continue; - - // Ignore size property of map, set. - if ((this.subtype === "map" || this.subtype === "set") && name === "size") - continue; - - // Never preview prototype properties. - if (!descriptor.isOwn) - continue; - - // Ignore computed properties. - if (!("value" in descriptor)) - continue; - - var value = descriptor.value; - var type = typeof value; - - // Never render functions in object preview. - if (type === "function" && (this.subtype !== "array" || !isUInt32(name))) - continue; - - // Special-case HTMLAll. - if (type === "undefined" && injectedScript._isHTMLAllCollection(value)) - type = "object"; - - // Render own properties. - if (value === null) { - this._appendPropertyPreview(preview, { name: name, type: "object", subtype: "null", value: "null", __proto__: null }, propertiesThreshold); - continue; - } - - var maxLength = 100; - if (InjectedScript.primitiveTypes[type]) { - if (type === "string" && value.length > maxLength) - value = this._abbreviateString(value, maxLength, true); - this._appendPropertyPreview(preview, { name: name, type: type, value: toStringDescription(value), __proto__: null }, propertiesThreshold); - continue; - } - - var property = { name: name, type: type, __proto__: null }; - var subtype = injectedScript._subtype(value); - if (subtype) - property.subtype = subtype; - - if (secondLevelKeys === null || secondLevelKeys) { - var subPreview = this._generatePreview(value, secondLevelKeys || undefined, undefined, isTable); - property.valuePreview = subPreview; - if (subPreview.overflow) - preview.overflow = true; - } else { - var description = ""; - if (type !== "function") - description = this._abbreviateString(/** @type {string} */ (injectedScript._describe(value)), maxLength, subtype === "regexp"); - property.value = description; - } - this._appendPropertyPreview(preview, property, propertiesThreshold); - } - }, - - /** - * @param {!RuntimeAgent.ObjectPreview} preview - * @param {!Object} property - * @param {!Object} propertiesThreshold - */ - _appendPropertyPreview: function(preview, property, propertiesThreshold) - { - if (toString(property.name >>> 0) === property.name) - propertiesThreshold.indexes--; - else - propertiesThreshold.properties--; - if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) { - preview.overflow = true; - } else { - push(preview.properties, property); - } - }, - - /** - * @param {?Array<*>} entries - * @param {!RuntimeAgent.ObjectPreview} preview - * @param {boolean=} skipEntriesPreview - */ - _appendEntriesPreview: function(entries, preview, skipEntriesPreview) - { - if (!entries) - return; - if (skipEntriesPreview) { - if (entries.length) - preview.overflow = true; - return; - } - preview.entries = []; - var entriesThreshold = 5; - for (var i = 0; i < entries.length; ++i) { - if (preview.entries.length >= entriesThreshold) { - preview.overflow = true; - break; - } - var entry = nullifyObjectProto(entries[i]); - var previewEntry = { - value: generateValuePreview(entry.value), - __proto__: null - }; - if ("key" in entry) - previewEntry.key = generateValuePreview(entry.key); - push(preview.entries, previewEntry); - } - - /** - * @param {*} value - * @return {!RuntimeAgent.ObjectPreview} - */ - function generateValuePreview(value) - { - var remoteObject = new InjectedScript.RemoteObject(value, undefined, true, undefined, true, undefined, undefined, true); - var valuePreview = remoteObject.preview || remoteObject._createEmptyPreview(); - return valuePreview; - } - }, - - /** - * @param {string} string - * @param {number} maxLength - * @param {boolean=} middle - * @return {string} - */ - _abbreviateString: function(string, maxLength, middle) - { - if (string.length <= maxLength) - return string; - if (middle) { - var leftHalf = maxLength >> 1; - var rightHalf = maxLength - leftHalf - 1; - return string.substr(0, leftHalf) + "\u2026" + string.substr(string.length - rightHalf, rightHalf); - } - return string.substr(0, maxLength) + "\u2026"; - }, - - __proto__: null -} - -return injectedScript; -}) diff --git a/deps/v8_inspector/src/inspector/injected-script.cc b/deps/v8_inspector/src/inspector/injected-script.cc deleted file mode 100644 index d379a50c7378bf..00000000000000 --- a/deps/v8_inspector/src/inspector/injected-script.cc +++ /dev/null @@ -1,575 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "src/inspector/injected-script.h" - -#include "src/inspector/injected-script-native.h" -#include "src/inspector/injected-script-source.h" -#include "src/inspector/inspected-context.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/remote-object-id.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console.h" -#include "src/inspector/v8-function-call.h" -#include "src/inspector/v8-injected-script-host.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" -#include "src/inspector/v8-value-copier.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -using protocol::Array; -using protocol::Runtime::PropertyDescriptor; -using protocol::Runtime::InternalPropertyDescriptor; -using protocol::Runtime::RemoteObject; -using protocol::Maybe; - -static bool hasInternalError(ErrorString* errorString, bool hasError) { - if (hasError) *errorString = "Internal error"; - return hasError; -} - -std::unique_ptr InjectedScript::create( - InspectedContext* inspectedContext) { - v8::Isolate* isolate = inspectedContext->isolate(); - v8::HandleScope handles(isolate); - v8::Local context = inspectedContext->context(); - v8::Context::Scope scope(context); - - std::unique_ptr injectedScriptNative( - new InjectedScriptNative(isolate)); - v8::Local scriptHostWrapper = - V8InjectedScriptHost::create(context, inspectedContext->inspector()); - injectedScriptNative->setOnInjectedScriptHost(scriptHostWrapper); - - // Inject javascript into the context. The compiled script is supposed to - // evaluate into - // a single anonymous function(it's anonymous to avoid cluttering the global - // object with - // inspector's stuff) the function is called a few lines below with - // InjectedScriptHost wrapper, - // injected script id and explicit reference to the inspected global object. - // The function is expected - // to create and configure InjectedScript instance that is going to be used by - // the inspector. - String16 injectedScriptSource( - reinterpret_cast(InjectedScriptSource_js), - sizeof(InjectedScriptSource_js)); - v8::Local value; - if (!inspectedContext->inspector() - ->compileAndRunInternalScript( - context, toV8String(isolate, injectedScriptSource)) - .ToLocal(&value)) - return nullptr; - DCHECK(value->IsFunction()); - v8::Local function = v8::Local::Cast(value); - v8::Local windowGlobal = context->Global(); - v8::Local info[] = { - scriptHostWrapper, windowGlobal, - v8::Number::New(isolate, inspectedContext->contextId())}; - v8::MicrotasksScope microtasksScope(isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local injectedScriptValue; - if (!function->Call(context, windowGlobal, arraysize(info), info) - .ToLocal(&injectedScriptValue)) - return nullptr; - if (!injectedScriptValue->IsObject()) return nullptr; - return wrapUnique(new InjectedScript(inspectedContext, - injectedScriptValue.As(), - std::move(injectedScriptNative))); -} - -InjectedScript::InjectedScript( - InspectedContext* context, v8::Local object, - std::unique_ptr injectedScriptNative) - : m_context(context), - m_value(context->isolate(), object), - m_native(std::move(injectedScriptNative)) {} - -InjectedScript::~InjectedScript() {} - -void InjectedScript::getProperties( - ErrorString* errorString, v8::Local object, - const String16& groupName, bool ownProperties, bool accessorPropertiesOnly, - bool generatePreview, - std::unique_ptr>* properties, - Maybe* exceptionDetails) { - v8::HandleScope handles(m_context->isolate()); - v8::Local context = m_context->context(); - V8FunctionCall function(m_context->inspector(), m_context->context(), - v8Value(), "getProperties"); - function.appendArgument(object); - function.appendArgument(groupName); - function.appendArgument(ownProperties); - function.appendArgument(accessorPropertiesOnly); - function.appendArgument(generatePreview); - - v8::TryCatch tryCatch(m_context->isolate()); - v8::Local resultValue = function.callWithoutExceptionHandling(); - if (tryCatch.HasCaught()) { - *exceptionDetails = createExceptionDetails(errorString, tryCatch, groupName, - generatePreview); - // FIXME: make properties optional - *properties = Array::create(); - return; - } - if (hasInternalError(errorString, resultValue.IsEmpty())) return; - std::unique_ptr protocolValue = - toProtocolValue(errorString, context, resultValue); - if (!protocolValue) return; - protocol::ErrorSupport errors(errorString); - std::unique_ptr> result = - Array::parse(protocolValue.get(), &errors); - if (!hasInternalError(errorString, errors.hasErrors())) - *properties = std::move(result); -} - -void InjectedScript::releaseObject(const String16& objectId) { - std::unique_ptr parsedObjectId = - protocol::parseJSON(objectId); - if (!parsedObjectId) return; - protocol::DictionaryValue* object = - protocol::DictionaryValue::cast(parsedObjectId.get()); - if (!object) return; - int boundId = 0; - if (!object->getInteger("id", &boundId)) return; - m_native->unbind(boundId); -} - -std::unique_ptr InjectedScript::wrapObject( - ErrorString* errorString, v8::Local value, - const String16& groupName, bool forceValueType, - bool generatePreview) const { - v8::HandleScope handles(m_context->isolate()); - v8::Local wrappedObject; - v8::Local context = m_context->context(); - if (!wrapValue(errorString, value, groupName, forceValueType, generatePreview) - .ToLocal(&wrappedObject)) - return nullptr; - protocol::ErrorSupport errors; - std::unique_ptr protocolValue = - toProtocolValue(errorString, context, wrappedObject); - if (!protocolValue) return nullptr; - std::unique_ptr remoteObject = - protocol::Runtime::RemoteObject::parse(protocolValue.get(), &errors); - if (!remoteObject) *errorString = errors.errors(); - return remoteObject; -} - -bool InjectedScript::wrapObjectProperty(ErrorString* errorString, - v8::Local object, - v8::Local key, - const String16& groupName, - bool forceValueType, - bool generatePreview) const { - v8::Local property; - v8::Local context = m_context->context(); - if (hasInternalError(errorString, - !object->Get(context, key).ToLocal(&property))) - return false; - v8::Local wrappedProperty; - if (!wrapValue(errorString, property, groupName, forceValueType, - generatePreview) - .ToLocal(&wrappedProperty)) - return false; - v8::Maybe success = - createDataProperty(context, object, key, wrappedProperty); - if (hasInternalError(errorString, success.IsNothing() || !success.FromJust())) - return false; - return true; -} - -bool InjectedScript::wrapPropertyInArray(ErrorString* errorString, - v8::Local array, - v8::Local property, - const String16& groupName, - bool forceValueType, - bool generatePreview) const { - V8FunctionCall function(m_context->inspector(), m_context->context(), - v8Value(), "wrapPropertyInArray"); - function.appendArgument(array); - function.appendArgument(property); - function.appendArgument(groupName); - function.appendArgument(forceValueType); - function.appendArgument(generatePreview); - bool hadException = false; - function.call(hadException); - return !hasInternalError(errorString, hadException); -} - -bool InjectedScript::wrapObjectsInArray(ErrorString* errorString, - v8::Local array, - const String16& groupName, - bool forceValueType, - bool generatePreview) const { - V8FunctionCall function(m_context->inspector(), m_context->context(), - v8Value(), "wrapObjectsInArray"); - function.appendArgument(array); - function.appendArgument(groupName); - function.appendArgument(forceValueType); - function.appendArgument(generatePreview); - bool hadException = false; - function.call(hadException); - return !hasInternalError(errorString, hadException); -} - -v8::MaybeLocal InjectedScript::wrapValue( - ErrorString* errorString, v8::Local value, - const String16& groupName, bool forceValueType, - bool generatePreview) const { - V8FunctionCall function(m_context->inspector(), m_context->context(), - v8Value(), "wrapObject"); - function.appendArgument(value); - function.appendArgument(groupName); - function.appendArgument(forceValueType); - function.appendArgument(generatePreview); - bool hadException = false; - v8::Local r = function.call(hadException); - if (hasInternalError(errorString, hadException || r.IsEmpty())) - return v8::MaybeLocal(); - return r; -} - -std::unique_ptr InjectedScript::wrapTable( - v8::Local table, v8::Local columns) const { - v8::HandleScope handles(m_context->isolate()); - v8::Local context = m_context->context(); - V8FunctionCall function(m_context->inspector(), context, v8Value(), - "wrapTable"); - function.appendArgument(table); - if (columns.IsEmpty()) - function.appendArgument(false); - else - function.appendArgument(columns); - bool hadException = false; - v8::Local r = function.call(hadException); - if (hadException || r.IsEmpty()) return nullptr; - protocol::ErrorString errorString; - std::unique_ptr protocolValue = - toProtocolValue(&errorString, context, r); - if (!protocolValue) return nullptr; - protocol::ErrorSupport errors; - return protocol::Runtime::RemoteObject::parse(protocolValue.get(), &errors); -} - -bool InjectedScript::findObject(ErrorString* errorString, - const RemoteObjectId& objectId, - v8::Local* outObject) const { - *outObject = m_native->objectForId(objectId.id()); - if (outObject->IsEmpty()) - *errorString = "Could not find object with given id"; - return !outObject->IsEmpty(); -} - -String16 InjectedScript::objectGroupName(const RemoteObjectId& objectId) const { - return m_native->groupName(objectId.id()); -} - -void InjectedScript::releaseObjectGroup(const String16& objectGroup) { - m_native->releaseObjectGroup(objectGroup); - if (objectGroup == "console") m_lastEvaluationResult.Reset(); -} - -void InjectedScript::setCustomObjectFormatterEnabled(bool enabled) { - v8::HandleScope handles(m_context->isolate()); - V8FunctionCall function(m_context->inspector(), m_context->context(), - v8Value(), "setCustomObjectFormatterEnabled"); - function.appendArgument(enabled); - bool hadException = false; - function.call(hadException); - DCHECK(!hadException); -} - -v8::Local InjectedScript::v8Value() const { - return m_value.Get(m_context->isolate()); -} - -v8::Local InjectedScript::lastEvaluationResult() const { - if (m_lastEvaluationResult.IsEmpty()) - return v8::Undefined(m_context->isolate()); - return m_lastEvaluationResult.Get(m_context->isolate()); -} - -v8::MaybeLocal InjectedScript::resolveCallArgument( - ErrorString* errorString, protocol::Runtime::CallArgument* callArgument) { - if (callArgument->hasObjectId()) { - std::unique_ptr remoteObjectId = - RemoteObjectId::parse(errorString, callArgument->getObjectId("")); - if (!remoteObjectId) return v8::MaybeLocal(); - if (remoteObjectId->contextId() != m_context->contextId()) { - *errorString = - "Argument should belong to the same JavaScript world as target " - "object"; - return v8::MaybeLocal(); - } - v8::Local object; - if (!findObject(errorString, *remoteObjectId, &object)) - return v8::MaybeLocal(); - return object; - } - if (callArgument->hasValue() || callArgument->hasUnserializableValue()) { - String16 value = - callArgument->hasValue() - ? callArgument->getValue(nullptr)->toJSONString() - : "Number(\"" + callArgument->getUnserializableValue("") + "\")"; - v8::Local object; - if (!m_context->inspector() - ->compileAndRunInternalScript( - m_context->context(), toV8String(m_context->isolate(), value)) - .ToLocal(&object)) { - *errorString = "Couldn't parse value object in call argument"; - return v8::MaybeLocal(); - } - return object; - } - return v8::Undefined(m_context->isolate()); -} - -std::unique_ptr -InjectedScript::createExceptionDetails(ErrorString* errorString, - const v8::TryCatch& tryCatch, - const String16& objectGroup, - bool generatePreview) { - if (!tryCatch.HasCaught()) return nullptr; - v8::Local message = tryCatch.Message(); - v8::Local exception = tryCatch.Exception(); - String16 messageText = - message.IsEmpty() ? String16() : toProtocolString(message->Get()); - std::unique_ptr exceptionDetails = - protocol::Runtime::ExceptionDetails::create() - .setExceptionId(m_context->inspector()->nextExceptionId()) - .setText(exception.IsEmpty() ? messageText : String16("Uncaught")) - .setLineNumber( - message.IsEmpty() - ? 0 - : message->GetLineNumber(m_context->context()).FromMaybe(1) - - 1) - .setColumnNumber( - message.IsEmpty() - ? 0 - : message->GetStartColumn(m_context->context()).FromMaybe(0)) - .build(); - if (!message.IsEmpty()) { - exceptionDetails->setScriptId(String16::fromInteger( - static_cast(message->GetScriptOrigin().ScriptID()->Value()))); - v8::Local stackTrace = message->GetStackTrace(); - if (!stackTrace.IsEmpty() && stackTrace->GetFrameCount() > 0) - exceptionDetails->setStackTrace(m_context->inspector() - ->debugger() - ->createStackTrace(stackTrace) - ->buildInspectorObjectImpl()); - } - if (!exception.IsEmpty()) { - std::unique_ptr wrapped = wrapObject( - errorString, exception, objectGroup, false /* forceValueType */, - generatePreview && !exception->IsNativeError()); - if (!wrapped) return nullptr; - exceptionDetails->setException(std::move(wrapped)); - } - return exceptionDetails; -} - -void InjectedScript::wrapEvaluateResult( - ErrorString* errorString, v8::MaybeLocal maybeResultValue, - const v8::TryCatch& tryCatch, const String16& objectGroup, - bool returnByValue, bool generatePreview, - std::unique_ptr* result, - Maybe* exceptionDetails) { - v8::Local resultValue; - if (!tryCatch.HasCaught()) { - if (hasInternalError(errorString, !maybeResultValue.ToLocal(&resultValue))) - return; - std::unique_ptr remoteObject = wrapObject( - errorString, resultValue, objectGroup, returnByValue, generatePreview); - if (!remoteObject) return; - if (objectGroup == "console") - m_lastEvaluationResult.Reset(m_context->isolate(), resultValue); - *result = std::move(remoteObject); - } else { - v8::Local exception = tryCatch.Exception(); - std::unique_ptr remoteObject = - wrapObject(errorString, exception, objectGroup, false, - generatePreview && !exception->IsNativeError()); - if (!remoteObject) return; - // We send exception in result for compatibility reasons, even though it's - // accessible through exceptionDetails.exception. - *result = std::move(remoteObject); - *exceptionDetails = createExceptionDetails(errorString, tryCatch, - objectGroup, generatePreview); - } -} - -v8::Local InjectedScript::commandLineAPI() { - if (m_commandLineAPI.IsEmpty()) - m_commandLineAPI.Reset(m_context->isolate(), - V8Console::createCommandLineAPI(m_context)); - return m_commandLineAPI.Get(m_context->isolate()); -} - -InjectedScript::Scope::Scope(ErrorString* errorString, - V8InspectorImpl* inspector, int contextGroupId) - : m_errorString(errorString), - m_inspector(inspector), - m_contextGroupId(contextGroupId), - m_injectedScript(nullptr), - m_handleScope(inspector->isolate()), - m_tryCatch(inspector->isolate()), - m_ignoreExceptionsAndMuteConsole(false), - m_previousPauseOnExceptionsState(V8Debugger::DontPauseOnExceptions), - m_userGesture(false) {} - -bool InjectedScript::Scope::initialize() { - cleanup(); - // TODO(dgozman): what if we reattach to the same context group during - // evaluate? Introduce a session id? - V8InspectorSessionImpl* session = - m_inspector->sessionForContextGroup(m_contextGroupId); - if (!session) { - *m_errorString = "Internal error"; - return false; - } - findInjectedScript(session); - if (!m_injectedScript) return false; - m_context = m_injectedScript->context()->context(); - m_context->Enter(); - return true; -} - -bool InjectedScript::Scope::installCommandLineAPI() { - DCHECK(m_injectedScript && !m_context.IsEmpty() && - !m_commandLineAPIScope.get()); - m_commandLineAPIScope.reset(new V8Console::CommandLineAPIScope( - m_context, m_injectedScript->commandLineAPI(), m_context->Global())); - return true; -} - -void InjectedScript::Scope::ignoreExceptionsAndMuteConsole() { - DCHECK(!m_ignoreExceptionsAndMuteConsole); - m_ignoreExceptionsAndMuteConsole = true; - m_inspector->client()->muteMetrics(m_contextGroupId); - m_inspector->muteExceptions(m_contextGroupId); - m_previousPauseOnExceptionsState = - setPauseOnExceptionsState(V8Debugger::DontPauseOnExceptions); -} - -V8Debugger::PauseOnExceptionsState -InjectedScript::Scope::setPauseOnExceptionsState( - V8Debugger::PauseOnExceptionsState newState) { - if (!m_inspector->debugger()->enabled()) return newState; - V8Debugger::PauseOnExceptionsState presentState = - m_inspector->debugger()->getPauseOnExceptionsState(); - if (presentState != newState) - m_inspector->debugger()->setPauseOnExceptionsState(newState); - return presentState; -} - -void InjectedScript::Scope::pretendUserGesture() { - DCHECK(!m_userGesture); - m_userGesture = true; - m_inspector->client()->beginUserGesture(); -} - -void InjectedScript::Scope::cleanup() { - m_commandLineAPIScope.reset(); - if (!m_context.IsEmpty()) { - m_context->Exit(); - m_context.Clear(); - } -} - -InjectedScript::Scope::~Scope() { - if (m_ignoreExceptionsAndMuteConsole) { - setPauseOnExceptionsState(m_previousPauseOnExceptionsState); - m_inspector->client()->unmuteMetrics(m_contextGroupId); - m_inspector->unmuteExceptions(m_contextGroupId); - } - if (m_userGesture) m_inspector->client()->endUserGesture(); - cleanup(); -} - -InjectedScript::ContextScope::ContextScope(ErrorString* errorString, - V8InspectorImpl* inspector, - int contextGroupId, - int executionContextId) - : InjectedScript::Scope(errorString, inspector, contextGroupId), - m_executionContextId(executionContextId) {} - -InjectedScript::ContextScope::~ContextScope() {} - -void InjectedScript::ContextScope::findInjectedScript( - V8InspectorSessionImpl* session) { - m_injectedScript = - session->findInjectedScript(m_errorString, m_executionContextId); -} - -InjectedScript::ObjectScope::ObjectScope(ErrorString* errorString, - V8InspectorImpl* inspector, - int contextGroupId, - const String16& remoteObjectId) - : InjectedScript::Scope(errorString, inspector, contextGroupId), - m_remoteObjectId(remoteObjectId) {} - -InjectedScript::ObjectScope::~ObjectScope() {} - -void InjectedScript::ObjectScope::findInjectedScript( - V8InspectorSessionImpl* session) { - std::unique_ptr remoteId = - RemoteObjectId::parse(m_errorString, m_remoteObjectId); - if (!remoteId) return; - InjectedScript* injectedScript = - session->findInjectedScript(m_errorString, remoteId.get()); - if (!injectedScript) return; - m_objectGroupName = injectedScript->objectGroupName(*remoteId); - if (!injectedScript->findObject(m_errorString, *remoteId, &m_object)) return; - m_injectedScript = injectedScript; -} - -InjectedScript::CallFrameScope::CallFrameScope(ErrorString* errorString, - V8InspectorImpl* inspector, - int contextGroupId, - const String16& remoteObjectId) - : InjectedScript::Scope(errorString, inspector, contextGroupId), - m_remoteCallFrameId(remoteObjectId) {} - -InjectedScript::CallFrameScope::~CallFrameScope() {} - -void InjectedScript::CallFrameScope::findInjectedScript( - V8InspectorSessionImpl* session) { - std::unique_ptr remoteId = - RemoteCallFrameId::parse(m_errorString, m_remoteCallFrameId); - if (!remoteId) return; - m_frameOrdinal = static_cast(remoteId->frameOrdinal()); - m_injectedScript = session->findInjectedScript(m_errorString, remoteId.get()); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/injected-script.h b/deps/v8_inspector/src/inspector/injected-script.h deleted file mode 100644 index 9b324c948d4f59..00000000000000 --- a/deps/v8_inspector/src/inspector/injected-script.h +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (C) 2012 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_INJECTEDSCRIPT_H_ -#define V8_INSPECTOR_INJECTEDSCRIPT_H_ - -#include "src/base/macros.h" -#include "src/inspector/injected-script-native.h" -#include "src/inspector/inspected-context.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Runtime.h" -#include "src/inspector/v8-console.h" -#include "src/inspector/v8-debugger.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class RemoteObjectId; -class V8FunctionCall; -class V8InspectorImpl; -class V8InspectorSessionImpl; - -using protocol::ErrorString; -using protocol::Maybe; - -class InjectedScript final { - public: - static std::unique_ptr create(InspectedContext*); - ~InjectedScript(); - - InspectedContext* context() const { return m_context; } - - void getProperties( - ErrorString*, v8::Local, const String16& groupName, - bool ownProperties, bool accessorPropertiesOnly, bool generatePreview, - std::unique_ptr>* - result, - Maybe*); - void releaseObject(const String16& objectId); - - std::unique_ptr wrapObject( - ErrorString*, v8::Local, const String16& groupName, - bool forceValueType = false, bool generatePreview = false) const; - bool wrapObjectProperty(ErrorString*, v8::Local, - v8::Local key, const String16& groupName, - bool forceValueType = false, - bool generatePreview = false) const; - bool wrapPropertyInArray(ErrorString*, v8::Local, - v8::Local property, - const String16& groupName, - bool forceValueType = false, - bool generatePreview = false) const; - bool wrapObjectsInArray(ErrorString*, v8::Local, - const String16& groupName, - bool forceValueType = false, - bool generatePreview = false) const; - std::unique_ptr wrapTable( - v8::Local table, v8::Local columns) const; - - bool findObject(ErrorString*, const RemoteObjectId&, - v8::Local*) const; - String16 objectGroupName(const RemoteObjectId&) const; - void releaseObjectGroup(const String16&); - void setCustomObjectFormatterEnabled(bool); - v8::MaybeLocal resolveCallArgument( - ErrorString*, protocol::Runtime::CallArgument*); - - std::unique_ptr createExceptionDetails( - ErrorString*, const v8::TryCatch&, const String16& groupName, - bool generatePreview); - void wrapEvaluateResult( - ErrorString*, v8::MaybeLocal maybeResultValue, - const v8::TryCatch&, const String16& objectGroup, bool returnByValue, - bool generatePreview, - std::unique_ptr* result, - Maybe*); - v8::Local lastEvaluationResult() const; - - class Scope { - public: - bool initialize(); - bool installCommandLineAPI(); - void ignoreExceptionsAndMuteConsole(); - void pretendUserGesture(); - v8::Local context() const { return m_context; } - InjectedScript* injectedScript() const { return m_injectedScript; } - const v8::TryCatch& tryCatch() const { return m_tryCatch; } - - protected: - Scope(ErrorString*, V8InspectorImpl*, int contextGroupId); - virtual ~Scope(); - virtual void findInjectedScript(V8InspectorSessionImpl*) = 0; - - ErrorString* m_errorString; - V8InspectorImpl* m_inspector; - int m_contextGroupId; - InjectedScript* m_injectedScript; - - private: - void cleanup(); - V8Debugger::PauseOnExceptionsState setPauseOnExceptionsState( - V8Debugger::PauseOnExceptionsState); - - v8::HandleScope m_handleScope; - v8::TryCatch m_tryCatch; - v8::Local m_context; - std::unique_ptr m_commandLineAPIScope; - bool m_ignoreExceptionsAndMuteConsole; - V8Debugger::PauseOnExceptionsState m_previousPauseOnExceptionsState; - bool m_userGesture; - }; - - class ContextScope : public Scope { - public: - ContextScope(ErrorString*, V8InspectorImpl*, int contextGroupId, - int executionContextId); - ~ContextScope(); - - private: - void findInjectedScript(V8InspectorSessionImpl*) override; - int m_executionContextId; - - DISALLOW_COPY_AND_ASSIGN(ContextScope); - }; - - class ObjectScope : public Scope { - public: - ObjectScope(ErrorString*, V8InspectorImpl*, int contextGroupId, - const String16& remoteObjectId); - ~ObjectScope(); - const String16& objectGroupName() const { return m_objectGroupName; } - v8::Local object() const { return m_object; } - - private: - void findInjectedScript(V8InspectorSessionImpl*) override; - String16 m_remoteObjectId; - String16 m_objectGroupName; - v8::Local m_object; - - DISALLOW_COPY_AND_ASSIGN(ObjectScope); - }; - - class CallFrameScope : public Scope { - public: - CallFrameScope(ErrorString*, V8InspectorImpl*, int contextGroupId, - const String16& remoteCallFrameId); - ~CallFrameScope(); - size_t frameOrdinal() const { return m_frameOrdinal; } - - private: - void findInjectedScript(V8InspectorSessionImpl*) override; - String16 m_remoteCallFrameId; - size_t m_frameOrdinal; - - DISALLOW_COPY_AND_ASSIGN(CallFrameScope); - }; - - private: - InjectedScript(InspectedContext*, v8::Local, - std::unique_ptr); - v8::Local v8Value() const; - v8::MaybeLocal wrapValue(ErrorString*, v8::Local, - const String16& groupName, - bool forceValueType, - bool generatePreview) const; - v8::Local commandLineAPI(); - - InspectedContext* m_context; - v8::Global m_value; - v8::Global m_lastEvaluationResult; - std::unique_ptr m_native; - v8::Global m_commandLineAPI; - - DISALLOW_COPY_AND_ASSIGN(InjectedScript); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_INJECTEDSCRIPT_H_ diff --git a/deps/v8_inspector/src/inspector/injected_script_externs.js b/deps/v8_inspector/src/inspector/injected_script_externs.js deleted file mode 100644 index b6339c6eb08667..00000000000000 --- a/deps/v8_inspector/src/inspector/injected_script_externs.js +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2015 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. - -/** @interface */ -function InjectedScriptHostClass() -{ -} - -/** - * @param {*} obj - * @return {string} - */ -InjectedScriptHostClass.prototype.internalConstructorName = function(obj) {} - -/** - * @param {*} obj - * @param {function()|undefined} func - * @return {boolean} - */ -InjectedScriptHostClass.prototype.formatAccessorsAsProperties = function(obj, func) {} - -/** - * @param {*} obj - * @return {string} - */ -InjectedScriptHostClass.prototype.subtype = function(obj) {} - -/** - * @param {*} obj - * @return {boolean} - */ -InjectedScriptHostClass.prototype.isTypedArray = function(obj) {} - -/** - * @param {*} obj - * @return {!Array.<*>} - */ -InjectedScriptHostClass.prototype.getInternalProperties = function(obj) {} - -/** - * @param {!Object} object - * @param {string} propertyName - * @return {boolean} - */ -InjectedScriptHostClass.prototype.objectHasOwnProperty = function(object, propertyName) {} - -/** - * @param {*} value - * @param {string} groupName - * @return {number} - */ -InjectedScriptHostClass.prototype.bind = function(value, groupName) {} - -/** - * @param {!Object} object - * @return {!Object} - */ -InjectedScriptHostClass.prototype.proxyTargetValue = function(object) {} - -/** @type {!InjectedScriptHostClass} */ -var InjectedScriptHost; -/** @type {!Window} */ -var inspectedGlobalObject; -/** @type {number} */ -var injectedScriptId; diff --git a/deps/v8_inspector/src/inspector/inspected-context.cc b/deps/v8_inspector/src/inspector/inspected-context.cc deleted file mode 100644 index 3fdb0846f3c053..00000000000000 --- a/deps/v8_inspector/src/inspector/inspected-context.cc +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/inspected-context.h" - -#include "src/inspector/injected-script.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-value-copier.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -void InspectedContext::weakCallback( - const v8::WeakCallbackInfo& data) { - InspectedContext* context = data.GetParameter(); - if (!context->m_context.IsEmpty()) { - context->m_context.Reset(); - data.SetSecondPassCallback(&InspectedContext::weakCallback); - } else { - context->m_inspector->discardInspectedContext(context->m_contextGroupId, - context->m_contextId); - } -} - -void InspectedContext::consoleWeakCallback( - const v8::WeakCallbackInfo& data) { - data.GetParameter()->m_console.Reset(); -} - -InspectedContext::InspectedContext(V8InspectorImpl* inspector, - const V8ContextInfo& info, int contextId) - : m_inspector(inspector), - m_context(info.context->GetIsolate(), info.context), - m_contextId(contextId), - m_contextGroupId(info.contextGroupId), - m_origin(toString16(info.origin)), - m_humanReadableName(toString16(info.humanReadableName)), - m_auxData(toString16(info.auxData)), - m_reported(false) { - m_context.SetWeak(this, &InspectedContext::weakCallback, - v8::WeakCallbackType::kParameter); - - v8::Isolate* isolate = m_inspector->isolate(); - v8::Local global = info.context->Global(); - v8::Local console = - V8Console::createConsole(this, info.hasMemoryOnConsole); - if (!global - ->Set(info.context, toV8StringInternalized(isolate, "console"), - console) - .FromMaybe(false)) - return; - m_console.Reset(isolate, console); - m_console.SetWeak(this, &InspectedContext::consoleWeakCallback, - v8::WeakCallbackType::kParameter); -} - -InspectedContext::~InspectedContext() { - if (!m_context.IsEmpty() && !m_console.IsEmpty()) { - v8::HandleScope scope(isolate()); - V8Console::clearInspectedContextIfNeeded(context(), - m_console.Get(isolate())); - } -} - -v8::Local InspectedContext::context() const { - return m_context.Get(isolate()); -} - -v8::Isolate* InspectedContext::isolate() const { - return m_inspector->isolate(); -} - -void InspectedContext::createInjectedScript() { - DCHECK(!m_injectedScript); - m_injectedScript = InjectedScript::create(this); -} - -void InspectedContext::discardInjectedScript() { m_injectedScript.reset(); } - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/inspected-context.h b/deps/v8_inspector/src/inspector/inspected-context.h deleted file mode 100644 index 443f4a1425734f..00000000000000 --- a/deps/v8_inspector/src/inspector/inspected-context.h +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_INSPECTEDCONTEXT_H_ -#define V8_INSPECTOR_INSPECTEDCONTEXT_H_ - -#include "src/base/macros.h" -#include "src/inspector/string-16.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class InjectedScript; -class InjectedScriptHost; -class V8ContextInfo; -class V8InspectorImpl; - -class InspectedContext { - public: - ~InspectedContext(); - - v8::Local context() const; - int contextId() const { return m_contextId; } - int contextGroupId() const { return m_contextGroupId; } - String16 origin() const { return m_origin; } - String16 humanReadableName() const { return m_humanReadableName; } - String16 auxData() const { return m_auxData; } - - bool isReported() const { return m_reported; } - void setReported(bool reported) { m_reported = reported; } - - v8::Isolate* isolate() const; - V8InspectorImpl* inspector() const { return m_inspector; } - - InjectedScript* getInjectedScript() { return m_injectedScript.get(); } - void createInjectedScript(); - void discardInjectedScript(); - - private: - friend class V8InspectorImpl; - InspectedContext(V8InspectorImpl*, const V8ContextInfo&, int contextId); - static void weakCallback(const v8::WeakCallbackInfo&); - static void consoleWeakCallback( - const v8::WeakCallbackInfo&); - - V8InspectorImpl* m_inspector; - v8::Global m_context; - int m_contextId; - int m_contextGroupId; - const String16 m_origin; - const String16 m_humanReadableName; - const String16 m_auxData; - bool m_reported; - std::unique_ptr m_injectedScript; - v8::Global m_console; - - DISALLOW_COPY_AND_ASSIGN(InspectedContext); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_INSPECTEDCONTEXT_H_ diff --git a/deps/v8_inspector/src/inspector/inspector.gyp b/deps/v8_inspector/src/inspector/inspector.gyp deleted file mode 100644 index 231814cb31f48c..00000000000000 --- a/deps/v8_inspector/src/inspector/inspector.gyp +++ /dev/null @@ -1,131 +0,0 @@ -# Copyright 2016 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. - -{ - 'variables': { - 'protocol_path': '../../third_party/WebKit/Source/platform/inspector_protocol', - }, - 'includes': [ - '../../../v8/gypfiles/toolchain.gypi', - '../../../v8/gypfiles/features.gypi', - 'inspector.gypi', - '../../third_party/WebKit/Source/platform/inspector_protocol/inspector_protocol.gypi', - ], - 'targets': [ - { 'target_name': 'inspector_injected_script', - 'type': 'none', - 'actions': [ - { - 'action_name': 'convert_js_to_cpp_char_array', - 'inputs': [ - 'build/xxd.py', - '<(inspector_injected_script_source)', - ], - 'outputs': [ - '<(inspector_generated_injected_script)', - ], - 'action': [ - 'python', - 'build/xxd.py', - 'InjectedScriptSource_js', - 'injected-script-source.js', - '<@(_outputs)' - ], - }, - ], - # Since this target generates header files, it needs to be a hard dependency. - 'hard_dependency': 1, - }, - { 'target_name': 'inspector_debugger_script', - 'type': 'none', - 'actions': [ - { - 'action_name': 'convert_js_to_cpp_char_array', - 'inputs': [ - 'build/xxd.py', - '<(inspector_debugger_script_source)', - ], - 'outputs': [ - '<(inspector_generated_debugger_script)', - ], - 'action': [ - 'python', - 'build/xxd.py', - 'DebuggerScript_js', - 'debugger-script.js', - '<@(_outputs)' - ], - }, - ], - # Since this target generates header files, it needs to be a hard dependency. - 'hard_dependency': 1, - }, - { 'target_name': 'protocol_compatibility', - 'type': 'none', - 'actions': [ - { - 'action_name': 'protocol_compatibility', - 'inputs': [ - 'js_protocol.json', - ], - 'outputs': [ - '<@(SHARED_INTERMEDIATE_DIR)/src/js_protocol.stamp', - ], - 'action': [ - 'python', - '<(protocol_path)/CheckProtocolCompatibility.py', - '--stamp', '<@(_outputs)', - 'js_protocol.json', - ], - 'message': 'Generating inspector protocol sources from protocol json definition', - }, - ] - }, - { 'target_name': 'protocol_generated_sources', - 'type': 'none', - 'dependencies': [ 'protocol_compatibility' ], - 'actions': [ - { - 'action_name': 'protocol_generated_sources', - 'inputs': [ - 'js_protocol.json', - 'inspector_protocol_config.json', - '<@(inspector_protocol_files)', - ], - 'outputs': [ - '<@(inspector_generated_sources)', - ], - 'action': [ - 'python', - '<(protocol_path)/CodeGenerator.py', - '--jinja_dir', '../../third_party', - '--output_base', '<(SHARED_INTERMEDIATE_DIR)/src/inspector', - '--config', 'inspector_protocol_config.json', - ], - 'message': 'Generating inspector protocol sources from protocol json', - }, - ] - }, - { - 'target_name': 'standalone_inspector', - 'type': 'static_library', - 'include_dirs': [ - '<(SHARED_INTERMEDIATE_DIR)', - '<(SHARED_INTERMEDIATE_DIR)/include', - '../../include', - '../..', - '../../../v8' - ], - 'sources': [ - '<@(inspector_all_sources)' - ], - 'dependencies': [ - 'protocol_generated_sources', - 'inspector_injected_script', - 'inspector_debugger_script', - '../../../v8/src/v8.gyp:v8_libplatform', - ], - }, - ], -} diff --git a/deps/v8_inspector/src/inspector/inspector.gypi b/deps/v8_inspector/src/inspector/inspector.gypi deleted file mode 100644 index 031735d7c6a610..00000000000000 --- a/deps/v8_inspector/src/inspector/inspector.gypi +++ /dev/null @@ -1,95 +0,0 @@ -# Copyright 2016 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. - -{ - 'variables': { - 'inspector_generated_sources': [ - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Forward.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Protocol.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Protocol.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Console.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Console.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Debugger.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Debugger.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/HeapProfiler.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/HeapProfiler.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Profiler.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Profiler.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Runtime.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Runtime.h', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Schema.cpp', - '<(SHARED_INTERMEDIATE_DIR)/src/inspector/protocol/Schema.h', - '<(SHARED_INTERMEDIATE_DIR)/include/inspector/Debugger.h', - '<(SHARED_INTERMEDIATE_DIR)/include/inspector/Runtime.h', - '<(SHARED_INTERMEDIATE_DIR)/include/inspector/Schema.h', - ], - - 'inspector_injected_script_source': 'injected-script-source.js', - 'inspector_generated_injected_script': '<(SHARED_INTERMEDIATE_DIR)/src/inspector/injected-script-source.h', - 'inspector_debugger_script_source': 'debugger-script.js', - 'inspector_generated_debugger_script': '<(SHARED_INTERMEDIATE_DIR)/src/inspector/debugger-script.h', - - 'inspector_all_sources': [ - '<@(inspector_generated_sources)', - '<(inspector_generated_injected_script)', - '<(inspector_generated_debugger_script)', - '../../include/v8-inspector.h', - '../../include/v8-inspector-protocol.h', - 'injected-script.cc', - 'injected-script.h', - 'injected-script-native.cc', - 'injected-script-native.h', - 'inspected-context.cc', - 'inspected-context.h', - 'java-script-call-frame.cc', - 'java-script-call-frame.h', - 'protocol-platform.h', - 'remote-object-id.cc', - 'remote-object-id.h', - 'script-breakpoint.h', - 'search-util.cc', - 'search-util.h', - 'string-16.cc', - 'string-16.h', - 'string-util.cc', - 'string-util.h', - 'v8-console.cc', - 'v8-console.h', - 'v8-console-agent-impl.cc', - 'v8-console-agent-impl.h', - 'v8-console-message.cc', - 'v8-console-message.h', - 'v8-debugger.cc', - 'v8-debugger.h', - 'v8-debugger-agent-impl.cc', - 'v8-debugger-agent-impl.h', - 'v8-debugger-script.cc', - 'v8-debugger-script.h', - 'v8-function-call.cc', - 'v8-function-call.h', - 'v8-heap-profiler-agent-impl.cc', - 'v8-heap-profiler-agent-impl.h', - 'v8-injected-script-host.cc', - 'v8-injected-script-host.h', - 'v8-inspector-impl.cc', - 'v8-inspector-impl.h', - 'v8-inspector-session-impl.cc', - 'v8-inspector-session-impl.h', - 'v8-internal-value-type.cc', - 'v8-internal-value-type.h', - 'v8-profiler-agent-impl.cc', - 'v8-profiler-agent-impl.h', - 'v8-regex.cc', - 'v8-regex.h', - 'v8-runtime-agent-impl.cc', - 'v8-runtime-agent-impl.h', - 'v8-schema-agent-impl.cc', - 'v8-schema-agent-impl.h', - 'v8-stack-trace-impl.cc', - 'v8-stack-trace-impl.h', - 'v8-value-copier.cc', - 'v8-value-copier.h', - ] - } -} diff --git a/deps/v8_inspector/src/inspector/inspector_protocol_config.json b/deps/v8_inspector/src/inspector/inspector_protocol_config.json deleted file mode 100644 index cb9e6698d16609..00000000000000 --- a/deps/v8_inspector/src/inspector/inspector_protocol_config.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "protocol": { - "path": "js_protocol.json", - "package": "src/inspector/protocol", - "output": "protocol", - "namespace": ["v8_inspector", "protocol"] - }, - - "exported": { - "package": "include/inspector", - "output": "../../include/inspector", - "string_header": "v8-inspector.h", - "string_in": "StringView", - "string_out": "std::unique_ptr", - "to_string_out": "StringBufferImpl::adopt(%s)", - "export_macro": "V8_EXPORT" - }, - - "lib": { - "package": "src/inspector/protocol", - "output": "protocol", - "string_header": "src/inspector/string-util.h", - "platform_header": "src/inspector/protocol-platform.h" - } -} diff --git a/deps/v8_inspector/src/inspector/java-script-call-frame.cc b/deps/v8_inspector/src/inspector/java-script-call-frame.cc deleted file mode 100644 index b70af21f8646e6..00000000000000 --- a/deps/v8_inspector/src/inspector/java-script-call-frame.cc +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright (c) 2010, Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "src/inspector/java-script-call-frame.h" - -#include "src/inspector/string-util.h" - -#include "include/v8-debug.h" - -namespace v8_inspector { - -JavaScriptCallFrame::JavaScriptCallFrame(v8::Local debuggerContext, - v8::Local callFrame) - : m_isolate(debuggerContext->GetIsolate()), - m_debuggerContext(m_isolate, debuggerContext), - m_callFrame(m_isolate, callFrame) {} - -JavaScriptCallFrame::~JavaScriptCallFrame() {} - -int JavaScriptCallFrame::callV8FunctionReturnInt(const char* name) const { - v8::HandleScope handleScope(m_isolate); - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local context = - v8::Local::New(m_isolate, m_debuggerContext); - v8::Local callFrame = - v8::Local::New(m_isolate, m_callFrame); - v8::Local func = v8::Local::Cast( - callFrame->Get(context, toV8StringInternalized(m_isolate, name)) - .ToLocalChecked()); - v8::Local result; - if (!func->Call(context, callFrame, 0, nullptr).ToLocal(&result) || - !result->IsInt32()) - return 0; - return result.As()->Value(); -} - -int JavaScriptCallFrame::sourceID() const { - return callV8FunctionReturnInt("sourceID"); -} - -int JavaScriptCallFrame::line() const { - return callV8FunctionReturnInt("line"); -} - -int JavaScriptCallFrame::column() const { - return callV8FunctionReturnInt("column"); -} - -int JavaScriptCallFrame::contextId() const { - return callV8FunctionReturnInt("contextId"); -} - -bool JavaScriptCallFrame::isAtReturn() const { - v8::HandleScope handleScope(m_isolate); - v8::Local context = - v8::Local::New(m_isolate, m_debuggerContext); - v8::Local callFrame = - v8::Local::New(m_isolate, m_callFrame); - v8::Local result; - if (!callFrame->Get(context, toV8StringInternalized(m_isolate, "isAtReturn")) - .ToLocal(&result) || - !result->IsBoolean()) - return false; - return result.As()->BooleanValue(context).FromMaybe(false); -} - -v8::Local JavaScriptCallFrame::details() const { - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local context = - v8::Local::New(m_isolate, m_debuggerContext); - v8::Local callFrame = - v8::Local::New(m_isolate, m_callFrame); - v8::Local func = v8::Local::Cast( - callFrame->Get(context, toV8StringInternalized(m_isolate, "details")) - .ToLocalChecked()); - return v8::Local::Cast( - func->Call(context, callFrame, 0, nullptr).ToLocalChecked()); -} - -v8::MaybeLocal JavaScriptCallFrame::evaluate( - v8::Local expression) { - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kRunMicrotasks); - v8::Local context = - v8::Local::New(m_isolate, m_debuggerContext); - v8::Local callFrame = - v8::Local::New(m_isolate, m_callFrame); - v8::Local evalFunction = v8::Local::Cast( - callFrame->Get(context, toV8StringInternalized(m_isolate, "evaluate")) - .ToLocalChecked()); - return evalFunction->Call(context, callFrame, 1, &expression); -} - -v8::MaybeLocal JavaScriptCallFrame::restart() { - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local context = - v8::Local::New(m_isolate, m_debuggerContext); - v8::Local callFrame = - v8::Local::New(m_isolate, m_callFrame); - v8::Local restartFunction = v8::Local::Cast( - callFrame->Get(context, toV8StringInternalized(m_isolate, "restart")) - .ToLocalChecked()); - v8::Debug::SetLiveEditEnabled(m_isolate, true); - v8::MaybeLocal result = restartFunction->Call( - m_debuggerContext.Get(m_isolate), callFrame, 0, nullptr); - v8::Debug::SetLiveEditEnabled(m_isolate, false); - return result; -} - -v8::MaybeLocal JavaScriptCallFrame::setVariableValue( - int scopeNumber, v8::Local variableName, - v8::Local newValue) { - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local context = - v8::Local::New(m_isolate, m_debuggerContext); - v8::Local callFrame = - v8::Local::New(m_isolate, m_callFrame); - v8::Local setVariableValueFunction = - v8::Local::Cast( - callFrame - ->Get(context, - toV8StringInternalized(m_isolate, "setVariableValue")) - .ToLocalChecked()); - v8::Local argv[] = { - v8::Local(v8::Integer::New(m_isolate, scopeNumber)), - variableName, newValue}; - return setVariableValueFunction->Call(context, callFrame, arraysize(argv), - argv); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/java-script-call-frame.h b/deps/v8_inspector/src/inspector/java-script-call-frame.h deleted file mode 100644 index 5a4ce19cc20ef6..00000000000000 --- a/deps/v8_inspector/src/inspector/java-script-call-frame.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2010, Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_JAVASCRIPTCALLFRAME_H_ -#define V8_INSPECTOR_JAVASCRIPTCALLFRAME_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/protocol-platform.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class JavaScriptCallFrame { - public: - static std::unique_ptr create( - v8::Local debuggerContext, v8::Local callFrame) { - return wrapUnique(new JavaScriptCallFrame(debuggerContext, callFrame)); - } - ~JavaScriptCallFrame(); - - int sourceID() const; - int line() const; - int column() const; - int contextId() const; - - bool isAtReturn() const; - v8::Local details() const; - - v8::MaybeLocal evaluate(v8::Local expression); - v8::MaybeLocal restart(); - v8::MaybeLocal setVariableValue(int scopeNumber, - v8::Local variableName, - v8::Local newValue); - - private: - JavaScriptCallFrame(v8::Local debuggerContext, - v8::Local callFrame); - - int callV8FunctionReturnInt(const char* name) const; - - v8::Isolate* m_isolate; - v8::Global m_debuggerContext; - v8::Global m_callFrame; - - DISALLOW_COPY_AND_ASSIGN(JavaScriptCallFrame); -}; - -using JavaScriptCallFrames = std::vector>; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_JAVASCRIPTCALLFRAME_H_ diff --git a/deps/v8_inspector/src/inspector/js_protocol-1.2.json b/deps/v8_inspector/src/inspector/js_protocol-1.2.json deleted file mode 100644 index aff68062226847..00000000000000 --- a/deps/v8_inspector/src/inspector/js_protocol-1.2.json +++ /dev/null @@ -1,997 +0,0 @@ -{ - "version": { "major": "1", "minor": "2" }, - "domains": [ - { - "domain": "Schema", - "description": "Provides information about the protocol schema.", - "types": [ - { - "id": "Domain", - "type": "object", - "description": "Description of the protocol domain.", - "exported": true, - "properties": [ - { "name": "name", "type": "string", "description": "Domain name." }, - { "name": "version", "type": "string", "description": "Domain version." } - ] - } - ], - "commands": [ - { - "name": "getDomains", - "description": "Returns supported domains.", - "handlers": ["browser", "renderer"], - "returns": [ - { "name": "domains", "type": "array", "items": { "$ref": "Domain" }, "description": "List of supported domains." } - ] - } - ] - }, - { - "domain": "Runtime", - "description": "Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects. Evaluation results are returned as mirror object that expose object type, string representation and unique identifier that can be used for further object reference. Original objects are maintained in memory unless they are either explicitly released or are released along with the other objects in their object group.", - "types": [ - { - "id": "ScriptId", - "type": "string", - "description": "Unique script identifier." - }, - { - "id": "RemoteObjectId", - "type": "string", - "description": "Unique object identifier." - }, - { - "id": "UnserializableValue", - "type": "string", - "enum": ["Infinity", "NaN", "-Infinity", "-0"], - "description": "Primitive value which cannot be JSON-stringified." - }, - { - "id": "RemoteObject", - "type": "object", - "description": "Mirror object referencing original JavaScript object.", - "exported": true, - "properties": [ - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol"], "description": "Object type." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "map", "set", "iterator", "generator", "error", "proxy", "promise", "typedarray"], "description": "Object subtype hint. Specified for object type values only." }, - { "name": "className", "type": "string", "optional": true, "description": "Object class (constructor) name. Specified for object type values only." }, - { "name": "value", "type": "any", "optional": true, "description": "Remote object value in case of primitive values or JSON values (if it was requested)." }, - { "name": "unserializableValue", "$ref": "UnserializableValue", "optional": true, "description": "Primitive value which can not be JSON-stringified does not have value, but gets this property." }, - { "name": "description", "type": "string", "optional": true, "description": "String representation of the object." }, - { "name": "objectId", "$ref": "RemoteObjectId", "optional": true, "description": "Unique object identifier (for non-primitive values)." }, - { "name": "preview", "$ref": "ObjectPreview", "optional": true, "description": "Preview containing abbreviated property values. Specified for object type values only.", "experimental": true }, - { "name": "customPreview", "$ref": "CustomPreview", "optional": true, "experimental": true} - ] - }, - { - "id": "CustomPreview", - "type": "object", - "experimental": true, - "properties": [ - { "name": "header", "type": "string"}, - { "name": "hasBody", "type": "boolean"}, - { "name": "formatterObjectId", "$ref": "RemoteObjectId"}, - { "name": "bindRemoteObjectFunctionId", "$ref": "RemoteObjectId" }, - { "name": "configObjectId", "$ref": "RemoteObjectId", "optional": true } - ] - }, - { - "id": "ObjectPreview", - "type": "object", - "experimental": true, - "description": "Object containing abbreviated remote object value.", - "properties": [ - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol"], "description": "Object type." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "map", "set", "iterator", "generator", "error"], "description": "Object subtype hint. Specified for object type values only." }, - { "name": "description", "type": "string", "optional": true, "description": "String representation of the object." }, - { "name": "overflow", "type": "boolean", "description": "True iff some of the properties or entries of the original object did not fit." }, - { "name": "properties", "type": "array", "items": { "$ref": "PropertyPreview" }, "description": "List of the properties." }, - { "name": "entries", "type": "array", "items": { "$ref": "EntryPreview" }, "optional": true, "description": "List of the entries. Specified for map and set subtype values only." } - ] - }, - { - "id": "PropertyPreview", - "type": "object", - "experimental": true, - "properties": [ - { "name": "name", "type": "string", "description": "Property name." }, - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol", "accessor"], "description": "Object type. Accessor means that the property itself is an accessor property." }, - { "name": "value", "type": "string", "optional": true, "description": "User-friendly property value string." }, - { "name": "valuePreview", "$ref": "ObjectPreview", "optional": true, "description": "Nested value preview." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "map", "set", "iterator", "generator", "error"], "description": "Object subtype hint. Specified for object type values only." } - ] - }, - { - "id": "EntryPreview", - "type": "object", - "experimental": true, - "properties": [ - { "name": "key", "$ref": "ObjectPreview", "optional": true, "description": "Preview of the key. Specified for map-like collection entries." }, - { "name": "value", "$ref": "ObjectPreview", "description": "Preview of the value." } - ] - }, - { - "id": "PropertyDescriptor", - "type": "object", - "description": "Object property descriptor.", - "properties": [ - { "name": "name", "type": "string", "description": "Property name or symbol description." }, - { "name": "value", "$ref": "RemoteObject", "optional": true, "description": "The value associated with the property." }, - { "name": "writable", "type": "boolean", "optional": true, "description": "True if the value associated with the property may be changed (data descriptors only)." }, - { "name": "get", "$ref": "RemoteObject", "optional": true, "description": "A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only)." }, - { "name": "set", "$ref": "RemoteObject", "optional": true, "description": "A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only)." }, - { "name": "configurable", "type": "boolean", "description": "True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object." }, - { "name": "enumerable", "type": "boolean", "description": "True if this property shows up during enumeration of the properties on the corresponding object." }, - { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." }, - { "name": "isOwn", "optional": true, "type": "boolean", "description": "True if the property is owned for the object." }, - { "name": "symbol", "$ref": "RemoteObject", "optional": true, "description": "Property symbol object, if the property is of the symbol type." } - ] - }, - { - "id": "InternalPropertyDescriptor", - "type": "object", - "description": "Object internal property descriptor. This property isn't normally visible in JavaScript code.", - "properties": [ - { "name": "name", "type": "string", "description": "Conventional property name." }, - { "name": "value", "$ref": "RemoteObject", "optional": true, "description": "The value associated with the property." } - ] - }, - { - "id": "CallArgument", - "type": "object", - "description": "Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified.", - "properties": [ - { "name": "value", "type": "any", "optional": true, "description": "Primitive value." }, - { "name": "unserializableValue", "$ref": "UnserializableValue", "optional": true, "description": "Primitive value which can not be JSON-stringified." }, - { "name": "objectId", "$ref": "RemoteObjectId", "optional": true, "description": "Remote object handle." } - ] - }, - { - "id": "ExecutionContextId", - "type": "integer", - "description": "Id of an execution context." - }, - { - "id": "ExecutionContextDescription", - "type": "object", - "description": "Description of an isolated world.", - "properties": [ - { "name": "id", "$ref": "ExecutionContextId", "description": "Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed." }, - { "name": "origin", "type": "string", "description": "Execution context origin." }, - { "name": "name", "type": "string", "description": "Human readable name describing given context." }, - { "name": "auxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data." } - ] - }, - { - "id": "ExceptionDetails", - "type": "object", - "description": "Detailed information about exception (or error) that was thrown during script compilation or execution.", - "properties": [ - { "name": "exceptionId", "type": "integer", "description": "Exception id." }, - { "name": "text", "type": "string", "description": "Exception text, which should be used together with exception object when available." }, - { "name": "lineNumber", "type": "integer", "description": "Line number of the exception location (0-based)." }, - { "name": "columnNumber", "type": "integer", "description": "Column number of the exception location (0-based)." }, - { "name": "scriptId", "$ref": "ScriptId", "optional": true, "description": "Script ID of the exception location." }, - { "name": "url", "type": "string", "optional": true, "description": "URL of the exception location, to be used when the script was not reported." }, - { "name": "stackTrace", "$ref": "StackTrace", "optional": true, "description": "JavaScript stack trace if available." }, - { "name": "exception", "$ref": "RemoteObject", "optional": true, "description": "Exception object if available." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "optional": true, "description": "Identifier of the context where exception happened." } - ] - }, - { - "id": "Timestamp", - "type": "number", - "description": "Number of milliseconds since epoch." - }, - { - "id": "CallFrame", - "type": "object", - "description": "Stack entry for runtime errors and assertions.", - "properties": [ - { "name": "functionName", "type": "string", "description": "JavaScript function name." }, - { "name": "scriptId", "$ref": "ScriptId", "description": "JavaScript script id." }, - { "name": "url", "type": "string", "description": "JavaScript script name or url." }, - { "name": "lineNumber", "type": "integer", "description": "JavaScript script line number (0-based)." }, - { "name": "columnNumber", "type": "integer", "description": "JavaScript script column number (0-based)." } - ] - }, - { - "id": "StackTrace", - "type": "object", - "description": "Call frames for assertions or error messages.", - "exported": true, - "properties": [ - { "name": "description", "type": "string", "optional": true, "description": "String label of this stack trace. For async traces this may be a name of the function that initiated the async call." }, - { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "JavaScript function name." }, - { "name": "parent", "$ref": "StackTrace", "optional": true, "description": "Asynchronous JavaScript stack trace that preceded this stack, if available." } - ] - } - ], - "commands": [ - { - "name": "evaluate", - "async": true, - "parameters": [ - { "name": "expression", "type": "string", "description": "Expression to evaluate." }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." }, - { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Determines whether Command Line API should be available during the evaluation." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "contextId", "$ref": "ExecutionContextId", "optional": true, "description": "Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the result." }, - { "name": "userGesture", "type": "boolean", "optional": true, "experimental": true, "description": "Whether execution should be treated as initiated by user in the UI." }, - { "name": "awaitPromise", "type": "boolean", "optional":true, "description": "Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Evaluation result." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Evaluates expression on global object." - }, - { - "name": "awaitPromise", - "async": true, - "parameters": [ - { "name": "promiseObjectId", "$ref": "RemoteObjectId", "description": "Identifier of the promise." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Promise result. Will contain rejected value if promise was rejected." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details if stack strace is available."} - ], - "description": "Add handler to promise with given promise object id." - }, - { - "name": "callFunctionOn", - "async": true, - "parameters": [ - { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to call function on." }, - { "name": "functionDeclaration", "type": "string", "description": "Declaration of the function to call." }, - { "name": "arguments", "type": "array", "items": { "$ref": "CallArgument", "description": "Call argument." }, "optional": true, "description": "Call arguments. All call arguments must belong to the same JavaScript world as the target object." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object which should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the result." }, - { "name": "userGesture", "type": "boolean", "optional": true, "experimental": true, "description": "Whether execution should be treated as initiated by user in the UI." }, - { "name": "awaitPromise", "type": "boolean", "optional":true, "description": "Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Call result." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Calls function with given declaration on the given object. Object group of the result is inherited from the target object." - }, - { - "name": "getProperties", - "parameters": [ - { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to return properties for." }, - { "name": "ownProperties", "optional": true, "type": "boolean", "description": "If true, returns properties belonging only to the element itself, not to its prototype chain." }, - { "name": "accessorPropertiesOnly", "optional": true, "type": "boolean", "description": "If true, returns accessor properties (with getter/setter) only; internal properties are not returned either.", "experimental": true }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the results." } - ], - "returns": [ - { "name": "result", "type": "array", "items": { "$ref": "PropertyDescriptor" }, "description": "Object properties." }, - { "name": "internalProperties", "optional": true, "type": "array", "items": { "$ref": "InternalPropertyDescriptor" }, "description": "Internal object properties (only of the element itself)." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Returns properties of a given object. Object group of the result is inherited from the target object." - }, - { - "name": "releaseObject", - "parameters": [ - { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to release." } - ], - "description": "Releases remote object with given id." - }, - { - "name": "releaseObjectGroup", - "parameters": [ - { "name": "objectGroup", "type": "string", "description": "Symbolic object group name." } - ], - "description": "Releases all remote objects that belong to a given group." - }, - { - "name": "runIfWaitingForDebugger", - "description": "Tells inspected instance to run if it was waiting for debugger to attach." - }, - { - "name": "enable", - "description": "Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context." - }, - { - "name": "disable", - "description": "Disables reporting of execution contexts creation." - }, - { - "name": "discardConsoleEntries", - "description": "Discards collected exceptions and console API calls." - }, - { - "name": "setCustomObjectFormatterEnabled", - "parameters": [ - { - "name": "enabled", - "type": "boolean" - } - ], - "experimental": true - }, - { - "name": "compileScript", - "parameters": [ - { "name": "expression", "type": "string", "description": "Expression to compile." }, - { "name": "sourceURL", "type": "string", "description": "Source url to be set for the script." }, - { "name": "persistScript", "type": "boolean", "description": "Specifies whether the compiled script should be persisted." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "optional": true, "description": "Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page." } - ], - "returns": [ - { "name": "scriptId", "$ref": "ScriptId", "optional": true, "description": "Id of the script." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Compiles expression." - }, - { - "name": "runScript", - "async": true, - "parameters": [ - { "name": "scriptId", "$ref": "ScriptId", "description": "Id of the script to run." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "optional": true, "description": "Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page." }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Determines whether Command Line API should be available during the evaluation." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object which should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." }, - { "name": "awaitPromise", "type": "boolean", "optional": true, "description": "Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Run result." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Runs script with given id in a given context." - } - ], - "events": [ - { - "name": "executionContextCreated", - "parameters": [ - { "name": "context", "$ref": "ExecutionContextDescription", "description": "A newly created execution contex." } - ], - "description": "Issued when new execution context is created." - }, - { - "name": "executionContextDestroyed", - "parameters": [ - { "name": "executionContextId", "$ref": "ExecutionContextId", "description": "Id of the destroyed context" } - ], - "description": "Issued when execution context is destroyed." - }, - { - "name": "executionContextsCleared", - "description": "Issued when all executionContexts were cleared in browser" - }, - { - "name": "exceptionThrown", - "description": "Issued when exception was thrown and unhandled.", - "parameters": [ - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp of the exception." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails" } - ] - }, - { - "name": "exceptionRevoked", - "description": "Issued when unhandled exception was revoked.", - "parameters": [ - { "name": "reason", "type": "string", "description": "Reason describing why exception was revoked." }, - { "name": "exceptionId", "type": "integer", "description": "The id of revoked exception, as reported in exceptionUnhandled." } - ] - }, - { - "name": "consoleAPICalled", - "description": "Issued when console API was called.", - "parameters": [ - { "name": "type", "type": "string", "enum": ["log", "debug", "info", "error", "warning", "dir", "dirxml", "table", "trace", "clear", "startGroup", "startGroupCollapsed", "endGroup", "assert", "profile", "profileEnd"], "description": "Type of the call." }, - { "name": "args", "type": "array", "items": { "$ref": "RemoteObject" }, "description": "Call arguments." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "description": "Identifier of the context where the call was made." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Call timestamp." }, - { "name": "stackTrace", "$ref": "StackTrace", "optional": true, "description": "Stack trace captured when the call was made." } - ] - }, - { - "name": "inspectRequested", - "description": "Issued when object should be inspected (for example, as a result of inspect() command line API call).", - "parameters": [ - { "name": "object", "$ref": "RemoteObject" }, - { "name": "hints", "type": "object" } - ] - } - ] - }, - { - "domain": "Debugger", - "description": "Debugger domain exposes JavaScript debugging capabilities. It allows setting and removing breakpoints, stepping through execution, exploring stack traces, etc.", - "dependencies": ["Runtime"], - "types": [ - { - "id": "BreakpointId", - "type": "string", - "description": "Breakpoint identifier." - }, - { - "id": "CallFrameId", - "type": "string", - "description": "Call frame identifier." - }, - { - "id": "Location", - "type": "object", - "properties": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Script identifier as reported in the Debugger.scriptParsed." }, - { "name": "lineNumber", "type": "integer", "description": "Line number in the script (0-based)." }, - { "name": "columnNumber", "type": "integer", "optional": true, "description": "Column number in the script (0-based)." } - ], - "description": "Location in the source code." - }, - { - "id": "ScriptPosition", - "experimental": true, - "type": "object", - "properties": [ - { "name": "lineNumber", "type": "integer" }, - { "name": "columnNumber", "type": "integer" } - ], - "description": "Location in the source code." - }, - { - "id": "CallFrame", - "type": "object", - "properties": [ - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier. This identifier is only valid while the virtual machine is paused." }, - { "name": "functionName", "type": "string", "description": "Name of the JavaScript function called on this call frame." }, - { "name": "functionLocation", "$ref": "Location", "optional": true, "experimental": true, "description": "Location in the source code." }, - { "name": "location", "$ref": "Location", "description": "Location in the source code." }, - { "name": "scopeChain", "type": "array", "items": { "$ref": "Scope" }, "description": "Scope chain for this call frame." }, - { "name": "this", "$ref": "Runtime.RemoteObject", "description": "this object for this call frame." }, - { "name": "returnValue", "$ref": "Runtime.RemoteObject", "optional": true, "description": "The value being returned, if the function is at return point." } - ], - "description": "JavaScript call frame. Array of call frames form the call stack." - }, - { - "id": "Scope", - "type": "object", - "properties": [ - { "name": "type", "type": "string", "enum": ["global", "local", "with", "closure", "catch", "block", "script"], "description": "Scope type." }, - { "name": "object", "$ref": "Runtime.RemoteObject", "description": "Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties." }, - { "name": "name", "type": "string", "optional": true }, - { "name": "startLocation", "$ref": "Location", "optional": true, "description": "Location in the source code where scope starts" }, - { "name": "endLocation", "$ref": "Location", "optional": true, "description": "Location in the source code where scope ends" } - ], - "description": "Scope description." - }, - { - "id": "SearchMatch", - "type": "object", - "description": "Search match for resource.", - "exported": true, - "properties": [ - { "name": "lineNumber", "type": "number", "description": "Line number in resource content." }, - { "name": "lineContent", "type": "string", "description": "Line with match content." } - ], - "experimental": true - } - ], - "commands": [ - { - "name": "enable", - "description": "Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received." - }, - { - "name": "disable", - "description": "Disables debugger for given page." - }, - { - "name": "setBreakpointsActive", - "parameters": [ - { "name": "active", "type": "boolean", "description": "New value for breakpoints active state." } - ], - "description": "Activates / deactivates all breakpoints on the page." - }, - { - "name": "setSkipAllPauses", - "parameters": [ - { "name": "skip", "type": "boolean", "description": "New value for skip pauses state." } - ], - "description": "Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc)." - }, - { - "name": "setBreakpointByUrl", - "parameters": [ - { "name": "lineNumber", "type": "integer", "description": "Line number to set breakpoint at." }, - { "name": "url", "type": "string", "optional": true, "description": "URL of the resources to set breakpoint on." }, - { "name": "urlRegex", "type": "string", "optional": true, "description": "Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified." }, - { "name": "columnNumber", "type": "integer", "optional": true, "description": "Offset in the line to set breakpoint at." }, - { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true." } - ], - "returns": [ - { "name": "breakpointId", "$ref": "BreakpointId", "description": "Id of the created breakpoint for further reference." }, - { "name": "locations", "type": "array", "items": { "$ref": "Location" }, "description": "List of the locations this breakpoint resolved into upon addition." } - ], - "description": "Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads." - }, - { - "name": "setBreakpoint", - "parameters": [ - { "name": "location", "$ref": "Location", "description": "Location to set breakpoint in." }, - { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true." } - ], - "returns": [ - { "name": "breakpointId", "$ref": "BreakpointId", "description": "Id of the created breakpoint for further reference." }, - { "name": "actualLocation", "$ref": "Location", "description": "Location this breakpoint resolved into." } - ], - "description": "Sets JavaScript breakpoint at a given location." - }, - { - "name": "removeBreakpoint", - "parameters": [ - { "name": "breakpointId", "$ref": "BreakpointId" } - ], - "description": "Removes JavaScript breakpoint." - }, - { - "name": "continueToLocation", - "parameters": [ - { "name": "location", "$ref": "Location", "description": "Location to continue to." } - ], - "description": "Continues execution until specific location is reached." - }, - { - "name": "stepOver", - "description": "Steps over the statement." - }, - { - "name": "stepInto", - "description": "Steps into the function call." - }, - { - "name": "stepOut", - "description": "Steps out of the function call." - }, - { - "name": "pause", - "description": "Stops on the next JavaScript statement." - }, - { - "name": "resume", - "description": "Resumes JavaScript execution." - }, - { - "name": "searchInContent", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script to search in." }, - { "name": "query", "type": "string", "description": "String to search for." }, - { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive." }, - { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex." } - ], - "returns": [ - { "name": "result", "type": "array", "items": { "$ref": "SearchMatch" }, "description": "List of search matches." } - ], - "experimental": true, - "description": "Searches for given string in script content." - }, - { - "name": "setScriptSource", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script to edit." }, - { "name": "scriptSource", "type": "string", "description": "New content of the script." }, - { "name": "dryRun", "type": "boolean", "optional": true, "description": " If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code." } - ], - "returns": [ - { "name": "callFrames", "type": "array", "optional": true, "items": { "$ref": "CallFrame" }, "description": "New stack trace in case editing has happened while VM was stopped." }, - { "name": "stackChanged", "type": "boolean", "optional": true, "description": "Whether current call stack was modified after applying the changes." }, - { "name": "asyncStackTrace", "$ref": "Runtime.StackTrace", "optional": true, "description": "Async stack trace, if any." }, - { "name": "exceptionDetails", "optional": true, "$ref": "Runtime.ExceptionDetails", "description": "Exception details if any." } - ], - "description": "Edits JavaScript source live." - }, - { - "name": "restartFrame", - "parameters": [ - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier to evaluate on." } - ], - "returns": [ - { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "New stack trace." }, - { "name": "asyncStackTrace", "$ref": "Runtime.StackTrace", "optional": true, "description": "Async stack trace, if any." } - ], - "description": "Restarts particular call frame from the beginning." - }, - { - "name": "getScriptSource", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script to get source for." } - ], - "returns": [ - { "name": "scriptSource", "type": "string", "description": "Script source." } - ], - "description": "Returns source for the script with given id." - }, - { - "name": "setPauseOnExceptions", - "parameters": [ - { "name": "state", "type": "string", "enum": ["none", "uncaught", "all"], "description": "Pause on exceptions mode." } - ], - "description": "Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none." - }, - { - "name": "evaluateOnCallFrame", - "parameters": [ - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier to evaluate on." }, - { "name": "expression", "type": "string", "description": "Expression to evaluate." }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup)." }, - { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Specifies whether command line API should be available to the evaluated expression, defaults to false." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the result." } - ], - "returns": [ - { "name": "result", "$ref": "Runtime.RemoteObject", "description": "Object wrapper for the evaluation result." }, - { "name": "exceptionDetails", "$ref": "Runtime.ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Evaluates expression on a given call frame." - }, - { - "name": "setVariableValue", - "parameters": [ - { "name": "scopeNumber", "type": "integer", "description": "0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually." }, - { "name": "variableName", "type": "string", "description": "Variable name." }, - { "name": "newValue", "$ref": "Runtime.CallArgument", "description": "New variable value." }, - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Id of callframe that holds variable." } - ], - "description": "Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually." - }, - { - "name": "setAsyncCallStackDepth", - "parameters": [ - { "name": "maxDepth", "type": "integer", "description": "Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default)." } - ], - "description": "Enables or disables async call stacks tracking." - }, - { - "name": "setBlackboxPatterns", - "parameters": [ - { "name": "patterns", "type": "array", "items": { "type": "string" }, "description": "Array of regexps that will be used to check script url for blackbox state." } - ], - "experimental": true, - "description": "Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful." - }, - { - "name": "setBlackboxedRanges", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script." }, - { "name": "positions", "type": "array", "items": { "$ref": "ScriptPosition" } } - ], - "experimental": true, - "description": "Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted." - } - ], - "events": [ - { - "name": "scriptParsed", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Identifier of the script parsed." }, - { "name": "url", "type": "string", "description": "URL or name of the script parsed (if any)." }, - { "name": "startLine", "type": "integer", "description": "Line offset of the script within the resource with given URL (for script tags)." }, - { "name": "startColumn", "type": "integer", "description": "Column offset of the script within the resource with given URL." }, - { "name": "endLine", "type": "integer", "description": "Last line of the script." }, - { "name": "endColumn", "type": "integer", "description": "Length of the last line of the script." }, - { "name": "executionContextId", "$ref": "Runtime.ExecutionContextId", "description": "Specifies script creation context." }, - { "name": "hash", "type": "string", "description": "Content hash of the script."}, - { "name": "executionContextAuxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data." }, - { "name": "isLiveEdit", "type": "boolean", "optional": true, "description": "True, if this script is generated as a result of the live edit operation.", "experimental": true }, - { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with script (if any)." }, - { "name": "hasSourceURL", "type": "boolean", "optional": true, "description": "True, if this script has sourceURL.", "experimental": true } - ], - "description": "Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger." - }, - { - "name": "scriptFailedToParse", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Identifier of the script parsed." }, - { "name": "url", "type": "string", "description": "URL or name of the script parsed (if any)." }, - { "name": "startLine", "type": "integer", "description": "Line offset of the script within the resource with given URL (for script tags)." }, - { "name": "startColumn", "type": "integer", "description": "Column offset of the script within the resource with given URL." }, - { "name": "endLine", "type": "integer", "description": "Last line of the script." }, - { "name": "endColumn", "type": "integer", "description": "Length of the last line of the script." }, - { "name": "executionContextId", "$ref": "Runtime.ExecutionContextId", "description": "Specifies script creation context." }, - { "name": "hash", "type": "string", "description": "Content hash of the script."}, - { "name": "executionContextAuxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data." }, - { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with script (if any)." }, - { "name": "hasSourceURL", "type": "boolean", "optional": true, "description": "True, if this script has sourceURL.", "experimental": true } - ], - "description": "Fired when virtual machine fails to parse the script." - }, - { - "name": "breakpointResolved", - "parameters": [ - { "name": "breakpointId", "$ref": "BreakpointId", "description": "Breakpoint unique identifier." }, - { "name": "location", "$ref": "Location", "description": "Actual breakpoint location." } - ], - "description": "Fired when breakpoint is resolved to an actual script and location." - }, - { - "name": "paused", - "parameters": [ - { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "Call stack the virtual machine stopped on." }, - { "name": "reason", "type": "string", "enum": [ "XHR", "DOM", "EventListener", "exception", "assert", "debugCommand", "promiseRejection", "other" ], "description": "Pause reason.", "exported": true }, - { "name": "data", "type": "object", "optional": true, "description": "Object containing break-specific auxiliary properties." }, - { "name": "hitBreakpoints", "type": "array", "optional": true, "items": { "type": "string" }, "description": "Hit breakpoints IDs" }, - { "name": "asyncStackTrace", "$ref": "Runtime.StackTrace", "optional": true, "description": "Async stack trace, if any." } - ], - "description": "Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria." - }, - { - "name": "resumed", - "description": "Fired when the virtual machine resumed execution." - } - ] - }, - { - "domain": "Console", - "description": "This domain is deprecated - use Runtime or Log instead.", - "dependencies": ["Runtime"], - "deprecated": true, - "types": [ - { - "id": "ConsoleMessage", - "type": "object", - "description": "Console message.", - "properties": [ - { "name": "source", "type": "string", "enum": ["xml", "javascript", "network", "console-api", "storage", "appcache", "rendering", "security", "other", "deprecation", "worker"], "description": "Message source." }, - { "name": "level", "type": "string", "enum": ["log", "warning", "error", "debug", "info"], "description": "Message severity." }, - { "name": "text", "type": "string", "description": "Message text." }, - { "name": "url", "type": "string", "optional": true, "description": "URL of the message origin." }, - { "name": "line", "type": "integer", "optional": true, "description": "Line number in the resource that generated this message (1-based)." }, - { "name": "column", "type": "integer", "optional": true, "description": "Column number in the resource that generated this message (1-based)." } - ] - } - ], - "commands": [ - { - "name": "enable", - "description": "Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification." - }, - { - "name": "disable", - "description": "Disables console domain, prevents further console messages from being reported to the client." - }, - { - "name": "clearMessages", - "description": "Does nothing." - } - ], - "events": [ - { - "name": "messageAdded", - "parameters": [ - { "name": "message", "$ref": "ConsoleMessage", "description": "Console message that has been added." } - ], - "description": "Issued when new console message is added." - } - ] - }, - { - "domain": "Profiler", - "dependencies": ["Runtime", "Debugger"], - "types": [ - { - "id": "ProfileNode", - "type": "object", - "description": "Profile node. Holds callsite information, execution statistics and child nodes.", - "properties": [ - { "name": "id", "type": "integer", "description": "Unique id of the node." }, - { "name": "callFrame", "$ref": "Runtime.CallFrame", "description": "Function location." }, - { "name": "hitCount", "type": "integer", "optional": true, "experimental": true, "description": "Number of samples where this node was on top of the call stack." }, - { "name": "children", "type": "array", "items": { "type": "integer" }, "optional": true, "description": "Child node ids." }, - { "name": "deoptReason", "type": "string", "optional": true, "description": "The reason of being not optimized. The function may be deoptimized or marked as don't optimize."}, - { "name": "positionTicks", "type": "array", "items": { "$ref": "PositionTickInfo" }, "optional": true, "experimental": true, "description": "An array of source position ticks." } - ] - }, - { - "id": "Profile", - "type": "object", - "description": "Profile.", - "properties": [ - { "name": "nodes", "type": "array", "items": { "$ref": "ProfileNode" }, "description": "The list of profile nodes. First item is the root node." }, - { "name": "startTime", "type": "number", "description": "Profiling start timestamp in microseconds." }, - { "name": "endTime", "type": "number", "description": "Profiling end timestamp in microseconds." }, - { "name": "samples", "optional": true, "type": "array", "items": { "type": "integer" }, "description": "Ids of samples top nodes." }, - { "name": "timeDeltas", "optional": true, "type": "array", "items": { "type": "integer" }, "description": "Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime." } - ] - }, - { - "id": "PositionTickInfo", - "type": "object", - "experimental": true, - "description": "Specifies a number of samples attributed to a certain source position.", - "properties": [ - { "name": "line", "type": "integer", "description": "Source line number (1-based)." }, - { "name": "ticks", "type": "integer", "description": "Number of samples attributed to the source line." } - ] - } - ], - "commands": [ - { - "name": "enable" - }, - { - "name": "disable" - }, - { - "name": "setSamplingInterval", - "parameters": [ - { "name": "interval", "type": "integer", "description": "New sampling interval in microseconds." } - ], - "description": "Changes CPU profiler sampling interval. Must be called before CPU profiles recording started." - }, - { - "name": "start" - }, - { - "name": "stop", - "returns": [ - { "name": "profile", "$ref": "Profile", "description": "Recorded profile." } - ] - } - ], - "events": [ - { - "name": "consoleProfileStarted", - "parameters": [ - { "name": "id", "type": "string" }, - { "name": "location", "$ref": "Debugger.Location", "description": "Location of console.profile()." }, - { "name": "title", "type": "string", "optional": true, "description": "Profile title passed as an argument to console.profile()." } - ], - "description": "Sent when new profile recodring is started using console.profile() call." - }, - { - "name": "consoleProfileFinished", - "parameters": [ - { "name": "id", "type": "string" }, - { "name": "location", "$ref": "Debugger.Location", "description": "Location of console.profileEnd()." }, - { "name": "profile", "$ref": "Profile" }, - { "name": "title", "type": "string", "optional": true, "description": "Profile title passed as an argument to console.profile()." } - ] - } - ] - }, - { - "domain": "HeapProfiler", - "dependencies": ["Runtime"], - "experimental": true, - "types": [ - { - "id": "HeapSnapshotObjectId", - "type": "string", - "description": "Heap snapshot object id." - }, - { - "id": "SamplingHeapProfileNode", - "type": "object", - "description": "Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.", - "properties": [ - { "name": "callFrame", "$ref": "Runtime.CallFrame", "description": "Function location." }, - { "name": "selfSize", "type": "number", "description": "Allocations size in bytes for the node excluding children." }, - { "name": "children", "type": "array", "items": { "$ref": "SamplingHeapProfileNode" }, "description": "Child nodes." } - ] - }, - { - "id": "SamplingHeapProfile", - "type": "object", - "description": "Profile.", - "properties": [ - { "name": "head", "$ref": "SamplingHeapProfileNode" } - ] - } - ], - "commands": [ - { - "name": "enable" - }, - { - "name": "disable" - }, - { - "name": "startTrackingHeapObjects", - "parameters": [ - { "name": "trackAllocations", "type": "boolean", "optional": true } - ] - }, - { - "name": "stopTrackingHeapObjects", - "parameters": [ - { "name": "reportProgress", "type": "boolean", "optional": true, "description": "If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped." } - ] - }, - { - "name": "takeHeapSnapshot", - "parameters": [ - { "name": "reportProgress", "type": "boolean", "optional": true, "description": "If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken." } - ] - }, - { - "name": "collectGarbage" - }, - { - "name": "getObjectByHeapObjectId", - "parameters": [ - { "name": "objectId", "$ref": "HeapSnapshotObjectId" }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." } - ], - "returns": [ - { "name": "result", "$ref": "Runtime.RemoteObject", "description": "Evaluation result." } - ] - }, - { - "name": "addInspectedHeapObject", - "parameters": [ - { "name": "heapObjectId", "$ref": "HeapSnapshotObjectId", "description": "Heap snapshot object id to be accessible by means of $x command line API." } - ], - "description": "Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions)." - }, - { - "name": "getHeapObjectId", - "parameters": [ - { "name": "objectId", "$ref": "Runtime.RemoteObjectId", "description": "Identifier of the object to get heap object id for." } - ], - "returns": [ - { "name": "heapSnapshotObjectId", "$ref": "HeapSnapshotObjectId", "description": "Id of the heap snapshot object corresponding to the passed remote object id." } - ] - }, - { - "name": "startSampling", - "parameters": [ - { "name": "samplingInterval", "type": "number", "optional": true, "description": "Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes." } - ] - }, - { - "name": "stopSampling", - "returns": [ - { "name": "profile", "$ref": "SamplingHeapProfile", "description": "Recorded sampling heap profile." } - ] - } - ], - "events": [ - { - "name": "addHeapSnapshotChunk", - "parameters": [ - { "name": "chunk", "type": "string" } - ] - }, - { - "name": "resetProfiles" - }, - { - "name": "reportHeapSnapshotProgress", - "parameters": [ - { "name": "done", "type": "integer" }, - { "name": "total", "type": "integer" }, - { "name": "finished", "type": "boolean", "optional": true } - ] - }, - { - "name": "lastSeenObjectId", - "description": "If heap objects tracking has been started then backend regulary sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event.", - "parameters": [ - { "name": "lastSeenObjectId", "type": "integer" }, - { "name": "timestamp", "type": "number" } - ] - }, - { - "name": "heapStatsUpdate", - "description": "If heap objects tracking has been started then backend may send update for one or more fragments", - "parameters": [ - { "name": "statsUpdate", "type": "array", "items": { "type": "integer" }, "description": "An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment."} - ] - } - ] - }] -} diff --git a/deps/v8_inspector/src/inspector/js_protocol.json b/deps/v8_inspector/src/inspector/js_protocol.json deleted file mode 100644 index aff68062226847..00000000000000 --- a/deps/v8_inspector/src/inspector/js_protocol.json +++ /dev/null @@ -1,997 +0,0 @@ -{ - "version": { "major": "1", "minor": "2" }, - "domains": [ - { - "domain": "Schema", - "description": "Provides information about the protocol schema.", - "types": [ - { - "id": "Domain", - "type": "object", - "description": "Description of the protocol domain.", - "exported": true, - "properties": [ - { "name": "name", "type": "string", "description": "Domain name." }, - { "name": "version", "type": "string", "description": "Domain version." } - ] - } - ], - "commands": [ - { - "name": "getDomains", - "description": "Returns supported domains.", - "handlers": ["browser", "renderer"], - "returns": [ - { "name": "domains", "type": "array", "items": { "$ref": "Domain" }, "description": "List of supported domains." } - ] - } - ] - }, - { - "domain": "Runtime", - "description": "Runtime domain exposes JavaScript runtime by means of remote evaluation and mirror objects. Evaluation results are returned as mirror object that expose object type, string representation and unique identifier that can be used for further object reference. Original objects are maintained in memory unless they are either explicitly released or are released along with the other objects in their object group.", - "types": [ - { - "id": "ScriptId", - "type": "string", - "description": "Unique script identifier." - }, - { - "id": "RemoteObjectId", - "type": "string", - "description": "Unique object identifier." - }, - { - "id": "UnserializableValue", - "type": "string", - "enum": ["Infinity", "NaN", "-Infinity", "-0"], - "description": "Primitive value which cannot be JSON-stringified." - }, - { - "id": "RemoteObject", - "type": "object", - "description": "Mirror object referencing original JavaScript object.", - "exported": true, - "properties": [ - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol"], "description": "Object type." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "map", "set", "iterator", "generator", "error", "proxy", "promise", "typedarray"], "description": "Object subtype hint. Specified for object type values only." }, - { "name": "className", "type": "string", "optional": true, "description": "Object class (constructor) name. Specified for object type values only." }, - { "name": "value", "type": "any", "optional": true, "description": "Remote object value in case of primitive values or JSON values (if it was requested)." }, - { "name": "unserializableValue", "$ref": "UnserializableValue", "optional": true, "description": "Primitive value which can not be JSON-stringified does not have value, but gets this property." }, - { "name": "description", "type": "string", "optional": true, "description": "String representation of the object." }, - { "name": "objectId", "$ref": "RemoteObjectId", "optional": true, "description": "Unique object identifier (for non-primitive values)." }, - { "name": "preview", "$ref": "ObjectPreview", "optional": true, "description": "Preview containing abbreviated property values. Specified for object type values only.", "experimental": true }, - { "name": "customPreview", "$ref": "CustomPreview", "optional": true, "experimental": true} - ] - }, - { - "id": "CustomPreview", - "type": "object", - "experimental": true, - "properties": [ - { "name": "header", "type": "string"}, - { "name": "hasBody", "type": "boolean"}, - { "name": "formatterObjectId", "$ref": "RemoteObjectId"}, - { "name": "bindRemoteObjectFunctionId", "$ref": "RemoteObjectId" }, - { "name": "configObjectId", "$ref": "RemoteObjectId", "optional": true } - ] - }, - { - "id": "ObjectPreview", - "type": "object", - "experimental": true, - "description": "Object containing abbreviated remote object value.", - "properties": [ - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol"], "description": "Object type." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "map", "set", "iterator", "generator", "error"], "description": "Object subtype hint. Specified for object type values only." }, - { "name": "description", "type": "string", "optional": true, "description": "String representation of the object." }, - { "name": "overflow", "type": "boolean", "description": "True iff some of the properties or entries of the original object did not fit." }, - { "name": "properties", "type": "array", "items": { "$ref": "PropertyPreview" }, "description": "List of the properties." }, - { "name": "entries", "type": "array", "items": { "$ref": "EntryPreview" }, "optional": true, "description": "List of the entries. Specified for map and set subtype values only." } - ] - }, - { - "id": "PropertyPreview", - "type": "object", - "experimental": true, - "properties": [ - { "name": "name", "type": "string", "description": "Property name." }, - { "name": "type", "type": "string", "enum": ["object", "function", "undefined", "string", "number", "boolean", "symbol", "accessor"], "description": "Object type. Accessor means that the property itself is an accessor property." }, - { "name": "value", "type": "string", "optional": true, "description": "User-friendly property value string." }, - { "name": "valuePreview", "$ref": "ObjectPreview", "optional": true, "description": "Nested value preview." }, - { "name": "subtype", "type": "string", "optional": true, "enum": ["array", "null", "node", "regexp", "date", "map", "set", "iterator", "generator", "error"], "description": "Object subtype hint. Specified for object type values only." } - ] - }, - { - "id": "EntryPreview", - "type": "object", - "experimental": true, - "properties": [ - { "name": "key", "$ref": "ObjectPreview", "optional": true, "description": "Preview of the key. Specified for map-like collection entries." }, - { "name": "value", "$ref": "ObjectPreview", "description": "Preview of the value." } - ] - }, - { - "id": "PropertyDescriptor", - "type": "object", - "description": "Object property descriptor.", - "properties": [ - { "name": "name", "type": "string", "description": "Property name or symbol description." }, - { "name": "value", "$ref": "RemoteObject", "optional": true, "description": "The value associated with the property." }, - { "name": "writable", "type": "boolean", "optional": true, "description": "True if the value associated with the property may be changed (data descriptors only)." }, - { "name": "get", "$ref": "RemoteObject", "optional": true, "description": "A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only)." }, - { "name": "set", "$ref": "RemoteObject", "optional": true, "description": "A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only)." }, - { "name": "configurable", "type": "boolean", "description": "True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object." }, - { "name": "enumerable", "type": "boolean", "description": "True if this property shows up during enumeration of the properties on the corresponding object." }, - { "name": "wasThrown", "type": "boolean", "optional": true, "description": "True if the result was thrown during the evaluation." }, - { "name": "isOwn", "optional": true, "type": "boolean", "description": "True if the property is owned for the object." }, - { "name": "symbol", "$ref": "RemoteObject", "optional": true, "description": "Property symbol object, if the property is of the symbol type." } - ] - }, - { - "id": "InternalPropertyDescriptor", - "type": "object", - "description": "Object internal property descriptor. This property isn't normally visible in JavaScript code.", - "properties": [ - { "name": "name", "type": "string", "description": "Conventional property name." }, - { "name": "value", "$ref": "RemoteObject", "optional": true, "description": "The value associated with the property." } - ] - }, - { - "id": "CallArgument", - "type": "object", - "description": "Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified.", - "properties": [ - { "name": "value", "type": "any", "optional": true, "description": "Primitive value." }, - { "name": "unserializableValue", "$ref": "UnserializableValue", "optional": true, "description": "Primitive value which can not be JSON-stringified." }, - { "name": "objectId", "$ref": "RemoteObjectId", "optional": true, "description": "Remote object handle." } - ] - }, - { - "id": "ExecutionContextId", - "type": "integer", - "description": "Id of an execution context." - }, - { - "id": "ExecutionContextDescription", - "type": "object", - "description": "Description of an isolated world.", - "properties": [ - { "name": "id", "$ref": "ExecutionContextId", "description": "Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed." }, - { "name": "origin", "type": "string", "description": "Execution context origin." }, - { "name": "name", "type": "string", "description": "Human readable name describing given context." }, - { "name": "auxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data." } - ] - }, - { - "id": "ExceptionDetails", - "type": "object", - "description": "Detailed information about exception (or error) that was thrown during script compilation or execution.", - "properties": [ - { "name": "exceptionId", "type": "integer", "description": "Exception id." }, - { "name": "text", "type": "string", "description": "Exception text, which should be used together with exception object when available." }, - { "name": "lineNumber", "type": "integer", "description": "Line number of the exception location (0-based)." }, - { "name": "columnNumber", "type": "integer", "description": "Column number of the exception location (0-based)." }, - { "name": "scriptId", "$ref": "ScriptId", "optional": true, "description": "Script ID of the exception location." }, - { "name": "url", "type": "string", "optional": true, "description": "URL of the exception location, to be used when the script was not reported." }, - { "name": "stackTrace", "$ref": "StackTrace", "optional": true, "description": "JavaScript stack trace if available." }, - { "name": "exception", "$ref": "RemoteObject", "optional": true, "description": "Exception object if available." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "optional": true, "description": "Identifier of the context where exception happened." } - ] - }, - { - "id": "Timestamp", - "type": "number", - "description": "Number of milliseconds since epoch." - }, - { - "id": "CallFrame", - "type": "object", - "description": "Stack entry for runtime errors and assertions.", - "properties": [ - { "name": "functionName", "type": "string", "description": "JavaScript function name." }, - { "name": "scriptId", "$ref": "ScriptId", "description": "JavaScript script id." }, - { "name": "url", "type": "string", "description": "JavaScript script name or url." }, - { "name": "lineNumber", "type": "integer", "description": "JavaScript script line number (0-based)." }, - { "name": "columnNumber", "type": "integer", "description": "JavaScript script column number (0-based)." } - ] - }, - { - "id": "StackTrace", - "type": "object", - "description": "Call frames for assertions or error messages.", - "exported": true, - "properties": [ - { "name": "description", "type": "string", "optional": true, "description": "String label of this stack trace. For async traces this may be a name of the function that initiated the async call." }, - { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "JavaScript function name." }, - { "name": "parent", "$ref": "StackTrace", "optional": true, "description": "Asynchronous JavaScript stack trace that preceded this stack, if available." } - ] - } - ], - "commands": [ - { - "name": "evaluate", - "async": true, - "parameters": [ - { "name": "expression", "type": "string", "description": "Expression to evaluate." }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." }, - { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Determines whether Command Line API should be available during the evaluation." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "contextId", "$ref": "ExecutionContextId", "optional": true, "description": "Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the result." }, - { "name": "userGesture", "type": "boolean", "optional": true, "experimental": true, "description": "Whether execution should be treated as initiated by user in the UI." }, - { "name": "awaitPromise", "type": "boolean", "optional":true, "description": "Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Evaluation result." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Evaluates expression on global object." - }, - { - "name": "awaitPromise", - "async": true, - "parameters": [ - { "name": "promiseObjectId", "$ref": "RemoteObjectId", "description": "Identifier of the promise." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Promise result. Will contain rejected value if promise was rejected." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details if stack strace is available."} - ], - "description": "Add handler to promise with given promise object id." - }, - { - "name": "callFunctionOn", - "async": true, - "parameters": [ - { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to call function on." }, - { "name": "functionDeclaration", "type": "string", "description": "Declaration of the function to call." }, - { "name": "arguments", "type": "array", "items": { "$ref": "CallArgument", "description": "Call argument." }, "optional": true, "description": "Call arguments. All call arguments must belong to the same JavaScript world as the target object." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object which should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the result." }, - { "name": "userGesture", "type": "boolean", "optional": true, "experimental": true, "description": "Whether execution should be treated as initiated by user in the UI." }, - { "name": "awaitPromise", "type": "boolean", "optional":true, "description": "Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Call result." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Calls function with given declaration on the given object. Object group of the result is inherited from the target object." - }, - { - "name": "getProperties", - "parameters": [ - { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to return properties for." }, - { "name": "ownProperties", "optional": true, "type": "boolean", "description": "If true, returns properties belonging only to the element itself, not to its prototype chain." }, - { "name": "accessorPropertiesOnly", "optional": true, "type": "boolean", "description": "If true, returns accessor properties (with getter/setter) only; internal properties are not returned either.", "experimental": true }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the results." } - ], - "returns": [ - { "name": "result", "type": "array", "items": { "$ref": "PropertyDescriptor" }, "description": "Object properties." }, - { "name": "internalProperties", "optional": true, "type": "array", "items": { "$ref": "InternalPropertyDescriptor" }, "description": "Internal object properties (only of the element itself)." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Returns properties of a given object. Object group of the result is inherited from the target object." - }, - { - "name": "releaseObject", - "parameters": [ - { "name": "objectId", "$ref": "RemoteObjectId", "description": "Identifier of the object to release." } - ], - "description": "Releases remote object with given id." - }, - { - "name": "releaseObjectGroup", - "parameters": [ - { "name": "objectGroup", "type": "string", "description": "Symbolic object group name." } - ], - "description": "Releases all remote objects that belong to a given group." - }, - { - "name": "runIfWaitingForDebugger", - "description": "Tells inspected instance to run if it was waiting for debugger to attach." - }, - { - "name": "enable", - "description": "Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context." - }, - { - "name": "disable", - "description": "Disables reporting of execution contexts creation." - }, - { - "name": "discardConsoleEntries", - "description": "Discards collected exceptions and console API calls." - }, - { - "name": "setCustomObjectFormatterEnabled", - "parameters": [ - { - "name": "enabled", - "type": "boolean" - } - ], - "experimental": true - }, - { - "name": "compileScript", - "parameters": [ - { "name": "expression", "type": "string", "description": "Expression to compile." }, - { "name": "sourceURL", "type": "string", "description": "Source url to be set for the script." }, - { "name": "persistScript", "type": "boolean", "description": "Specifies whether the compiled script should be persisted." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "optional": true, "description": "Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page." } - ], - "returns": [ - { "name": "scriptId", "$ref": "ScriptId", "optional": true, "description": "Id of the script." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Compiles expression." - }, - { - "name": "runScript", - "async": true, - "parameters": [ - { "name": "scriptId", "$ref": "ScriptId", "description": "Id of the script to run." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "optional": true, "description": "Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page." }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Determines whether Command Line API should be available during the evaluation." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object which should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "description": "Whether preview should be generated for the result." }, - { "name": "awaitPromise", "type": "boolean", "optional": true, "description": "Whether execution should wait for promise to be resolved. If the result of evaluation is not a Promise, it's considered to be an error." } - ], - "returns": [ - { "name": "result", "$ref": "RemoteObject", "description": "Run result." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Runs script with given id in a given context." - } - ], - "events": [ - { - "name": "executionContextCreated", - "parameters": [ - { "name": "context", "$ref": "ExecutionContextDescription", "description": "A newly created execution contex." } - ], - "description": "Issued when new execution context is created." - }, - { - "name": "executionContextDestroyed", - "parameters": [ - { "name": "executionContextId", "$ref": "ExecutionContextId", "description": "Id of the destroyed context" } - ], - "description": "Issued when execution context is destroyed." - }, - { - "name": "executionContextsCleared", - "description": "Issued when all executionContexts were cleared in browser" - }, - { - "name": "exceptionThrown", - "description": "Issued when exception was thrown and unhandled.", - "parameters": [ - { "name": "timestamp", "$ref": "Timestamp", "description": "Timestamp of the exception." }, - { "name": "exceptionDetails", "$ref": "ExceptionDetails" } - ] - }, - { - "name": "exceptionRevoked", - "description": "Issued when unhandled exception was revoked.", - "parameters": [ - { "name": "reason", "type": "string", "description": "Reason describing why exception was revoked." }, - { "name": "exceptionId", "type": "integer", "description": "The id of revoked exception, as reported in exceptionUnhandled." } - ] - }, - { - "name": "consoleAPICalled", - "description": "Issued when console API was called.", - "parameters": [ - { "name": "type", "type": "string", "enum": ["log", "debug", "info", "error", "warning", "dir", "dirxml", "table", "trace", "clear", "startGroup", "startGroupCollapsed", "endGroup", "assert", "profile", "profileEnd"], "description": "Type of the call." }, - { "name": "args", "type": "array", "items": { "$ref": "RemoteObject" }, "description": "Call arguments." }, - { "name": "executionContextId", "$ref": "ExecutionContextId", "description": "Identifier of the context where the call was made." }, - { "name": "timestamp", "$ref": "Timestamp", "description": "Call timestamp." }, - { "name": "stackTrace", "$ref": "StackTrace", "optional": true, "description": "Stack trace captured when the call was made." } - ] - }, - { - "name": "inspectRequested", - "description": "Issued when object should be inspected (for example, as a result of inspect() command line API call).", - "parameters": [ - { "name": "object", "$ref": "RemoteObject" }, - { "name": "hints", "type": "object" } - ] - } - ] - }, - { - "domain": "Debugger", - "description": "Debugger domain exposes JavaScript debugging capabilities. It allows setting and removing breakpoints, stepping through execution, exploring stack traces, etc.", - "dependencies": ["Runtime"], - "types": [ - { - "id": "BreakpointId", - "type": "string", - "description": "Breakpoint identifier." - }, - { - "id": "CallFrameId", - "type": "string", - "description": "Call frame identifier." - }, - { - "id": "Location", - "type": "object", - "properties": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Script identifier as reported in the Debugger.scriptParsed." }, - { "name": "lineNumber", "type": "integer", "description": "Line number in the script (0-based)." }, - { "name": "columnNumber", "type": "integer", "optional": true, "description": "Column number in the script (0-based)." } - ], - "description": "Location in the source code." - }, - { - "id": "ScriptPosition", - "experimental": true, - "type": "object", - "properties": [ - { "name": "lineNumber", "type": "integer" }, - { "name": "columnNumber", "type": "integer" } - ], - "description": "Location in the source code." - }, - { - "id": "CallFrame", - "type": "object", - "properties": [ - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier. This identifier is only valid while the virtual machine is paused." }, - { "name": "functionName", "type": "string", "description": "Name of the JavaScript function called on this call frame." }, - { "name": "functionLocation", "$ref": "Location", "optional": true, "experimental": true, "description": "Location in the source code." }, - { "name": "location", "$ref": "Location", "description": "Location in the source code." }, - { "name": "scopeChain", "type": "array", "items": { "$ref": "Scope" }, "description": "Scope chain for this call frame." }, - { "name": "this", "$ref": "Runtime.RemoteObject", "description": "this object for this call frame." }, - { "name": "returnValue", "$ref": "Runtime.RemoteObject", "optional": true, "description": "The value being returned, if the function is at return point." } - ], - "description": "JavaScript call frame. Array of call frames form the call stack." - }, - { - "id": "Scope", - "type": "object", - "properties": [ - { "name": "type", "type": "string", "enum": ["global", "local", "with", "closure", "catch", "block", "script"], "description": "Scope type." }, - { "name": "object", "$ref": "Runtime.RemoteObject", "description": "Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties." }, - { "name": "name", "type": "string", "optional": true }, - { "name": "startLocation", "$ref": "Location", "optional": true, "description": "Location in the source code where scope starts" }, - { "name": "endLocation", "$ref": "Location", "optional": true, "description": "Location in the source code where scope ends" } - ], - "description": "Scope description." - }, - { - "id": "SearchMatch", - "type": "object", - "description": "Search match for resource.", - "exported": true, - "properties": [ - { "name": "lineNumber", "type": "number", "description": "Line number in resource content." }, - { "name": "lineContent", "type": "string", "description": "Line with match content." } - ], - "experimental": true - } - ], - "commands": [ - { - "name": "enable", - "description": "Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received." - }, - { - "name": "disable", - "description": "Disables debugger for given page." - }, - { - "name": "setBreakpointsActive", - "parameters": [ - { "name": "active", "type": "boolean", "description": "New value for breakpoints active state." } - ], - "description": "Activates / deactivates all breakpoints on the page." - }, - { - "name": "setSkipAllPauses", - "parameters": [ - { "name": "skip", "type": "boolean", "description": "New value for skip pauses state." } - ], - "description": "Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc)." - }, - { - "name": "setBreakpointByUrl", - "parameters": [ - { "name": "lineNumber", "type": "integer", "description": "Line number to set breakpoint at." }, - { "name": "url", "type": "string", "optional": true, "description": "URL of the resources to set breakpoint on." }, - { "name": "urlRegex", "type": "string", "optional": true, "description": "Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified." }, - { "name": "columnNumber", "type": "integer", "optional": true, "description": "Offset in the line to set breakpoint at." }, - { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true." } - ], - "returns": [ - { "name": "breakpointId", "$ref": "BreakpointId", "description": "Id of the created breakpoint for further reference." }, - { "name": "locations", "type": "array", "items": { "$ref": "Location" }, "description": "List of the locations this breakpoint resolved into upon addition." } - ], - "description": "Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads." - }, - { - "name": "setBreakpoint", - "parameters": [ - { "name": "location", "$ref": "Location", "description": "Location to set breakpoint in." }, - { "name": "condition", "type": "string", "optional": true, "description": "Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true." } - ], - "returns": [ - { "name": "breakpointId", "$ref": "BreakpointId", "description": "Id of the created breakpoint for further reference." }, - { "name": "actualLocation", "$ref": "Location", "description": "Location this breakpoint resolved into." } - ], - "description": "Sets JavaScript breakpoint at a given location." - }, - { - "name": "removeBreakpoint", - "parameters": [ - { "name": "breakpointId", "$ref": "BreakpointId" } - ], - "description": "Removes JavaScript breakpoint." - }, - { - "name": "continueToLocation", - "parameters": [ - { "name": "location", "$ref": "Location", "description": "Location to continue to." } - ], - "description": "Continues execution until specific location is reached." - }, - { - "name": "stepOver", - "description": "Steps over the statement." - }, - { - "name": "stepInto", - "description": "Steps into the function call." - }, - { - "name": "stepOut", - "description": "Steps out of the function call." - }, - { - "name": "pause", - "description": "Stops on the next JavaScript statement." - }, - { - "name": "resume", - "description": "Resumes JavaScript execution." - }, - { - "name": "searchInContent", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script to search in." }, - { "name": "query", "type": "string", "description": "String to search for." }, - { "name": "caseSensitive", "type": "boolean", "optional": true, "description": "If true, search is case sensitive." }, - { "name": "isRegex", "type": "boolean", "optional": true, "description": "If true, treats string parameter as regex." } - ], - "returns": [ - { "name": "result", "type": "array", "items": { "$ref": "SearchMatch" }, "description": "List of search matches." } - ], - "experimental": true, - "description": "Searches for given string in script content." - }, - { - "name": "setScriptSource", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script to edit." }, - { "name": "scriptSource", "type": "string", "description": "New content of the script." }, - { "name": "dryRun", "type": "boolean", "optional": true, "description": " If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code." } - ], - "returns": [ - { "name": "callFrames", "type": "array", "optional": true, "items": { "$ref": "CallFrame" }, "description": "New stack trace in case editing has happened while VM was stopped." }, - { "name": "stackChanged", "type": "boolean", "optional": true, "description": "Whether current call stack was modified after applying the changes." }, - { "name": "asyncStackTrace", "$ref": "Runtime.StackTrace", "optional": true, "description": "Async stack trace, if any." }, - { "name": "exceptionDetails", "optional": true, "$ref": "Runtime.ExceptionDetails", "description": "Exception details if any." } - ], - "description": "Edits JavaScript source live." - }, - { - "name": "restartFrame", - "parameters": [ - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier to evaluate on." } - ], - "returns": [ - { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "New stack trace." }, - { "name": "asyncStackTrace", "$ref": "Runtime.StackTrace", "optional": true, "description": "Async stack trace, if any." } - ], - "description": "Restarts particular call frame from the beginning." - }, - { - "name": "getScriptSource", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script to get source for." } - ], - "returns": [ - { "name": "scriptSource", "type": "string", "description": "Script source." } - ], - "description": "Returns source for the script with given id." - }, - { - "name": "setPauseOnExceptions", - "parameters": [ - { "name": "state", "type": "string", "enum": ["none", "uncaught", "all"], "description": "Pause on exceptions mode." } - ], - "description": "Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none." - }, - { - "name": "evaluateOnCallFrame", - "parameters": [ - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Call frame identifier to evaluate on." }, - { "name": "expression", "type": "string", "description": "Expression to evaluate." }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup)." }, - { "name": "includeCommandLineAPI", "type": "boolean", "optional": true, "description": "Specifies whether command line API should be available to the evaluated expression, defaults to false." }, - { "name": "silent", "type": "boolean", "optional": true, "description": "In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state." }, - { "name": "returnByValue", "type": "boolean", "optional": true, "description": "Whether the result is expected to be a JSON object that should be sent by value." }, - { "name": "generatePreview", "type": "boolean", "optional": true, "experimental": true, "description": "Whether preview should be generated for the result." } - ], - "returns": [ - { "name": "result", "$ref": "Runtime.RemoteObject", "description": "Object wrapper for the evaluation result." }, - { "name": "exceptionDetails", "$ref": "Runtime.ExceptionDetails", "optional": true, "description": "Exception details."} - ], - "description": "Evaluates expression on a given call frame." - }, - { - "name": "setVariableValue", - "parameters": [ - { "name": "scopeNumber", "type": "integer", "description": "0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually." }, - { "name": "variableName", "type": "string", "description": "Variable name." }, - { "name": "newValue", "$ref": "Runtime.CallArgument", "description": "New variable value." }, - { "name": "callFrameId", "$ref": "CallFrameId", "description": "Id of callframe that holds variable." } - ], - "description": "Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually." - }, - { - "name": "setAsyncCallStackDepth", - "parameters": [ - { "name": "maxDepth", "type": "integer", "description": "Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default)." } - ], - "description": "Enables or disables async call stacks tracking." - }, - { - "name": "setBlackboxPatterns", - "parameters": [ - { "name": "patterns", "type": "array", "items": { "type": "string" }, "description": "Array of regexps that will be used to check script url for blackbox state." } - ], - "experimental": true, - "description": "Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful." - }, - { - "name": "setBlackboxedRanges", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Id of the script." }, - { "name": "positions", "type": "array", "items": { "$ref": "ScriptPosition" } } - ], - "experimental": true, - "description": "Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted." - } - ], - "events": [ - { - "name": "scriptParsed", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Identifier of the script parsed." }, - { "name": "url", "type": "string", "description": "URL or name of the script parsed (if any)." }, - { "name": "startLine", "type": "integer", "description": "Line offset of the script within the resource with given URL (for script tags)." }, - { "name": "startColumn", "type": "integer", "description": "Column offset of the script within the resource with given URL." }, - { "name": "endLine", "type": "integer", "description": "Last line of the script." }, - { "name": "endColumn", "type": "integer", "description": "Length of the last line of the script." }, - { "name": "executionContextId", "$ref": "Runtime.ExecutionContextId", "description": "Specifies script creation context." }, - { "name": "hash", "type": "string", "description": "Content hash of the script."}, - { "name": "executionContextAuxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data." }, - { "name": "isLiveEdit", "type": "boolean", "optional": true, "description": "True, if this script is generated as a result of the live edit operation.", "experimental": true }, - { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with script (if any)." }, - { "name": "hasSourceURL", "type": "boolean", "optional": true, "description": "True, if this script has sourceURL.", "experimental": true } - ], - "description": "Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger." - }, - { - "name": "scriptFailedToParse", - "parameters": [ - { "name": "scriptId", "$ref": "Runtime.ScriptId", "description": "Identifier of the script parsed." }, - { "name": "url", "type": "string", "description": "URL or name of the script parsed (if any)." }, - { "name": "startLine", "type": "integer", "description": "Line offset of the script within the resource with given URL (for script tags)." }, - { "name": "startColumn", "type": "integer", "description": "Column offset of the script within the resource with given URL." }, - { "name": "endLine", "type": "integer", "description": "Last line of the script." }, - { "name": "endColumn", "type": "integer", "description": "Length of the last line of the script." }, - { "name": "executionContextId", "$ref": "Runtime.ExecutionContextId", "description": "Specifies script creation context." }, - { "name": "hash", "type": "string", "description": "Content hash of the script."}, - { "name": "executionContextAuxData", "type": "object", "optional": true, "description": "Embedder-specific auxiliary data." }, - { "name": "sourceMapURL", "type": "string", "optional": true, "description": "URL of source map associated with script (if any)." }, - { "name": "hasSourceURL", "type": "boolean", "optional": true, "description": "True, if this script has sourceURL.", "experimental": true } - ], - "description": "Fired when virtual machine fails to parse the script." - }, - { - "name": "breakpointResolved", - "parameters": [ - { "name": "breakpointId", "$ref": "BreakpointId", "description": "Breakpoint unique identifier." }, - { "name": "location", "$ref": "Location", "description": "Actual breakpoint location." } - ], - "description": "Fired when breakpoint is resolved to an actual script and location." - }, - { - "name": "paused", - "parameters": [ - { "name": "callFrames", "type": "array", "items": { "$ref": "CallFrame" }, "description": "Call stack the virtual machine stopped on." }, - { "name": "reason", "type": "string", "enum": [ "XHR", "DOM", "EventListener", "exception", "assert", "debugCommand", "promiseRejection", "other" ], "description": "Pause reason.", "exported": true }, - { "name": "data", "type": "object", "optional": true, "description": "Object containing break-specific auxiliary properties." }, - { "name": "hitBreakpoints", "type": "array", "optional": true, "items": { "type": "string" }, "description": "Hit breakpoints IDs" }, - { "name": "asyncStackTrace", "$ref": "Runtime.StackTrace", "optional": true, "description": "Async stack trace, if any." } - ], - "description": "Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria." - }, - { - "name": "resumed", - "description": "Fired when the virtual machine resumed execution." - } - ] - }, - { - "domain": "Console", - "description": "This domain is deprecated - use Runtime or Log instead.", - "dependencies": ["Runtime"], - "deprecated": true, - "types": [ - { - "id": "ConsoleMessage", - "type": "object", - "description": "Console message.", - "properties": [ - { "name": "source", "type": "string", "enum": ["xml", "javascript", "network", "console-api", "storage", "appcache", "rendering", "security", "other", "deprecation", "worker"], "description": "Message source." }, - { "name": "level", "type": "string", "enum": ["log", "warning", "error", "debug", "info"], "description": "Message severity." }, - { "name": "text", "type": "string", "description": "Message text." }, - { "name": "url", "type": "string", "optional": true, "description": "URL of the message origin." }, - { "name": "line", "type": "integer", "optional": true, "description": "Line number in the resource that generated this message (1-based)." }, - { "name": "column", "type": "integer", "optional": true, "description": "Column number in the resource that generated this message (1-based)." } - ] - } - ], - "commands": [ - { - "name": "enable", - "description": "Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification." - }, - { - "name": "disable", - "description": "Disables console domain, prevents further console messages from being reported to the client." - }, - { - "name": "clearMessages", - "description": "Does nothing." - } - ], - "events": [ - { - "name": "messageAdded", - "parameters": [ - { "name": "message", "$ref": "ConsoleMessage", "description": "Console message that has been added." } - ], - "description": "Issued when new console message is added." - } - ] - }, - { - "domain": "Profiler", - "dependencies": ["Runtime", "Debugger"], - "types": [ - { - "id": "ProfileNode", - "type": "object", - "description": "Profile node. Holds callsite information, execution statistics and child nodes.", - "properties": [ - { "name": "id", "type": "integer", "description": "Unique id of the node." }, - { "name": "callFrame", "$ref": "Runtime.CallFrame", "description": "Function location." }, - { "name": "hitCount", "type": "integer", "optional": true, "experimental": true, "description": "Number of samples where this node was on top of the call stack." }, - { "name": "children", "type": "array", "items": { "type": "integer" }, "optional": true, "description": "Child node ids." }, - { "name": "deoptReason", "type": "string", "optional": true, "description": "The reason of being not optimized. The function may be deoptimized or marked as don't optimize."}, - { "name": "positionTicks", "type": "array", "items": { "$ref": "PositionTickInfo" }, "optional": true, "experimental": true, "description": "An array of source position ticks." } - ] - }, - { - "id": "Profile", - "type": "object", - "description": "Profile.", - "properties": [ - { "name": "nodes", "type": "array", "items": { "$ref": "ProfileNode" }, "description": "The list of profile nodes. First item is the root node." }, - { "name": "startTime", "type": "number", "description": "Profiling start timestamp in microseconds." }, - { "name": "endTime", "type": "number", "description": "Profiling end timestamp in microseconds." }, - { "name": "samples", "optional": true, "type": "array", "items": { "type": "integer" }, "description": "Ids of samples top nodes." }, - { "name": "timeDeltas", "optional": true, "type": "array", "items": { "type": "integer" }, "description": "Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime." } - ] - }, - { - "id": "PositionTickInfo", - "type": "object", - "experimental": true, - "description": "Specifies a number of samples attributed to a certain source position.", - "properties": [ - { "name": "line", "type": "integer", "description": "Source line number (1-based)." }, - { "name": "ticks", "type": "integer", "description": "Number of samples attributed to the source line." } - ] - } - ], - "commands": [ - { - "name": "enable" - }, - { - "name": "disable" - }, - { - "name": "setSamplingInterval", - "parameters": [ - { "name": "interval", "type": "integer", "description": "New sampling interval in microseconds." } - ], - "description": "Changes CPU profiler sampling interval. Must be called before CPU profiles recording started." - }, - { - "name": "start" - }, - { - "name": "stop", - "returns": [ - { "name": "profile", "$ref": "Profile", "description": "Recorded profile." } - ] - } - ], - "events": [ - { - "name": "consoleProfileStarted", - "parameters": [ - { "name": "id", "type": "string" }, - { "name": "location", "$ref": "Debugger.Location", "description": "Location of console.profile()." }, - { "name": "title", "type": "string", "optional": true, "description": "Profile title passed as an argument to console.profile()." } - ], - "description": "Sent when new profile recodring is started using console.profile() call." - }, - { - "name": "consoleProfileFinished", - "parameters": [ - { "name": "id", "type": "string" }, - { "name": "location", "$ref": "Debugger.Location", "description": "Location of console.profileEnd()." }, - { "name": "profile", "$ref": "Profile" }, - { "name": "title", "type": "string", "optional": true, "description": "Profile title passed as an argument to console.profile()." } - ] - } - ] - }, - { - "domain": "HeapProfiler", - "dependencies": ["Runtime"], - "experimental": true, - "types": [ - { - "id": "HeapSnapshotObjectId", - "type": "string", - "description": "Heap snapshot object id." - }, - { - "id": "SamplingHeapProfileNode", - "type": "object", - "description": "Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes.", - "properties": [ - { "name": "callFrame", "$ref": "Runtime.CallFrame", "description": "Function location." }, - { "name": "selfSize", "type": "number", "description": "Allocations size in bytes for the node excluding children." }, - { "name": "children", "type": "array", "items": { "$ref": "SamplingHeapProfileNode" }, "description": "Child nodes." } - ] - }, - { - "id": "SamplingHeapProfile", - "type": "object", - "description": "Profile.", - "properties": [ - { "name": "head", "$ref": "SamplingHeapProfileNode" } - ] - } - ], - "commands": [ - { - "name": "enable" - }, - { - "name": "disable" - }, - { - "name": "startTrackingHeapObjects", - "parameters": [ - { "name": "trackAllocations", "type": "boolean", "optional": true } - ] - }, - { - "name": "stopTrackingHeapObjects", - "parameters": [ - { "name": "reportProgress", "type": "boolean", "optional": true, "description": "If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped." } - ] - }, - { - "name": "takeHeapSnapshot", - "parameters": [ - { "name": "reportProgress", "type": "boolean", "optional": true, "description": "If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken." } - ] - }, - { - "name": "collectGarbage" - }, - { - "name": "getObjectByHeapObjectId", - "parameters": [ - { "name": "objectId", "$ref": "HeapSnapshotObjectId" }, - { "name": "objectGroup", "type": "string", "optional": true, "description": "Symbolic group name that can be used to release multiple objects." } - ], - "returns": [ - { "name": "result", "$ref": "Runtime.RemoteObject", "description": "Evaluation result." } - ] - }, - { - "name": "addInspectedHeapObject", - "parameters": [ - { "name": "heapObjectId", "$ref": "HeapSnapshotObjectId", "description": "Heap snapshot object id to be accessible by means of $x command line API." } - ], - "description": "Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions)." - }, - { - "name": "getHeapObjectId", - "parameters": [ - { "name": "objectId", "$ref": "Runtime.RemoteObjectId", "description": "Identifier of the object to get heap object id for." } - ], - "returns": [ - { "name": "heapSnapshotObjectId", "$ref": "HeapSnapshotObjectId", "description": "Id of the heap snapshot object corresponding to the passed remote object id." } - ] - }, - { - "name": "startSampling", - "parameters": [ - { "name": "samplingInterval", "type": "number", "optional": true, "description": "Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes." } - ] - }, - { - "name": "stopSampling", - "returns": [ - { "name": "profile", "$ref": "SamplingHeapProfile", "description": "Recorded sampling heap profile." } - ] - } - ], - "events": [ - { - "name": "addHeapSnapshotChunk", - "parameters": [ - { "name": "chunk", "type": "string" } - ] - }, - { - "name": "resetProfiles" - }, - { - "name": "reportHeapSnapshotProgress", - "parameters": [ - { "name": "done", "type": "integer" }, - { "name": "total", "type": "integer" }, - { "name": "finished", "type": "boolean", "optional": true } - ] - }, - { - "name": "lastSeenObjectId", - "description": "If heap objects tracking has been started then backend regulary sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event.", - "parameters": [ - { "name": "lastSeenObjectId", "type": "integer" }, - { "name": "timestamp", "type": "number" } - ] - }, - { - "name": "heapStatsUpdate", - "description": "If heap objects tracking has been started then backend may send update for one or more fragments", - "parameters": [ - { "name": "statsUpdate", "type": "array", "items": { "type": "integer" }, "description": "An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment."} - ] - } - ] - }] -} diff --git a/deps/v8_inspector/src/inspector/protocol-platform.h b/deps/v8_inspector/src/inspector/protocol-platform.h deleted file mode 100644 index c7723932b42465..00000000000000 --- a/deps/v8_inspector/src/inspector/protocol-platform.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_PROTOCOLPLATFORM_H_ -#define V8_INSPECTOR_PROTOCOLPLATFORM_H_ - -#include - -#include "src/base/logging.h" - -namespace v8_inspector { - -template -std::unique_ptr wrapUnique(T* ptr) { - return std::unique_ptr(ptr); -} - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_PROTOCOLPLATFORM_H_ diff --git a/deps/v8_inspector/src/inspector/remote-object-id.cc b/deps/v8_inspector/src/inspector/remote-object-id.cc deleted file mode 100644 index d83020c6f20208..00000000000000 --- a/deps/v8_inspector/src/inspector/remote-object-id.cc +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2015 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. - -#include "src/inspector/remote-object-id.h" - -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/string-util.h" - -namespace v8_inspector { - -RemoteObjectIdBase::RemoteObjectIdBase() : m_injectedScriptId(0) {} - -std::unique_ptr -RemoteObjectIdBase::parseInjectedScriptId(const String16& objectId) { - std::unique_ptr parsedValue = protocol::parseJSON(objectId); - if (!parsedValue || parsedValue->type() != protocol::Value::TypeObject) - return nullptr; - - std::unique_ptr parsedObjectId( - protocol::DictionaryValue::cast(parsedValue.release())); - bool success = - parsedObjectId->getInteger("injectedScriptId", &m_injectedScriptId); - if (success) return parsedObjectId; - return nullptr; -} - -RemoteObjectId::RemoteObjectId() : RemoteObjectIdBase(), m_id(0) {} - -std::unique_ptr RemoteObjectId::parse( - ErrorString* errorString, const String16& objectId) { - std::unique_ptr result(new RemoteObjectId()); - std::unique_ptr parsedObjectId = - result->parseInjectedScriptId(objectId); - if (!parsedObjectId) { - *errorString = "Invalid remote object id"; - return nullptr; - } - - bool success = parsedObjectId->getInteger("id", &result->m_id); - if (!success) { - *errorString = "Invalid remote object id"; - return nullptr; - } - return result; -} - -RemoteCallFrameId::RemoteCallFrameId() - : RemoteObjectIdBase(), m_frameOrdinal(0) {} - -std::unique_ptr RemoteCallFrameId::parse( - ErrorString* errorString, const String16& objectId) { - std::unique_ptr result(new RemoteCallFrameId()); - std::unique_ptr parsedObjectId = - result->parseInjectedScriptId(objectId); - if (!parsedObjectId) { - *errorString = "Invalid call frame id"; - return nullptr; - } - - bool success = parsedObjectId->getInteger("ordinal", &result->m_frameOrdinal); - if (!success) { - *errorString = "Invalid call frame id"; - return nullptr; - } - - return result; -} - -String16 RemoteCallFrameId::serialize(int injectedScriptId, int frameOrdinal) { - return "{\"ordinal\":" + String16::fromInteger(frameOrdinal) + - ",\"injectedScriptId\":" + String16::fromInteger(injectedScriptId) + - "}"; -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/remote-object-id.h b/deps/v8_inspector/src/inspector/remote-object-id.h deleted file mode 100644 index a32f568fb8ac0e..00000000000000 --- a/deps/v8_inspector/src/inspector/remote-object-id.h +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2015 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_REMOTEOBJECTID_H_ -#define V8_INSPECTOR_REMOTEOBJECTID_H_ - -#include "src/inspector/protocol/Forward.h" - -namespace v8_inspector { - -using protocol::ErrorString; - -class RemoteObjectIdBase { - public: - int contextId() const { return m_injectedScriptId; } - - protected: - RemoteObjectIdBase(); - ~RemoteObjectIdBase() {} - - std::unique_ptr parseInjectedScriptId( - const String16&); - - int m_injectedScriptId; -}; - -class RemoteObjectId final : public RemoteObjectIdBase { - public: - static std::unique_ptr parse(ErrorString*, const String16&); - ~RemoteObjectId() {} - int id() const { return m_id; } - - private: - RemoteObjectId(); - - int m_id; -}; - -class RemoteCallFrameId final : public RemoteObjectIdBase { - public: - static std::unique_ptr parse(ErrorString*, - const String16&); - ~RemoteCallFrameId() {} - - int frameOrdinal() const { return m_frameOrdinal; } - - static String16 serialize(int injectedScriptId, int frameOrdinal); - - private: - RemoteCallFrameId(); - - int m_frameOrdinal; -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_REMOTEOBJECTID_H_ diff --git a/deps/v8_inspector/src/inspector/script-breakpoint.h b/deps/v8_inspector/src/inspector/script-breakpoint.h deleted file mode 100644 index 025233dd19e802..00000000000000 --- a/deps/v8_inspector/src/inspector/script-breakpoint.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2009 Apple Inc. All rights reserved. - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_SCRIPTBREAKPOINT_H_ -#define V8_INSPECTOR_SCRIPTBREAKPOINT_H_ - -#include "src/inspector/string-16.h" - -namespace v8_inspector { - -struct ScriptBreakpoint { - ScriptBreakpoint() : ScriptBreakpoint(0, 0, String16()) {} - - ScriptBreakpoint(int lineNumber, int columnNumber, const String16& condition) - : lineNumber(lineNumber), - columnNumber(columnNumber), - condition(condition) {} - - int lineNumber; - int columnNumber; - String16 condition; -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_SCRIPTBREAKPOINT_H_ diff --git a/deps/v8_inspector/src/inspector/search-util.cc b/deps/v8_inspector/src/inspector/search-util.cc deleted file mode 100644 index a6fba06c115b72..00000000000000 --- a/deps/v8_inspector/src/inspector/search-util.cc +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/search-util.h" - -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-regex.h" - -namespace v8_inspector { - -namespace { - -String16 findMagicComment(const String16& content, const String16& name, - bool multiline) { - DCHECK(name.find("=") == String16::kNotFound); - size_t length = content.length(); - size_t nameLength = name.length(); - - size_t pos = length; - size_t equalSignPos = 0; - size_t closingCommentPos = 0; - while (true) { - pos = content.reverseFind(name, pos); - if (pos == String16::kNotFound) return String16(); - - // Check for a /\/[\/*][@#][ \t]/ regexp (length of 4) before found name. - if (pos < 4) return String16(); - pos -= 4; - if (content[pos] != '/') continue; - if ((content[pos + 1] != '/' || multiline) && - (content[pos + 1] != '*' || !multiline)) - continue; - if (content[pos + 2] != '#' && content[pos + 2] != '@') continue; - if (content[pos + 3] != ' ' && content[pos + 3] != '\t') continue; - equalSignPos = pos + 4 + nameLength; - if (equalSignPos < length && content[equalSignPos] != '=') continue; - if (multiline) { - closingCommentPos = content.find("*/", equalSignPos + 1); - if (closingCommentPos == String16::kNotFound) return String16(); - } - - break; - } - - DCHECK(equalSignPos); - DCHECK(!multiline || closingCommentPos); - size_t urlPos = equalSignPos + 1; - String16 match = multiline - ? content.substring(urlPos, closingCommentPos - urlPos) - : content.substring(urlPos); - - size_t newLine = match.find("\n"); - if (newLine != String16::kNotFound) match = match.substring(0, newLine); - match = match.stripWhiteSpace(); - - for (size_t i = 0; i < match.length(); ++i) { - UChar c = match[i]; - if (c == '"' || c == '\'' || c == ' ' || c == '\t') return ""; - } - - return match; -} - -String16 createSearchRegexSource(const String16& text) { - String16Builder result; - - for (size_t i = 0; i < text.length(); i++) { - UChar c = text[i]; - if (c == '[' || c == ']' || c == '(' || c == ')' || c == '{' || c == '}' || - c == '+' || c == '-' || c == '*' || c == '.' || c == ',' || c == '?' || - c == '\\' || c == '^' || c == '$' || c == '|') { - result.append('\\'); - } - result.append(c); - } - - return result.toString(); -} - -std::unique_ptr> lineEndings(const String16& text) { - std::unique_ptr> result(new std::vector()); - - const String16 lineEndString = "\n"; - size_t start = 0; - while (start < text.length()) { - size_t lineEnd = text.find(lineEndString, start); - if (lineEnd == String16::kNotFound) break; - - result->push_back(lineEnd); - start = lineEnd + 1; - } - result->push_back(text.length()); - - return result; -} - -std::vector> scriptRegexpMatchesByLines( - const V8Regex& regex, const String16& text) { - std::vector> result; - if (text.isEmpty()) return result; - - std::unique_ptr> endings(lineEndings(text)); - size_t size = endings->size(); - size_t start = 0; - for (size_t lineNumber = 0; lineNumber < size; ++lineNumber) { - size_t lineEnd = endings->at(lineNumber); - String16 line = text.substring(start, lineEnd - start); - if (line.length() && line[line.length() - 1] == '\r') - line = line.substring(0, line.length() - 1); - - int matchLength; - if (regex.match(line, 0, &matchLength) != -1) - result.push_back(std::pair(lineNumber, line)); - - start = lineEnd + 1; - } - return result; -} - -std::unique_ptr buildObjectForSearchMatch( - int lineNumber, const String16& lineContent) { - return protocol::Debugger::SearchMatch::create() - .setLineNumber(lineNumber) - .setLineContent(lineContent) - .build(); -} - -std::unique_ptr createSearchRegex(V8InspectorImpl* inspector, - const String16& query, - bool caseSensitive, bool isRegex) { - String16 regexSource = isRegex ? query : createSearchRegexSource(query); - return wrapUnique(new V8Regex(inspector, regexSource, caseSensitive)); -} - -} // namespace - -std::vector> -searchInTextByLinesImpl(V8InspectorSession* session, const String16& text, - const String16& query, const bool caseSensitive, - const bool isRegex) { - std::unique_ptr regex = createSearchRegex( - static_cast(session)->inspector(), query, - caseSensitive, isRegex); - std::vector> matches = - scriptRegexpMatchesByLines(*regex.get(), text); - - std::vector> result; - for (const auto& match : matches) - result.push_back(buildObjectForSearchMatch(match.first, match.second)); - return result; -} - -String16 findSourceURL(const String16& content, bool multiline) { - return findMagicComment(content, "sourceURL", multiline); -} - -String16 findSourceMapURL(const String16& content, bool multiline) { - return findMagicComment(content, "sourceMappingURL", multiline); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/search-util.h b/deps/v8_inspector/src/inspector/search-util.h deleted file mode 100644 index 8f5753b6202c1d..00000000000000 --- a/deps/v8_inspector/src/inspector/search-util.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_SEARCHUTIL_H_ -#define V8_INSPECTOR_SEARCHUTIL_H_ - -#include "src/inspector/protocol/Debugger.h" -#include "src/inspector/string-util.h" - -namespace v8_inspector { - -class V8InspectorSession; - -String16 findSourceURL(const String16& content, bool multiline); -String16 findSourceMapURL(const String16& content, bool multiline); -std::vector> -searchInTextByLinesImpl(V8InspectorSession*, const String16& text, - const String16& query, bool caseSensitive, - bool isRegex); - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_SEARCHUTIL_H_ diff --git a/deps/v8_inspector/src/inspector/string-16.cc b/deps/v8_inspector/src/inspector/string-16.cc deleted file mode 100644 index e39b87c17f8f03..00000000000000 --- a/deps/v8_inspector/src/inspector/string-16.cc +++ /dev/null @@ -1,523 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/string-16.h" - -#include -#include -#include -#include -#include -#include -#include - -#include "src/base/platform/platform.h" -#include "src/inspector/protocol-platform.h" - -namespace v8_inspector { - -namespace { - -bool isASCII(UChar c) { return !(c & ~0x7F); } - -bool isSpaceOrNewLine(UChar c) { - return isASCII(c) && c <= ' ' && (c == ' ' || (c <= 0xD && c >= 0x9)); -} - -int charactersToInteger(const UChar* characters, size_t length, - bool* ok = nullptr) { - std::vector buffer; - buffer.reserve(length + 1); - for (size_t i = 0; i < length; ++i) { - if (!isASCII(characters[i])) { - if (ok) *ok = false; - return 0; - } - buffer.push_back(static_cast(characters[i])); - } - buffer.push_back('\0'); - - char* endptr; - int64_t result = - static_cast(std::strtol(buffer.data(), &endptr, 10)); - if (ok) { - *ok = !(*endptr) && result <= std::numeric_limits::max() && - result >= std::numeric_limits::min(); - } - return static_cast(result); -} - -const UChar replacementCharacter = 0xFFFD; -using UChar32 = uint32_t; - -inline int inlineUTF8SequenceLengthNonASCII(char b0) { - if ((b0 & 0xC0) != 0xC0) return 0; - if ((b0 & 0xE0) == 0xC0) return 2; - if ((b0 & 0xF0) == 0xE0) return 3; - if ((b0 & 0xF8) == 0xF0) return 4; - return 0; -} - -inline int inlineUTF8SequenceLength(char b0) { - return isASCII(b0) ? 1 : inlineUTF8SequenceLengthNonASCII(b0); -} - -// Once the bits are split out into bytes of UTF-8, this is a mask OR-ed -// into the first byte, depending on how many bytes follow. There are -// as many entries in this table as there are UTF-8 sequence types. -// (I.e., one byte sequence, two byte... etc.). Remember that sequences -// for *legal* UTF-8 will be 4 or fewer bytes total. -static const unsigned char firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, - 0xF0, 0xF8, 0xFC}; - -typedef enum { - conversionOK, // conversion successful - sourceExhausted, // partial character in source, but hit end - targetExhausted, // insuff. room in target for conversion - sourceIllegal // source sequence is illegal/malformed -} ConversionResult; - -ConversionResult convertUTF16ToUTF8(const UChar** sourceStart, - const UChar* sourceEnd, char** targetStart, - char* targetEnd, bool strict) { - ConversionResult result = conversionOK; - const UChar* source = *sourceStart; - char* target = *targetStart; - while (source < sourceEnd) { - UChar32 ch; - uint32_t bytesToWrite = 0; - const UChar32 byteMask = 0xBF; - const UChar32 byteMark = 0x80; - const UChar* oldSource = - source; // In case we have to back up because of target overflow. - ch = static_cast(*source++); - // If we have a surrogate pair, convert to UChar32 first. - if (ch >= 0xD800 && ch <= 0xDBFF) { - // If the 16 bits following the high surrogate are in the source buffer... - if (source < sourceEnd) { - UChar32 ch2 = static_cast(*source); - // If it's a low surrogate, convert to UChar32. - if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) { - ch = ((ch - 0xD800) << 10) + (ch2 - 0xDC00) + 0x0010000; - ++source; - } else if (strict) { // it's an unpaired high surrogate - --source; // return to the illegal value itself - result = sourceIllegal; - break; - } - } else { // We don't have the 16 bits following the high surrogate. - --source; // return to the high surrogate - result = sourceExhausted; - break; - } - } else if (strict) { - // UTF-16 surrogate values are illegal in UTF-32 - if (ch >= 0xDC00 && ch <= 0xDFFF) { - --source; // return to the illegal value itself - result = sourceIllegal; - break; - } - } - // Figure out how many bytes the result will require - if (ch < (UChar32)0x80) { - bytesToWrite = 1; - } else if (ch < (UChar32)0x800) { - bytesToWrite = 2; - } else if (ch < (UChar32)0x10000) { - bytesToWrite = 3; - } else if (ch < (UChar32)0x110000) { - bytesToWrite = 4; - } else { - bytesToWrite = 3; - ch = replacementCharacter; - } - - target += bytesToWrite; - if (target > targetEnd) { - source = oldSource; // Back up source pointer! - target -= bytesToWrite; - result = targetExhausted; - break; - } - switch (bytesToWrite) { // note: everything falls through. - case 4: - *--target = static_cast((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--target = static_cast((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--target = static_cast((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--target = static_cast(ch | firstByteMark[bytesToWrite]); - } - target += bytesToWrite; - } - *sourceStart = source; - *targetStart = target; - return result; -} - -/** - * Is this code point a BMP code point (U+0000..U+ffff)? - * @param c 32-bit code point - * @return TRUE or FALSE - * @stable ICU 2.8 - */ -#define U_IS_BMP(c) ((uint32_t)(c) <= 0xffff) - -/** - * Is this code point a supplementary code point (U+10000..U+10ffff)? - * @param c 32-bit code point - * @return TRUE or FALSE - * @stable ICU 2.8 - */ -#define U_IS_SUPPLEMENTARY(c) ((uint32_t)((c)-0x10000) <= 0xfffff) - -/** - * Is this code point a surrogate (U+d800..U+dfff)? - * @param c 32-bit code point - * @return TRUE or FALSE - * @stable ICU 2.4 - */ -#define U_IS_SURROGATE(c) (((c)&0xfffff800) == 0xd800) - -/** - * Get the lead surrogate (0xd800..0xdbff) for a - * supplementary code point (0x10000..0x10ffff). - * @param supplementary 32-bit code point (U+10000..U+10ffff) - * @return lead surrogate (U+d800..U+dbff) for supplementary - * @stable ICU 2.4 - */ -#define U16_LEAD(supplementary) (UChar)(((supplementary) >> 10) + 0xd7c0) - -/** - * Get the trail surrogate (0xdc00..0xdfff) for a - * supplementary code point (0x10000..0x10ffff). - * @param supplementary 32-bit code point (U+10000..U+10ffff) - * @return trail surrogate (U+dc00..U+dfff) for supplementary - * @stable ICU 2.4 - */ -#define U16_TRAIL(supplementary) (UChar)(((supplementary)&0x3ff) | 0xdc00) - -// This must be called with the length pre-determined by the first byte. -// If presented with a length > 4, this returns false. The Unicode -// definition of UTF-8 goes up to 4-byte sequences. -static bool isLegalUTF8(const unsigned char* source, int length) { - unsigned char a; - const unsigned char* srcptr = source + length; - switch (length) { - default: - return false; - // Everything else falls through when "true"... - case 4: - if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; - case 3: - if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false; - case 2: - if ((a = (*--srcptr)) > 0xBF) return false; - - // no fall-through in this inner switch - switch (*source) { - case 0xE0: - if (a < 0xA0) return false; - break; - case 0xED: - if (a > 0x9F) return false; - break; - case 0xF0: - if (a < 0x90) return false; - break; - case 0xF4: - if (a > 0x8F) return false; - break; - default: - if (a < 0x80) return false; - } - - case 1: - if (*source >= 0x80 && *source < 0xC2) return false; - } - if (*source > 0xF4) return false; - return true; -} - -// Magic values subtracted from a buffer value during UTF8 conversion. -// This table contains as many values as there might be trailing bytes -// in a UTF-8 sequence. -static const UChar32 offsetsFromUTF8[6] = {0x00000000UL, - 0x00003080UL, - 0x000E2080UL, - 0x03C82080UL, - static_cast(0xFA082080UL), - static_cast(0x82082080UL)}; - -static inline UChar32 readUTF8Sequence(const char*& sequence, size_t length) { - UChar32 character = 0; - - // The cases all fall through. - switch (length) { - case 6: - character += static_cast(*sequence++); - character <<= 6; - case 5: - character += static_cast(*sequence++); - character <<= 6; - case 4: - character += static_cast(*sequence++); - character <<= 6; - case 3: - character += static_cast(*sequence++); - character <<= 6; - case 2: - character += static_cast(*sequence++); - character <<= 6; - case 1: - character += static_cast(*sequence++); - } - - return character - offsetsFromUTF8[length - 1]; -} - -ConversionResult convertUTF8ToUTF16(const char** sourceStart, - const char* sourceEnd, UChar** targetStart, - UChar* targetEnd, bool* sourceAllASCII, - bool strict) { - ConversionResult result = conversionOK; - const char* source = *sourceStart; - UChar* target = *targetStart; - UChar orAllData = 0; - while (source < sourceEnd) { - int utf8SequenceLength = inlineUTF8SequenceLength(*source); - if (sourceEnd - source < utf8SequenceLength) { - result = sourceExhausted; - break; - } - // Do this check whether lenient or strict - if (!isLegalUTF8(reinterpret_cast(source), - utf8SequenceLength)) { - result = sourceIllegal; - break; - } - - UChar32 character = readUTF8Sequence(source, utf8SequenceLength); - - if (target >= targetEnd) { - source -= utf8SequenceLength; // Back up source pointer! - result = targetExhausted; - break; - } - - if (U_IS_BMP(character)) { - // UTF-16 surrogate values are illegal in UTF-32 - if (U_IS_SURROGATE(character)) { - if (strict) { - source -= utf8SequenceLength; // return to the illegal value itself - result = sourceIllegal; - break; - } - *target++ = replacementCharacter; - orAllData |= replacementCharacter; - } else { - *target++ = static_cast(character); // normal case - orAllData |= character; - } - } else if (U_IS_SUPPLEMENTARY(character)) { - // target is a character in range 0xFFFF - 0x10FFFF - if (target + 1 >= targetEnd) { - source -= utf8SequenceLength; // Back up source pointer! - result = targetExhausted; - break; - } - *target++ = U16_LEAD(character); - *target++ = U16_TRAIL(character); - orAllData = 0xffff; - } else { - if (strict) { - source -= utf8SequenceLength; // return to the start - result = sourceIllegal; - break; // Bail out; shouldn't continue - } else { - *target++ = replacementCharacter; - orAllData |= replacementCharacter; - } - } - } - *sourceStart = source; - *targetStart = target; - - if (sourceAllASCII) *sourceAllASCII = !(orAllData & ~0x7f); - - return result; -} - -// Helper to write a three-byte UTF-8 code point to the buffer, caller must -// check room is available. -static inline void putUTF8Triple(char*& buffer, UChar ch) { - *buffer++ = static_cast(((ch >> 12) & 0x0F) | 0xE0); - *buffer++ = static_cast(((ch >> 6) & 0x3F) | 0x80); - *buffer++ = static_cast((ch & 0x3F) | 0x80); -} - -} // namespace - -// static -String16 String16::fromInteger(int number) { - const size_t kBufferSize = 50; - char buffer[kBufferSize]; - v8::base::OS::SNPrintF(buffer, kBufferSize, "%d", number); - return String16(buffer); -} - -// static -String16 String16::fromInteger(size_t number) { - const size_t kBufferSize = 50; - char buffer[kBufferSize]; - v8::base::OS::SNPrintF(buffer, kBufferSize, "%zu", number); - return String16(buffer); -} - -// static -String16 String16::fromDouble(double number) { - const size_t kBufferSize = 100; - char buffer[kBufferSize]; - v8::base::OS::SNPrintF(buffer, kBufferSize, "%f", number); - return String16(buffer); -} - -// static -String16 String16::fromDoublePrecision3(double number) { - const size_t kBufferSize = 100; - char buffer[kBufferSize]; - v8::base::OS::SNPrintF(buffer, kBufferSize, "%.3g", number); - return String16(buffer); -} - -// static -String16 String16::fromDoublePrecision6(double number) { - const size_t kBufferSize = 100; - char buffer[kBufferSize]; - v8::base::OS::SNPrintF(buffer, kBufferSize, "%.6g", number); - return String16(buffer); -} - -int String16::toInteger(bool* ok) const { - return charactersToInteger(characters16(), length(), ok); -} - -String16 String16::stripWhiteSpace() const { - if (!length()) return String16(); - - size_t start = 0; - size_t end = length() - 1; - - // skip white space from start - while (start <= end && isSpaceOrNewLine(characters16()[start])) ++start; - - // only white space - if (start > end) return String16(); - - // skip white space from end - while (end && isSpaceOrNewLine(characters16()[end])) --end; - - if (!start && end == length() - 1) return *this; - return String16(characters16() + start, end + 1 - start); -} - -String16Builder::String16Builder() {} - -void String16Builder::append(const String16& s) { - m_buffer.insert(m_buffer.end(), s.characters16(), - s.characters16() + s.length()); -} - -void String16Builder::append(UChar c) { m_buffer.push_back(c); } - -void String16Builder::append(char c) { - UChar u = c; - m_buffer.push_back(u); -} - -void String16Builder::append(const UChar* characters, size_t length) { - m_buffer.insert(m_buffer.end(), characters, characters + length); -} - -void String16Builder::append(const char* characters, size_t length) { - m_buffer.insert(m_buffer.end(), characters, characters + length); -} - -String16 String16Builder::toString() { - return String16(m_buffer.data(), m_buffer.size()); -} - -void String16Builder::reserveCapacity(size_t capacity) { - m_buffer.reserve(capacity); -} - -String16 String16::fromUTF8(const char* stringStart, size_t length) { - if (!stringStart || !length) return String16(); - - std::vector buffer(length); - UChar* bufferStart = buffer.data(); - - UChar* bufferCurrent = bufferStart; - const char* stringCurrent = stringStart; - if (convertUTF8ToUTF16(&stringCurrent, stringStart + length, &bufferCurrent, - bufferCurrent + buffer.size(), 0, - true) != conversionOK) - return String16(); - - size_t utf16Length = bufferCurrent - bufferStart; - return String16(bufferStart, utf16Length); -} - -std::string String16::utf8() const { - size_t length = this->length(); - - if (!length) return std::string(""); - - // Allocate a buffer big enough to hold all the characters - // (an individual UTF-16 UChar can only expand to 3 UTF-8 bytes). - // Optimization ideas, if we find this function is hot: - // * We could speculatively create a CStringBuffer to contain 'length' - // characters, and resize if necessary (i.e. if the buffer contains - // non-ascii characters). (Alternatively, scan the buffer first for - // ascii characters, so we know this will be sufficient). - // * We could allocate a CStringBuffer with an appropriate size to - // have a good chance of being able to write the string into the - // buffer without reallocing (say, 1.5 x length). - if (length > std::numeric_limits::max() / 3) return std::string(); - std::vector bufferVector(length * 3); - char* buffer = bufferVector.data(); - const UChar* characters = m_impl.data(); - - ConversionResult result = - convertUTF16ToUTF8(&characters, characters + length, &buffer, - buffer + bufferVector.size(), false); - DCHECK( - result != - targetExhausted); // (length * 3) should be sufficient for any conversion - - // Only produced from strict conversion. - DCHECK(result != sourceIllegal); - - // Check for an unconverted high surrogate. - if (result == sourceExhausted) { - // This should be one unpaired high surrogate. Treat it the same - // was as an unpaired high surrogate would have been handled in - // the middle of a string with non-strict conversion - which is - // to say, simply encode it to UTF-8. - DCHECK((characters + 1) == (m_impl.data() + length)); - DCHECK((*characters >= 0xD800) && (*characters <= 0xDBFF)); - // There should be room left, since one UChar hasn't been - // converted. - DCHECK((buffer + 3) <= (buffer + bufferVector.size())); - putUTF8Triple(buffer, *characters); - } - - return std::string(bufferVector.data(), buffer - bufferVector.data()); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/string-16.h b/deps/v8_inspector/src/inspector/string-16.h deleted file mode 100644 index 94069479579faf..00000000000000 --- a/deps/v8_inspector/src/inspector/string-16.h +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_STRING16_H_ -#define V8_INSPECTOR_STRING16_H_ - -#include -#include -#include -#include -#include -#include - -namespace v8_inspector { - -using UChar = uint16_t; - -class String16 { - public: - static const size_t kNotFound = static_cast(-1); - - String16() {} - String16(const String16& other) : m_impl(other.m_impl) {} - String16(const UChar* characters, size_t size) : m_impl(characters, size) {} - String16(const UChar* characters) // NOLINT(runtime/explicit) - : m_impl(characters) {} - String16(const char* characters) // NOLINT(runtime/explicit) - : String16(characters, std::strlen(characters)) {} - String16(const char* characters, size_t size) { - m_impl.resize(size); - for (size_t i = 0; i < size; ++i) m_impl[i] = characters[i]; - } - - static String16 fromInteger(int); - static String16 fromInteger(size_t); - static String16 fromDouble(double); - static String16 fromDoublePrecision3(double); - static String16 fromDoublePrecision6(double); - - int toInteger(bool* ok = nullptr) const; - String16 stripWhiteSpace() const; - const UChar* characters16() const { return m_impl.c_str(); } - size_t length() const { return m_impl.length(); } - bool isEmpty() const { return !m_impl.length(); } - UChar operator[](size_t index) const { return m_impl[index]; } - String16 substring(size_t pos, size_t len = UINT_MAX) const { - return String16(m_impl.substr(pos, len)); - } - size_t find(const String16& str, size_t start = 0) const { - return m_impl.find(str.m_impl, start); - } - size_t reverseFind(const String16& str, size_t start = UINT_MAX) const { - return m_impl.rfind(str.m_impl, start); - } - void swap(String16& other) { m_impl.swap(other.m_impl); } - - // Convenience methods. - std::string utf8() const; - static String16 fromUTF8(const char* stringStart, size_t length); - - const std::basic_string& impl() const { return m_impl; } - explicit String16(const std::basic_string& impl) : m_impl(impl) {} - - std::size_t hash() const { - if (!has_hash) { - size_t hash = 0; - for (size_t i = 0; i < length(); ++i) hash = 31 * hash + m_impl[i]; - hash_code = hash; - has_hash = true; - } - return hash_code; - } - - private: - std::basic_string m_impl; - mutable bool has_hash = false; - mutable std::size_t hash_code = 0; -}; - -inline bool operator==(const String16& a, const String16& b) { - return a.impl() == b.impl(); -} -inline bool operator<(const String16& a, const String16& b) { - return a.impl() < b.impl(); -} -inline bool operator!=(const String16& a, const String16& b) { - return a.impl() != b.impl(); -} -inline bool operator==(const String16& a, const char* b) { - return a.impl() == String16(b).impl(); -} -inline String16 operator+(const String16& a, const char* b) { - return String16(a.impl() + String16(b).impl()); -} -inline String16 operator+(const char* a, const String16& b) { - return String16(String16(a).impl() + b.impl()); -} -inline String16 operator+(const String16& a, const String16& b) { - return String16(a.impl() + b.impl()); -} - -class String16Builder { - public: - String16Builder(); - void append(const String16&); - void append(UChar); - void append(char); - void append(const UChar*, size_t); - void append(const char*, size_t); - String16 toString(); - void reserveCapacity(size_t); - - private: - std::vector m_buffer; -}; - -} // namespace v8_inspector - -#if !defined(__APPLE__) || defined(_LIBCPP_VERSION) - -namespace std { -template <> -struct hash { - std::size_t operator()(const v8_inspector::String16& string) const { - return string.hash(); - } -}; - -} // namespace std - -#endif // !defined(__APPLE__) || defined(_LIBCPP_VERSION) - -#endif // V8_INSPECTOR_STRING16_H_ diff --git a/deps/v8_inspector/src/inspector/string-util.cc b/deps/v8_inspector/src/inspector/string-util.cc deleted file mode 100644 index e6b83a5d7db6f8..00000000000000 --- a/deps/v8_inspector/src/inspector/string-util.cc +++ /dev/null @@ -1,218 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/string-util.h" - -#include "src/inspector/protocol/Protocol.h" - -namespace v8_inspector { - -v8::Local toV8String(v8::Isolate* isolate, const String16& string) { - if (string.isEmpty()) return v8::String::Empty(isolate); - DCHECK(string.length() < v8::String::kMaxLength); - return v8::String::NewFromTwoByte( - isolate, reinterpret_cast(string.characters16()), - v8::NewStringType::kNormal, static_cast(string.length())) - .ToLocalChecked(); -} - -v8::Local toV8StringInternalized(v8::Isolate* isolate, - const String16& string) { - if (string.isEmpty()) return v8::String::Empty(isolate); - DCHECK(string.length() < v8::String::kMaxLength); - return v8::String::NewFromTwoByte( - isolate, reinterpret_cast(string.characters16()), - v8::NewStringType::kInternalized, - static_cast(string.length())) - .ToLocalChecked(); -} - -v8::Local toV8StringInternalized(v8::Isolate* isolate, - const char* str) { - return v8::String::NewFromUtf8(isolate, str, v8::NewStringType::kInternalized) - .ToLocalChecked(); -} - -v8::Local toV8String(v8::Isolate* isolate, - const StringView& string) { - if (!string.length()) return v8::String::Empty(isolate); - DCHECK(string.length() < v8::String::kMaxLength); - if (string.is8Bit()) - return v8::String::NewFromOneByte( - isolate, reinterpret_cast(string.characters8()), - v8::NewStringType::kNormal, static_cast(string.length())) - .ToLocalChecked(); - return v8::String::NewFromTwoByte( - isolate, reinterpret_cast(string.characters16()), - v8::NewStringType::kNormal, static_cast(string.length())) - .ToLocalChecked(); -} - -String16 toProtocolString(v8::Local value) { - if (value.IsEmpty() || value->IsNull() || value->IsUndefined()) - return String16(); - std::unique_ptr buffer(new UChar[value->Length()]); - value->Write(reinterpret_cast(buffer.get()), 0, value->Length()); - return String16(buffer.get(), value->Length()); -} - -String16 toProtocolStringWithTypeCheck(v8::Local value) { - if (value.IsEmpty() || !value->IsString()) return String16(); - return toProtocolString(value.As()); -} - -String16 toString16(const StringView& string) { - if (!string.length()) return String16(); - if (string.is8Bit()) - return String16(reinterpret_cast(string.characters8()), - string.length()); - return String16(reinterpret_cast(string.characters16()), - string.length()); -} - -StringView toStringView(const String16& string) { - if (string.isEmpty()) return StringView(); - return StringView(reinterpret_cast(string.characters16()), - string.length()); -} - -bool stringViewStartsWith(const StringView& string, const char* prefix) { - if (!string.length()) return !(*prefix); - if (string.is8Bit()) { - for (size_t i = 0, j = 0; prefix[j] && i < string.length(); ++i, ++j) { - if (string.characters8()[i] != prefix[j]) return false; - } - } else { - for (size_t i = 0, j = 0; prefix[j] && i < string.length(); ++i, ++j) { - if (string.characters16()[i] != prefix[j]) return false; - } - } - return true; -} - -namespace protocol { - -std::unique_ptr parseJSON(const StringView& string) { - if (!string.length()) return nullptr; - if (string.is8Bit()) { - return protocol::parseJSON(string.characters8(), - static_cast(string.length())); - } - return protocol::parseJSON(string.characters16(), - static_cast(string.length())); -} - -std::unique_ptr parseJSON(const String16& string) { - if (!string.length()) return nullptr; - return protocol::parseJSON(string.characters16(), - static_cast(string.length())); -} - -} // namespace protocol - -std::unique_ptr toProtocolValue(protocol::String* errorString, - v8::Local context, - v8::Local value, - int maxDepth) { - if (value.IsEmpty()) { - UNREACHABLE(); - return nullptr; - } - - if (!maxDepth) { - *errorString = "Object reference chain is too long"; - return nullptr; - } - maxDepth--; - - if (value->IsNull() || value->IsUndefined()) return protocol::Value::null(); - if (value->IsBoolean()) - return protocol::FundamentalValue::create(value.As()->Value()); - if (value->IsNumber()) { - double doubleValue = value.As()->Value(); - int intValue = static_cast(doubleValue); - if (intValue == doubleValue) - return protocol::FundamentalValue::create(intValue); - return protocol::FundamentalValue::create(doubleValue); - } - if (value->IsString()) - return protocol::StringValue::create( - toProtocolString(value.As())); - if (value->IsArray()) { - v8::Local array = value.As(); - std::unique_ptr inspectorArray = - protocol::ListValue::create(); - uint32_t length = array->Length(); - for (uint32_t i = 0; i < length; i++) { - v8::Local value; - if (!array->Get(context, i).ToLocal(&value)) { - *errorString = "Internal error"; - return nullptr; - } - std::unique_ptr element = - toProtocolValue(errorString, context, value, maxDepth); - if (!element) return nullptr; - inspectorArray->pushValue(std::move(element)); - } - return std::move(inspectorArray); - } - if (value->IsObject()) { - std::unique_ptr jsonObject = - protocol::DictionaryValue::create(); - v8::Local object = v8::Local::Cast(value); - v8::Local propertyNames; - if (!object->GetPropertyNames(context).ToLocal(&propertyNames)) { - *errorString = "Internal error"; - return nullptr; - } - uint32_t length = propertyNames->Length(); - for (uint32_t i = 0; i < length; i++) { - v8::Local name; - if (!propertyNames->Get(context, i).ToLocal(&name)) { - *errorString = "Internal error"; - return nullptr; - } - // FIXME(yurys): v8::Object should support GetOwnPropertyNames - if (name->IsString()) { - v8::Maybe hasRealNamedProperty = object->HasRealNamedProperty( - context, v8::Local::Cast(name)); - if (!hasRealNamedProperty.IsJust() || !hasRealNamedProperty.FromJust()) - continue; - } - v8::Local propertyName; - if (!name->ToString(context).ToLocal(&propertyName)) continue; - v8::Local property; - if (!object->Get(context, name).ToLocal(&property)) { - *errorString = "Internal error"; - return nullptr; - } - std::unique_ptr propertyValue = - toProtocolValue(errorString, context, property, maxDepth); - if (!propertyValue) return nullptr; - jsonObject->setValue(toProtocolString(propertyName), - std::move(propertyValue)); - } - return std::move(jsonObject); - } - *errorString = "Object couldn't be returned by value"; - return nullptr; -} - -// static -std::unique_ptr StringBuffer::create(const StringView& string) { - String16 owner = toString16(string); - return StringBufferImpl::adopt(owner); -} - -// static -std::unique_ptr StringBufferImpl::adopt(String16& string) { - return wrapUnique(new StringBufferImpl(string)); -} - -StringBufferImpl::StringBufferImpl(String16& string) { - m_owner.swap(string); - m_string = toStringView(m_owner); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/string-util.h b/deps/v8_inspector/src/inspector/string-util.h deleted file mode 100644 index 30137b8b786f97..00000000000000 --- a/deps/v8_inspector/src/inspector/string-util.h +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_STRINGUTIL_H_ -#define V8_INSPECTOR_STRINGUTIL_H_ - -#include "src/base/macros.h" -#include "src/inspector/string-16.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -namespace protocol { - -class Value; - -using String = v8_inspector::String16; -using StringBuilder = v8_inspector::String16Builder; - -class StringUtil { - public: - static String substring(const String& s, size_t pos, size_t len) { - return s.substring(pos, len); - } - static String fromInteger(int number) { return String::fromInteger(number); } - static String fromInteger(size_t number) { - return String::fromInteger(number); - } - static String fromDouble(double number) { return String::fromDouble(number); } - static const size_t kNotFound = String::kNotFound; - static void builderReserve(StringBuilder& builder, size_t capacity) { - builder.reserveCapacity(capacity); - } -}; - -std::unique_ptr parseJSON(const StringView& json); -std::unique_ptr parseJSON(const String16& json); - -} // namespace protocol - -std::unique_ptr toProtocolValue(protocol::String* errorString, - v8::Local, - v8::Local, - int maxDepth = 1000); - -v8::Local toV8String(v8::Isolate*, const String16&); -v8::Local toV8StringInternalized(v8::Isolate*, const String16&); -v8::Local toV8StringInternalized(v8::Isolate*, const char*); -v8::Local toV8String(v8::Isolate*, const StringView&); -// TODO(dgozman): rename to toString16. -String16 toProtocolString(v8::Local); -String16 toProtocolStringWithTypeCheck(v8::Local); -String16 toString16(const StringView&); -StringView toStringView(const String16&); -bool stringViewStartsWith(const StringView&, const char*); - -class StringBufferImpl : public StringBuffer { - public: - // Destroys string's content. - static std::unique_ptr adopt(String16&); - const StringView& string() override { return m_string; } - - private: - explicit StringBufferImpl(String16&); - String16 m_owner; - StringView m_string; - - DISALLOW_COPY_AND_ASSIGN(StringBufferImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_STRINGUTIL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-console-agent-impl.cc b/deps/v8_inspector/src/inspector/v8-console-agent-impl.cc deleted file mode 100644 index 8eb883cb754c44..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-console-agent-impl.cc +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-console-agent-impl.h" - -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/v8-console-message.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" - -namespace v8_inspector { - -namespace ConsoleAgentState { -static const char consoleEnabled[] = "consoleEnabled"; -} - -V8ConsoleAgentImpl::V8ConsoleAgentImpl( - V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, - protocol::DictionaryValue* state) - : m_session(session), - m_state(state), - m_frontend(frontendChannel), - m_enabled(false) {} - -V8ConsoleAgentImpl::~V8ConsoleAgentImpl() {} - -void V8ConsoleAgentImpl::enable(ErrorString* errorString) { - if (m_enabled) return; - m_state->setBoolean(ConsoleAgentState::consoleEnabled, true); - m_enabled = true; - m_session->inspector()->enableStackCapturingIfNeeded(); - reportAllMessages(); -} - -void V8ConsoleAgentImpl::disable(ErrorString* errorString) { - if (!m_enabled) return; - m_session->inspector()->disableStackCapturingIfNeeded(); - m_state->setBoolean(ConsoleAgentState::consoleEnabled, false); - m_enabled = false; -} - -void V8ConsoleAgentImpl::clearMessages(ErrorString* errorString) {} - -void V8ConsoleAgentImpl::restore() { - if (!m_state->booleanProperty(ConsoleAgentState::consoleEnabled, false)) - return; - ErrorString ignored; - enable(&ignored); -} - -void V8ConsoleAgentImpl::messageAdded(V8ConsoleMessage* message) { - if (m_enabled) reportMessage(message, true); -} - -bool V8ConsoleAgentImpl::enabled() { return m_enabled; } - -void V8ConsoleAgentImpl::reportAllMessages() { - V8ConsoleMessageStorage* storage = - m_session->inspector()->ensureConsoleMessageStorage( - m_session->contextGroupId()); - for (const auto& message : storage->messages()) { - if (message->origin() == V8MessageOrigin::kConsole) { - if (!reportMessage(message.get(), false)) return; - } - } -} - -bool V8ConsoleAgentImpl::reportMessage(V8ConsoleMessage* message, - bool generatePreview) { - DCHECK(message->origin() == V8MessageOrigin::kConsole); - message->reportToFrontend(&m_frontend); - m_frontend.flush(); - return m_session->inspector()->hasConsoleMessageStorage( - m_session->contextGroupId()); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-console-agent-impl.h b/deps/v8_inspector/src/inspector/v8-console-agent-impl.h deleted file mode 100644 index f3d598bb3494fb..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-console-agent-impl.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8CONSOLEAGENTIMPL_H_ -#define V8_INSPECTOR_V8CONSOLEAGENTIMPL_H_ - -#include "src/base/macros.h" -#include "src/inspector/protocol/Console.h" -#include "src/inspector/protocol/Forward.h" - -namespace v8_inspector { - -class V8ConsoleMessage; -class V8InspectorSessionImpl; - -using protocol::ErrorString; - -class V8ConsoleAgentImpl : public protocol::Console::Backend { - public: - V8ConsoleAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, - protocol::DictionaryValue* state); - ~V8ConsoleAgentImpl() override; - - void enable(ErrorString*) override; - void disable(ErrorString*) override; - void clearMessages(ErrorString*) override; - - void restore(); - void messageAdded(V8ConsoleMessage*); - void reset(); - bool enabled(); - - private: - void reportAllMessages(); - bool reportMessage(V8ConsoleMessage*, bool generatePreview); - - V8InspectorSessionImpl* m_session; - protocol::DictionaryValue* m_state; - protocol::Console::Frontend m_frontend; - bool m_enabled; - - DISALLOW_COPY_AND_ASSIGN(V8ConsoleAgentImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8CONSOLEAGENTIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-console-message.cc b/deps/v8_inspector/src/inspector/v8-console-message.cc deleted file mode 100644 index 87c9d68d9b3514..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-console-message.cc +++ /dev/null @@ -1,473 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-console-message.h" - -#include "src/inspector/inspected-context.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console-agent-impl.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-runtime-agent-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -namespace { - -String16 consoleAPITypeValue(ConsoleAPIType type) { - switch (type) { - case ConsoleAPIType::kLog: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log; - case ConsoleAPIType::kDebug: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug; - case ConsoleAPIType::kInfo: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Info; - case ConsoleAPIType::kError: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Error; - case ConsoleAPIType::kWarning: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Warning; - case ConsoleAPIType::kClear: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Clear; - case ConsoleAPIType::kDir: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dir; - case ConsoleAPIType::kDirXML: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Dirxml; - case ConsoleAPIType::kTable: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Table; - case ConsoleAPIType::kTrace: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Trace; - case ConsoleAPIType::kStartGroup: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroup; - case ConsoleAPIType::kStartGroupCollapsed: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::StartGroupCollapsed; - case ConsoleAPIType::kEndGroup: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::EndGroup; - case ConsoleAPIType::kAssert: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Assert; - case ConsoleAPIType::kTimeEnd: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug; - case ConsoleAPIType::kCount: - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Debug; - } - return protocol::Runtime::ConsoleAPICalled::TypeEnum::Log; -} - -const unsigned maxConsoleMessageCount = 1000; -const unsigned maxArrayItemsLimit = 10000; -const unsigned maxStackDepthLimit = 32; - -class V8ValueStringBuilder { - public: - static String16 toString(v8::Local value, - v8::Local context) { - V8ValueStringBuilder builder(context); - if (!builder.append(value)) return String16(); - return builder.toString(); - } - - private: - enum { - IgnoreNull = 1 << 0, - IgnoreUndefined = 1 << 1, - }; - - explicit V8ValueStringBuilder(v8::Local context) - : m_arrayLimit(maxArrayItemsLimit), - m_isolate(context->GetIsolate()), - m_tryCatch(context->GetIsolate()), - m_context(context) {} - - bool append(v8::Local value, unsigned ignoreOptions = 0) { - if (value.IsEmpty()) return true; - if ((ignoreOptions & IgnoreNull) && value->IsNull()) return true; - if ((ignoreOptions & IgnoreUndefined) && value->IsUndefined()) return true; - if (value->IsString()) return append(v8::Local::Cast(value)); - if (value->IsStringObject()) - return append(v8::Local::Cast(value)->ValueOf()); - if (value->IsSymbol()) return append(v8::Local::Cast(value)); - if (value->IsSymbolObject()) - return append(v8::Local::Cast(value)->ValueOf()); - if (value->IsNumberObject()) { - m_builder.append(String16::fromDoublePrecision6( - v8::Local::Cast(value)->ValueOf())); - return true; - } - if (value->IsBooleanObject()) { - m_builder.append(v8::Local::Cast(value)->ValueOf() - ? "true" - : "false"); - return true; - } - if (value->IsArray()) return append(v8::Local::Cast(value)); - if (value->IsProxy()) { - m_builder.append("[object Proxy]"); - return true; - } - if (value->IsObject() && !value->IsDate() && !value->IsFunction() && - !value->IsNativeError() && !value->IsRegExp()) { - v8::Local object = v8::Local::Cast(value); - v8::Local stringValue; - if (object->ObjectProtoToString(m_isolate->GetCurrentContext()) - .ToLocal(&stringValue)) - return append(stringValue); - } - v8::Local stringValue; - if (!value->ToString(m_isolate->GetCurrentContext()).ToLocal(&stringValue)) - return false; - return append(stringValue); - } - - bool append(v8::Local array) { - for (const auto& it : m_visitedArrays) { - if (it == array) return true; - } - uint32_t length = array->Length(); - if (length > m_arrayLimit) return false; - if (m_visitedArrays.size() > maxStackDepthLimit) return false; - - bool result = true; - m_arrayLimit -= length; - m_visitedArrays.push_back(array); - for (uint32_t i = 0; i < length; ++i) { - if (i) m_builder.append(','); - v8::Local value; - if (!array->Get(m_context, i).ToLocal(&value)) continue; - if (!append(value, IgnoreNull | IgnoreUndefined)) { - result = false; - break; - } - } - m_visitedArrays.pop_back(); - return result; - } - - bool append(v8::Local symbol) { - m_builder.append("Symbol("); - bool result = append(symbol->Name(), IgnoreUndefined); - m_builder.append(')'); - return result; - } - - bool append(v8::Local string) { - if (m_tryCatch.HasCaught()) return false; - if (!string.IsEmpty()) m_builder.append(toProtocolString(string)); - return true; - } - - String16 toString() { - if (m_tryCatch.HasCaught()) return String16(); - return m_builder.toString(); - } - - uint32_t m_arrayLimit; - v8::Isolate* m_isolate; - String16Builder m_builder; - std::vector> m_visitedArrays; - v8::TryCatch m_tryCatch; - v8::Local m_context; -}; - -} // namespace - -V8ConsoleMessage::V8ConsoleMessage(V8MessageOrigin origin, double timestamp, - const String16& message) - : m_origin(origin), - m_timestamp(timestamp), - m_message(message), - m_lineNumber(0), - m_columnNumber(0), - m_scriptId(0), - m_contextId(0), - m_type(ConsoleAPIType::kLog), - m_exceptionId(0), - m_revokedExceptionId(0) {} - -V8ConsoleMessage::~V8ConsoleMessage() {} - -void V8ConsoleMessage::setLocation(const String16& url, unsigned lineNumber, - unsigned columnNumber, - std::unique_ptr stackTrace, - int scriptId) { - m_url = url; - m_lineNumber = lineNumber; - m_columnNumber = columnNumber; - m_stackTrace = std::move(stackTrace); - m_scriptId = scriptId; -} - -void V8ConsoleMessage::reportToFrontend( - protocol::Console::Frontend* frontend) const { - DCHECK(m_origin == V8MessageOrigin::kConsole); - String16 level = protocol::Console::ConsoleMessage::LevelEnum::Log; - if (m_type == ConsoleAPIType::kDebug || m_type == ConsoleAPIType::kCount || - m_type == ConsoleAPIType::kTimeEnd) - level = protocol::Console::ConsoleMessage::LevelEnum::Debug; - else if (m_type == ConsoleAPIType::kError || - m_type == ConsoleAPIType::kAssert) - level = protocol::Console::ConsoleMessage::LevelEnum::Error; - else if (m_type == ConsoleAPIType::kWarning) - level = protocol::Console::ConsoleMessage::LevelEnum::Warning; - else if (m_type == ConsoleAPIType::kInfo) - level = protocol::Console::ConsoleMessage::LevelEnum::Info; - std::unique_ptr result = - protocol::Console::ConsoleMessage::create() - .setSource(protocol::Console::ConsoleMessage::SourceEnum::ConsoleApi) - .setLevel(level) - .setText(m_message) - .build(); - result->setLine(static_cast(m_lineNumber)); - result->setColumn(static_cast(m_columnNumber)); - result->setUrl(m_url); - frontend->messageAdded(std::move(result)); -} - -std::unique_ptr> -V8ConsoleMessage::wrapArguments(V8InspectorSessionImpl* session, - bool generatePreview) const { - if (!m_arguments.size() || !m_contextId) return nullptr; - InspectedContext* inspectedContext = - session->inspector()->getContext(session->contextGroupId(), m_contextId); - if (!inspectedContext) return nullptr; - - v8::Isolate* isolate = inspectedContext->isolate(); - v8::HandleScope handles(isolate); - v8::Local context = inspectedContext->context(); - - std::unique_ptr> args = - protocol::Array::create(); - if (m_type == ConsoleAPIType::kTable && generatePreview) { - v8::Local table = m_arguments[0]->Get(isolate); - v8::Local columns = m_arguments.size() > 1 - ? m_arguments[1]->Get(isolate) - : v8::Local(); - std::unique_ptr wrapped = - session->wrapTable(context, table, columns); - if (wrapped) - args->addItem(std::move(wrapped)); - else - args = nullptr; - } else { - for (size_t i = 0; i < m_arguments.size(); ++i) { - std::unique_ptr wrapped = - session->wrapObject(context, m_arguments[i]->Get(isolate), "console", - generatePreview); - if (!wrapped) { - args = nullptr; - break; - } - args->addItem(std::move(wrapped)); - } - } - return args; -} - -void V8ConsoleMessage::reportToFrontend(protocol::Runtime::Frontend* frontend, - V8InspectorSessionImpl* session, - bool generatePreview) const { - if (m_origin == V8MessageOrigin::kException) { - std::unique_ptr exception = - wrapException(session, generatePreview); - std::unique_ptr exceptionDetails = - protocol::Runtime::ExceptionDetails::create() - .setExceptionId(m_exceptionId) - .setText(exception ? m_message : m_detailedMessage) - .setLineNumber(m_lineNumber ? m_lineNumber - 1 : 0) - .setColumnNumber(m_columnNumber ? m_columnNumber - 1 : 0) - .build(); - if (m_scriptId) - exceptionDetails->setScriptId(String16::fromInteger(m_scriptId)); - if (!m_url.isEmpty()) exceptionDetails->setUrl(m_url); - if (m_stackTrace) - exceptionDetails->setStackTrace(m_stackTrace->buildInspectorObjectImpl()); - if (m_contextId) exceptionDetails->setExecutionContextId(m_contextId); - if (exception) exceptionDetails->setException(std::move(exception)); - frontend->exceptionThrown(m_timestamp, std::move(exceptionDetails)); - return; - } - if (m_origin == V8MessageOrigin::kRevokedException) { - frontend->exceptionRevoked(m_message, m_revokedExceptionId); - return; - } - if (m_origin == V8MessageOrigin::kConsole) { - std::unique_ptr> - arguments = wrapArguments(session, generatePreview); - if (!arguments) { - arguments = protocol::Array::create(); - if (!m_message.isEmpty()) { - std::unique_ptr messageArg = - protocol::Runtime::RemoteObject::create() - .setType(protocol::Runtime::RemoteObject::TypeEnum::String) - .build(); - messageArg->setValue(protocol::StringValue::create(m_message)); - arguments->addItem(std::move(messageArg)); - } - } - frontend->consoleAPICalled( - consoleAPITypeValue(m_type), std::move(arguments), m_contextId, - m_timestamp, - m_stackTrace ? m_stackTrace->buildInspectorObjectImpl() : nullptr); - return; - } - UNREACHABLE(); -} - -std::unique_ptr -V8ConsoleMessage::wrapException(V8InspectorSessionImpl* session, - bool generatePreview) const { - if (!m_arguments.size() || !m_contextId) return nullptr; - DCHECK_EQ(1u, m_arguments.size()); - InspectedContext* inspectedContext = - session->inspector()->getContext(session->contextGroupId(), m_contextId); - if (!inspectedContext) return nullptr; - - v8::Isolate* isolate = inspectedContext->isolate(); - v8::HandleScope handles(isolate); - // TODO(dgozman): should we use different object group? - return session->wrapObject(inspectedContext->context(), - m_arguments[0]->Get(isolate), "console", - generatePreview); -} - -V8MessageOrigin V8ConsoleMessage::origin() const { return m_origin; } - -ConsoleAPIType V8ConsoleMessage::type() const { return m_type; } - -// static -std::unique_ptr V8ConsoleMessage::createForConsoleAPI( - double timestamp, ConsoleAPIType type, - const std::vector>& arguments, - std::unique_ptr stackTrace, - InspectedContext* inspectedContext) { - v8::Isolate* isolate = inspectedContext->isolate(); - int contextId = inspectedContext->contextId(); - int contextGroupId = inspectedContext->contextGroupId(); - V8InspectorImpl* inspector = inspectedContext->inspector(); - v8::Local context = inspectedContext->context(); - - std::unique_ptr message = wrapUnique( - new V8ConsoleMessage(V8MessageOrigin::kConsole, timestamp, String16())); - if (stackTrace && !stackTrace->isEmpty()) { - message->m_url = toString16(stackTrace->topSourceURL()); - message->m_lineNumber = stackTrace->topLineNumber(); - message->m_columnNumber = stackTrace->topColumnNumber(); - } - message->m_stackTrace = std::move(stackTrace); - message->m_type = type; - message->m_contextId = contextId; - for (size_t i = 0; i < arguments.size(); ++i) - message->m_arguments.push_back( - wrapUnique(new v8::Global(isolate, arguments.at(i)))); - if (arguments.size()) - message->m_message = V8ValueStringBuilder::toString(arguments[0], context); - - V8ConsoleAPIType clientType = V8ConsoleAPIType::kLog; - if (type == ConsoleAPIType::kDebug || type == ConsoleAPIType::kCount || - type == ConsoleAPIType::kTimeEnd) - clientType = V8ConsoleAPIType::kDebug; - else if (type == ConsoleAPIType::kError || type == ConsoleAPIType::kAssert) - clientType = V8ConsoleAPIType::kError; - else if (type == ConsoleAPIType::kWarning) - clientType = V8ConsoleAPIType::kWarning; - else if (type == ConsoleAPIType::kInfo) - clientType = V8ConsoleAPIType::kInfo; - else if (type == ConsoleAPIType::kClear) - clientType = V8ConsoleAPIType::kClear; - inspector->client()->consoleAPIMessage( - contextGroupId, clientType, toStringView(message->m_message), - toStringView(message->m_url), message->m_lineNumber, - message->m_columnNumber, message->m_stackTrace.get()); - - return message; -} - -// static -std::unique_ptr V8ConsoleMessage::createForException( - double timestamp, const String16& detailedMessage, const String16& url, - unsigned lineNumber, unsigned columnNumber, - std::unique_ptr stackTrace, int scriptId, - v8::Isolate* isolate, const String16& message, int contextId, - v8::Local exception, unsigned exceptionId) { - std::unique_ptr consoleMessage = wrapUnique( - new V8ConsoleMessage(V8MessageOrigin::kException, timestamp, message)); - consoleMessage->setLocation(url, lineNumber, columnNumber, - std::move(stackTrace), scriptId); - consoleMessage->m_exceptionId = exceptionId; - consoleMessage->m_detailedMessage = detailedMessage; - if (contextId && !exception.IsEmpty()) { - consoleMessage->m_contextId = contextId; - consoleMessage->m_arguments.push_back( - wrapUnique(new v8::Global(isolate, exception))); - } - return consoleMessage; -} - -// static -std::unique_ptr V8ConsoleMessage::createForRevokedException( - double timestamp, const String16& messageText, - unsigned revokedExceptionId) { - std::unique_ptr message = wrapUnique(new V8ConsoleMessage( - V8MessageOrigin::kRevokedException, timestamp, messageText)); - message->m_revokedExceptionId = revokedExceptionId; - return message; -} - -void V8ConsoleMessage::contextDestroyed(int contextId) { - if (contextId != m_contextId) return; - m_contextId = 0; - if (m_message.isEmpty()) m_message = ""; - Arguments empty; - m_arguments.swap(empty); -} - -// ------------------------ V8ConsoleMessageStorage ---------------------------- - -V8ConsoleMessageStorage::V8ConsoleMessageStorage(V8InspectorImpl* inspector, - int contextGroupId) - : m_inspector(inspector), - m_contextGroupId(contextGroupId), - m_expiredCount(0) {} - -V8ConsoleMessageStorage::~V8ConsoleMessageStorage() { clear(); } - -void V8ConsoleMessageStorage::addMessage( - std::unique_ptr message) { - int contextGroupId = m_contextGroupId; - V8InspectorImpl* inspector = m_inspector; - if (message->type() == ConsoleAPIType::kClear) clear(); - - V8InspectorSessionImpl* session = - inspector->sessionForContextGroup(contextGroupId); - if (session) { - if (message->origin() == V8MessageOrigin::kConsole) - session->consoleAgent()->messageAdded(message.get()); - session->runtimeAgent()->messageAdded(message.get()); - } - if (!inspector->hasConsoleMessageStorage(contextGroupId)) return; - - DCHECK(m_messages.size() <= maxConsoleMessageCount); - if (m_messages.size() == maxConsoleMessageCount) { - ++m_expiredCount; - m_messages.pop_front(); - } - m_messages.push_back(std::move(message)); -} - -void V8ConsoleMessageStorage::clear() { - m_messages.clear(); - m_expiredCount = 0; - if (V8InspectorSessionImpl* session = - m_inspector->sessionForContextGroup(m_contextGroupId)) - session->releaseObjectGroup("console"); -} - -void V8ConsoleMessageStorage::contextDestroyed(int contextId) { - for (size_t i = 0; i < m_messages.size(); ++i) - m_messages[i]->contextDestroyed(contextId); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-console-message.h b/deps/v8_inspector/src/inspector/v8-console-message.h deleted file mode 100644 index a6e9eafe2d983c..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-console-message.h +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8CONSOLEMESSAGE_H_ -#define V8_INSPECTOR_V8CONSOLEMESSAGE_H_ - -#include -#include "include/v8.h" -#include "src/inspector/protocol/Console.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Runtime.h" - -namespace v8_inspector { - -class InspectedContext; -class V8InspectorImpl; -class V8InspectorSessionImpl; -class V8StackTraceImpl; - -enum class V8MessageOrigin { kConsole, kException, kRevokedException }; - -enum class ConsoleAPIType { - kLog, - kDebug, - kInfo, - kError, - kWarning, - kDir, - kDirXML, - kTable, - kTrace, - kStartGroup, - kStartGroupCollapsed, - kEndGroup, - kClear, - kAssert, - kTimeEnd, - kCount -}; - -class V8ConsoleMessage { - public: - ~V8ConsoleMessage(); - - static std::unique_ptr createForConsoleAPI( - double timestamp, ConsoleAPIType, - const std::vector>& arguments, - std::unique_ptr, InspectedContext*); - - static std::unique_ptr createForException( - double timestamp, const String16& detailedMessage, const String16& url, - unsigned lineNumber, unsigned columnNumber, - std::unique_ptr, int scriptId, v8::Isolate*, - const String16& message, int contextId, v8::Local exception, - unsigned exceptionId); - - static std::unique_ptr createForRevokedException( - double timestamp, const String16& message, unsigned revokedExceptionId); - - V8MessageOrigin origin() const; - void reportToFrontend(protocol::Console::Frontend*) const; - void reportToFrontend(protocol::Runtime::Frontend*, V8InspectorSessionImpl*, - bool generatePreview) const; - ConsoleAPIType type() const; - void contextDestroyed(int contextId); - - private: - V8ConsoleMessage(V8MessageOrigin, double timestamp, const String16& message); - - using Arguments = std::vector>>; - std::unique_ptr> - wrapArguments(V8InspectorSessionImpl*, bool generatePreview) const; - std::unique_ptr wrapException( - V8InspectorSessionImpl*, bool generatePreview) const; - void setLocation(const String16& url, unsigned lineNumber, - unsigned columnNumber, std::unique_ptr, - int scriptId); - - V8MessageOrigin m_origin; - double m_timestamp; - String16 m_message; - String16 m_url; - unsigned m_lineNumber; - unsigned m_columnNumber; - std::unique_ptr m_stackTrace; - int m_scriptId; - int m_contextId; - ConsoleAPIType m_type; - unsigned m_exceptionId; - unsigned m_revokedExceptionId; - Arguments m_arguments; - String16 m_detailedMessage; -}; - -class V8ConsoleMessageStorage { - public: - V8ConsoleMessageStorage(V8InspectorImpl*, int contextGroupId); - ~V8ConsoleMessageStorage(); - - int contextGroupId() { return m_contextGroupId; } - int expiredCount() { return m_expiredCount; } - const std::deque>& messages() const { - return m_messages; - } - - void addMessage(std::unique_ptr); - void contextDestroyed(int contextId); - void clear(); - - private: - V8InspectorImpl* m_inspector; - int m_contextGroupId; - int m_expiredCount; - std::deque> m_messages; -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8CONSOLEMESSAGE_H_ diff --git a/deps/v8_inspector/src/inspector/v8-console.cc b/deps/v8_inspector/src/inspector/v8-console.cc deleted file mode 100644 index b094de10b0469f..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-console.cc +++ /dev/null @@ -1,919 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-console.h" - -#include "src/base/macros.h" -#include "src/inspector/injected-script.h" -#include "src/inspector/inspected-context.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console-message.h" -#include "src/inspector/v8-debugger-agent-impl.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-profiler-agent-impl.h" -#include "src/inspector/v8-runtime-agent-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" -#include "src/inspector/v8-value-copier.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -namespace { - -v8::Local inspectedContextPrivateKey(v8::Isolate* isolate) { - return v8::Private::ForApi( - isolate, toV8StringInternalized(isolate, "V8Console#InspectedContext")); -} - -class ConsoleHelper { - public: - explicit ConsoleHelper(const v8::FunctionCallbackInfo& info) - : m_info(info), - m_isolate(info.GetIsolate()), - m_context(info.GetIsolate()->GetCurrentContext()), - m_inspectedContext(nullptr), - m_inspectorClient(nullptr) {} - - v8::Local ensureConsole() { - if (m_console.IsEmpty()) { - DCHECK(!m_info.Data().IsEmpty()); - DCHECK(!m_info.Data()->IsUndefined()); - m_console = m_info.Data().As(); - } - return m_console; - } - - InspectedContext* ensureInspectedContext() { - if (m_inspectedContext) return m_inspectedContext; - v8::Local console = ensureConsole(); - - v8::Local key = inspectedContextPrivateKey(m_isolate); - v8::Local inspectedContextValue; - if (!console->GetPrivate(m_context, key).ToLocal(&inspectedContextValue)) - return nullptr; - DCHECK(inspectedContextValue->IsExternal()); - m_inspectedContext = static_cast( - inspectedContextValue.As()->Value()); - return m_inspectedContext; - } - - V8InspectorClient* ensureDebuggerClient() { - if (m_inspectorClient) return m_inspectorClient; - InspectedContext* inspectedContext = ensureInspectedContext(); - if (!inspectedContext) return nullptr; - m_inspectorClient = inspectedContext->inspector()->client(); - return m_inspectorClient; - } - - void reportCall(ConsoleAPIType type) { - if (!m_info.Length()) return; - std::vector> arguments; - for (int i = 0; i < m_info.Length(); ++i) arguments.push_back(m_info[i]); - reportCall(type, arguments); - } - - void reportCallWithDefaultArgument(ConsoleAPIType type, - const String16& message) { - std::vector> arguments; - for (int i = 0; i < m_info.Length(); ++i) arguments.push_back(m_info[i]); - if (!m_info.Length()) arguments.push_back(toV8String(m_isolate, message)); - reportCall(type, arguments); - } - - void reportCallWithArgument(ConsoleAPIType type, const String16& message) { - std::vector> arguments(1, - toV8String(m_isolate, message)); - reportCall(type, arguments); - } - - void reportCall(ConsoleAPIType type, - const std::vector>& arguments) { - InspectedContext* inspectedContext = ensureInspectedContext(); - if (!inspectedContext) return; - int contextGroupId = inspectedContext->contextGroupId(); - V8InspectorImpl* inspector = inspectedContext->inspector(); - std::unique_ptr message = - V8ConsoleMessage::createForConsoleAPI( - inspector->client()->currentTimeMS(), type, arguments, - inspector->debugger()->captureStackTrace(false), inspectedContext); - inspector->ensureConsoleMessageStorage(contextGroupId) - ->addMessage(std::move(message)); - } - - void reportDeprecatedCall(const char* id, const String16& message) { - if (checkAndSetPrivateFlagOnConsole(id, false)) return; - std::vector> arguments(1, - toV8String(m_isolate, message)); - reportCall(ConsoleAPIType::kWarning, arguments); - } - - bool firstArgToBoolean(bool defaultValue) { - if (m_info.Length() < 1) return defaultValue; - if (m_info[0]->IsBoolean()) return m_info[0].As()->Value(); - return m_info[0]->BooleanValue(m_context).FromMaybe(defaultValue); - } - - String16 firstArgToString(const String16& defaultValue) { - if (m_info.Length() < 1) return defaultValue; - v8::Local titleValue; - if (m_info[0]->IsObject()) { - if (!m_info[0].As()->ObjectProtoToString(m_context).ToLocal( - &titleValue)) - return defaultValue; - } else { - if (!m_info[0]->ToString(m_context).ToLocal(&titleValue)) - return defaultValue; - } - return toProtocolString(titleValue); - } - - v8::MaybeLocal firstArgAsObject() { - if (m_info.Length() < 1 || !m_info[0]->IsObject()) - return v8::MaybeLocal(); - return m_info[0].As(); - } - - v8::MaybeLocal firstArgAsFunction() { - if (m_info.Length() < 1 || !m_info[0]->IsFunction()) - return v8::MaybeLocal(); - return m_info[0].As(); - } - - v8::MaybeLocal privateMap(const char* name) { - v8::Local console = ensureConsole(); - v8::Local privateKey = - v8::Private::ForApi(m_isolate, toV8StringInternalized(m_isolate, name)); - v8::Local mapValue; - if (!console->GetPrivate(m_context, privateKey).ToLocal(&mapValue)) - return v8::MaybeLocal(); - if (mapValue->IsUndefined()) { - v8::Local map = v8::Map::New(m_isolate); - if (!console->SetPrivate(m_context, privateKey, map).FromMaybe(false)) - return v8::MaybeLocal(); - return map; - } - return mapValue->IsMap() ? mapValue.As() - : v8::MaybeLocal(); - } - - int32_t getIntFromMap(v8::Local map, const String16& key, - int32_t defaultValue) { - v8::Local v8Key = toV8String(m_isolate, key); - if (!map->Has(m_context, v8Key).FromMaybe(false)) return defaultValue; - v8::Local intValue; - if (!map->Get(m_context, v8Key).ToLocal(&intValue)) return defaultValue; - return static_cast(intValue.As()->Value()); - } - - void setIntOnMap(v8::Local map, const String16& key, int32_t value) { - v8::Local v8Key = toV8String(m_isolate, key); - if (!map->Set(m_context, v8Key, v8::Integer::New(m_isolate, value)) - .ToLocal(&map)) - return; - } - - double getDoubleFromMap(v8::Local map, const String16& key, - double defaultValue) { - v8::Local v8Key = toV8String(m_isolate, key); - if (!map->Has(m_context, v8Key).FromMaybe(false)) return defaultValue; - v8::Local intValue; - if (!map->Get(m_context, v8Key).ToLocal(&intValue)) return defaultValue; - return intValue.As()->Value(); - } - - void setDoubleOnMap(v8::Local map, const String16& key, - double value) { - v8::Local v8Key = toV8String(m_isolate, key); - if (!map->Set(m_context, v8Key, v8::Number::New(m_isolate, value)) - .ToLocal(&map)) - return; - } - - V8ProfilerAgentImpl* profilerAgent() { - if (V8InspectorSessionImpl* session = currentSession()) { - if (session && session->profilerAgent()->enabled()) - return session->profilerAgent(); - } - return nullptr; - } - - V8DebuggerAgentImpl* debuggerAgent() { - if (V8InspectorSessionImpl* session = currentSession()) { - if (session && session->debuggerAgent()->enabled()) - return session->debuggerAgent(); - } - return nullptr; - } - - V8InspectorSessionImpl* currentSession() { - InspectedContext* inspectedContext = ensureInspectedContext(); - if (!inspectedContext) return nullptr; - return inspectedContext->inspector()->sessionForContextGroup( - inspectedContext->contextGroupId()); - } - - private: - const v8::FunctionCallbackInfo& m_info; - v8::Isolate* m_isolate; - v8::Local m_context; - v8::Local m_console; - InspectedContext* m_inspectedContext; - V8InspectorClient* m_inspectorClient; - - bool checkAndSetPrivateFlagOnConsole(const char* name, bool defaultValue) { - v8::Local console = ensureConsole(); - v8::Local key = - v8::Private::ForApi(m_isolate, toV8StringInternalized(m_isolate, name)); - v8::Local flagValue; - if (!console->GetPrivate(m_context, key).ToLocal(&flagValue)) - return defaultValue; - DCHECK(flagValue->IsUndefined() || flagValue->IsBoolean()); - if (flagValue->IsBoolean()) { - DCHECK(flagValue.As()->Value()); - return true; - } - if (!console->SetPrivate(m_context, key, v8::True(m_isolate)) - .FromMaybe(false)) - return defaultValue; - return false; - } - - DISALLOW_COPY_AND_ASSIGN(ConsoleHelper); -}; - -void returnDataCallback(const v8::FunctionCallbackInfo& info) { - info.GetReturnValue().Set(info.Data()); -} - -void createBoundFunctionProperty(v8::Local context, - v8::Local console, - const char* name, - v8::FunctionCallback callback, - const char* description = nullptr) { - v8::Local funcName = - toV8StringInternalized(context->GetIsolate(), name); - v8::Local func; - if (!v8::Function::New(context, callback, console, 0, - v8::ConstructorBehavior::kThrow) - .ToLocal(&func)) - return; - func->SetName(funcName); - if (description) { - v8::Local returnValue = - toV8String(context->GetIsolate(), description); - v8::Local toStringFunction; - if (v8::Function::New(context, returnDataCallback, returnValue, 0, - v8::ConstructorBehavior::kThrow) - .ToLocal(&toStringFunction)) - createDataProperty(context, func, toV8StringInternalized( - context->GetIsolate(), "toString"), - toStringFunction); - } - createDataProperty(context, console, funcName, func); -} - -} // namespace - -void V8Console::debugCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kDebug); -} - -void V8Console::errorCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kError); -} - -void V8Console::infoCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kInfo); -} - -void V8Console::logCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kLog); -} - -void V8Console::warnCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kWarning); -} - -void V8Console::dirCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kDir); -} - -void V8Console::dirxmlCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kDirXML); -} - -void V8Console::tableCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCall(ConsoleAPIType::kTable); -} - -void V8Console::traceCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCallWithDefaultArgument(ConsoleAPIType::kTrace, - String16("console.trace")); -} - -void V8Console::groupCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCallWithDefaultArgument(ConsoleAPIType::kStartGroup, - String16("console.group")); -} - -void V8Console::groupCollapsedCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCallWithDefaultArgument( - ConsoleAPIType::kStartGroupCollapsed, String16("console.groupCollapsed")); -} - -void V8Console::groupEndCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCallWithDefaultArgument( - ConsoleAPIType::kEndGroup, String16("console.groupEnd")); -} - -void V8Console::clearCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportCallWithDefaultArgument(ConsoleAPIType::kClear, - String16("console.clear")); -} - -void V8Console::countCallback(const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - - String16 title = helper.firstArgToString(String16()); - String16 identifier; - if (title.isEmpty()) { - std::unique_ptr stackTrace = - V8StackTraceImpl::capture(nullptr, 0, 1); - if (stackTrace && !stackTrace->isEmpty()) { - identifier = toString16(stackTrace->topSourceURL()) + ":" + - String16::fromInteger(stackTrace->topLineNumber()); - } - } else { - identifier = title + "@"; - } - - v8::Local countMap; - if (!helper.privateMap("V8Console#countMap").ToLocal(&countMap)) return; - int32_t count = helper.getIntFromMap(countMap, identifier, 0) + 1; - helper.setIntOnMap(countMap, identifier, count); - helper.reportCallWithArgument(ConsoleAPIType::kCount, - title + ": " + String16::fromInteger(count)); -} - -void V8Console::assertCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - if (helper.firstArgToBoolean(false)) return; - - std::vector> arguments; - for (int i = 1; i < info.Length(); ++i) arguments.push_back(info[i]); - if (info.Length() < 2) - arguments.push_back( - toV8String(info.GetIsolate(), String16("console.assert"))); - helper.reportCall(ConsoleAPIType::kAssert, arguments); - - if (V8DebuggerAgentImpl* debuggerAgent = helper.debuggerAgent()) - debuggerAgent->breakProgramOnException( - protocol::Debugger::Paused::ReasonEnum::Assert, nullptr); -} - -void V8Console::markTimelineCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportDeprecatedCall("V8Console#markTimelineDeprecated", - "'console.markTimeline' is " - "deprecated. Please use " - "'console.timeStamp' instead."); - timeStampCallback(info); -} - -void V8Console::profileCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - if (V8ProfilerAgentImpl* profilerAgent = helper.profilerAgent()) - profilerAgent->consoleProfile(helper.firstArgToString(String16())); -} - -void V8Console::profileEndCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - if (V8ProfilerAgentImpl* profilerAgent = helper.profilerAgent()) - profilerAgent->consoleProfileEnd(helper.firstArgToString(String16())); -} - -static void timeFunction(const v8::FunctionCallbackInfo& info, - bool timelinePrefix) { - ConsoleHelper helper(info); - if (V8InspectorClient* client = helper.ensureDebuggerClient()) { - String16 protocolTitle = helper.firstArgToString("default"); - if (timelinePrefix) protocolTitle = "Timeline '" + protocolTitle + "'"; - client->consoleTime(toStringView(protocolTitle)); - - v8::Local timeMap; - if (!helper.privateMap("V8Console#timeMap").ToLocal(&timeMap)) return; - helper.setDoubleOnMap(timeMap, protocolTitle, client->currentTimeMS()); - } -} - -static void timeEndFunction(const v8::FunctionCallbackInfo& info, - bool timelinePrefix) { - ConsoleHelper helper(info); - if (V8InspectorClient* client = helper.ensureDebuggerClient()) { - String16 protocolTitle = helper.firstArgToString("default"); - if (timelinePrefix) protocolTitle = "Timeline '" + protocolTitle + "'"; - client->consoleTimeEnd(toStringView(protocolTitle)); - - v8::Local timeMap; - if (!helper.privateMap("V8Console#timeMap").ToLocal(&timeMap)) return; - double elapsed = client->currentTimeMS() - - helper.getDoubleFromMap(timeMap, protocolTitle, 0.0); - String16 message = - protocolTitle + ": " + String16::fromDoublePrecision3(elapsed) + "ms"; - helper.reportCallWithArgument(ConsoleAPIType::kTimeEnd, message); - } -} - -void V8Console::timelineCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportDeprecatedCall( - "V8Console#timeline", - "'console.timeline' is deprecated. Please use 'console.time' instead."); - timeFunction(info, true); -} - -void V8Console::timelineEndCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper(info).reportDeprecatedCall("V8Console#timelineEnd", - "'console.timelineEnd' is " - "deprecated. Please use " - "'console.timeEnd' instead."); - timeEndFunction(info, true); -} - -void V8Console::timeCallback(const v8::FunctionCallbackInfo& info) { - timeFunction(info, false); -} - -void V8Console::timeEndCallback( - const v8::FunctionCallbackInfo& info) { - timeEndFunction(info, false); -} - -void V8Console::timeStampCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - if (V8InspectorClient* client = helper.ensureDebuggerClient()) { - String16 title = helper.firstArgToString(String16()); - client->consoleTimeStamp(toStringView(title)); - } -} - -void V8Console::memoryGetterCallback( - const v8::FunctionCallbackInfo& info) { - if (V8InspectorClient* client = ConsoleHelper(info).ensureDebuggerClient()) { - v8::Local memoryValue; - if (!client - ->memoryInfo(info.GetIsolate(), - info.GetIsolate()->GetCurrentContext()) - .ToLocal(&memoryValue)) - return; - info.GetReturnValue().Set(memoryValue); - } -} - -void V8Console::memorySetterCallback( - const v8::FunctionCallbackInfo& info) { - // We can't make the attribute readonly as it breaks existing code that relies - // on being able to assign to console.memory in strict mode. Instead, the - // setter just ignores the passed value. http://crbug.com/468611 -} - -void V8Console::keysCallback(const v8::FunctionCallbackInfo& info) { - v8::Isolate* isolate = info.GetIsolate(); - info.GetReturnValue().Set(v8::Array::New(isolate)); - - ConsoleHelper helper(info); - v8::Local obj; - if (!helper.firstArgAsObject().ToLocal(&obj)) return; - v8::Local names; - if (!obj->GetOwnPropertyNames(isolate->GetCurrentContext()).ToLocal(&names)) - return; - info.GetReturnValue().Set(names); -} - -void V8Console::valuesCallback( - const v8::FunctionCallbackInfo& info) { - v8::Isolate* isolate = info.GetIsolate(); - info.GetReturnValue().Set(v8::Array::New(isolate)); - - ConsoleHelper helper(info); - v8::Local obj; - if (!helper.firstArgAsObject().ToLocal(&obj)) return; - v8::Local names; - v8::Local context = isolate->GetCurrentContext(); - if (!obj->GetOwnPropertyNames(context).ToLocal(&names)) return; - v8::Local values = v8::Array::New(isolate, names->Length()); - for (uint32_t i = 0; i < names->Length(); ++i) { - v8::Local key; - if (!names->Get(context, i).ToLocal(&key)) continue; - v8::Local value; - if (!obj->Get(context, key).ToLocal(&value)) continue; - createDataProperty(context, values, i, value); - } - info.GetReturnValue().Set(values); -} - -static void setFunctionBreakpoint(ConsoleHelper& helper, - v8::Local function, - V8DebuggerAgentImpl::BreakpointSource source, - const String16& condition, bool enable) { - V8DebuggerAgentImpl* debuggerAgent = helper.debuggerAgent(); - if (!debuggerAgent) return; - String16 scriptId = String16::fromInteger(function->ScriptId()); - int lineNumber = function->GetScriptLineNumber(); - int columnNumber = function->GetScriptColumnNumber(); - if (lineNumber == v8::Function::kLineOffsetNotFound || - columnNumber == v8::Function::kLineOffsetNotFound) - return; - if (enable) - debuggerAgent->setBreakpointAt(scriptId, lineNumber, columnNumber, source, - condition); - else - debuggerAgent->removeBreakpointAt(scriptId, lineNumber, columnNumber, - source); -} - -void V8Console::debugFunctionCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - v8::Local function; - if (!helper.firstArgAsFunction().ToLocal(&function)) return; - setFunctionBreakpoint(helper, function, - V8DebuggerAgentImpl::DebugCommandBreakpointSource, - String16(), true); -} - -void V8Console::undebugFunctionCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - v8::Local function; - if (!helper.firstArgAsFunction().ToLocal(&function)) return; - setFunctionBreakpoint(helper, function, - V8DebuggerAgentImpl::DebugCommandBreakpointSource, - String16(), false); -} - -void V8Console::monitorFunctionCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - v8::Local function; - if (!helper.firstArgAsFunction().ToLocal(&function)) return; - v8::Local name = function->GetName(); - if (!name->IsString() || !v8::Local::Cast(name)->Length()) - name = function->GetInferredName(); - String16 functionName = toProtocolStringWithTypeCheck(name); - String16Builder builder; - builder.append("console.log(\"function "); - if (functionName.isEmpty()) - builder.append("(anonymous function)"); - else - builder.append(functionName); - builder.append( - " called\" + (arguments.length > 0 ? \" with arguments: \" + " - "Array.prototype.join.call(arguments, \", \") : \"\")) && false"); - setFunctionBreakpoint(helper, function, - V8DebuggerAgentImpl::MonitorCommandBreakpointSource, - builder.toString(), true); -} - -void V8Console::unmonitorFunctionCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - v8::Local function; - if (!helper.firstArgAsFunction().ToLocal(&function)) return; - setFunctionBreakpoint(helper, function, - V8DebuggerAgentImpl::MonitorCommandBreakpointSource, - String16(), false); -} - -void V8Console::lastEvaluationResultCallback( - const v8::FunctionCallbackInfo& info) { - ConsoleHelper helper(info); - InspectedContext* context = helper.ensureInspectedContext(); - if (!context) return; - if (InjectedScript* injectedScript = context->getInjectedScript()) - info.GetReturnValue().Set(injectedScript->lastEvaluationResult()); -} - -static void inspectImpl(const v8::FunctionCallbackInfo& info, - bool copyToClipboard) { - if (info.Length() < 1) return; - if (!copyToClipboard) info.GetReturnValue().Set(info[0]); - - ConsoleHelper helper(info); - InspectedContext* context = helper.ensureInspectedContext(); - if (!context) return; - InjectedScript* injectedScript = context->getInjectedScript(); - if (!injectedScript) return; - ErrorString errorString; - std::unique_ptr wrappedObject = - injectedScript->wrapObject(&errorString, info[0], "", - false /** forceValueType */, - false /** generatePreview */); - if (!wrappedObject || !errorString.isEmpty()) return; - - std::unique_ptr hints = - protocol::DictionaryValue::create(); - if (copyToClipboard) hints->setBoolean("copyToClipboard", true); - if (V8InspectorSessionImpl* session = helper.currentSession()) - session->runtimeAgent()->inspect(std::move(wrappedObject), - std::move(hints)); -} - -void V8Console::inspectCallback( - const v8::FunctionCallbackInfo& info) { - inspectImpl(info, false); -} - -void V8Console::copyCallback(const v8::FunctionCallbackInfo& info) { - inspectImpl(info, true); -} - -void V8Console::inspectedObject(const v8::FunctionCallbackInfo& info, - unsigned num) { - DCHECK(num < V8InspectorSessionImpl::kInspectedObjectBufferSize); - ConsoleHelper helper(info); - if (V8InspectorSessionImpl* session = helper.currentSession()) { - V8InspectorSession::Inspectable* object = session->inspectedObject(num); - v8::Isolate* isolate = info.GetIsolate(); - if (object) - info.GetReturnValue().Set(object->get(isolate->GetCurrentContext())); - else - info.GetReturnValue().Set(v8::Undefined(isolate)); - } -} - -v8::Local V8Console::createConsole( - InspectedContext* inspectedContext, bool hasMemoryAttribute) { - v8::Local context = inspectedContext->context(); - v8::Context::Scope contextScope(context); - v8::Isolate* isolate = context->GetIsolate(); - v8::MicrotasksScope microtasksScope(isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - - v8::Local console = v8::Object::New(isolate); - bool success = - console->SetPrototype(context, v8::Object::New(isolate)).FromMaybe(false); - DCHECK(success); - USE(success); - - createBoundFunctionProperty(context, console, "debug", - V8Console::debugCallback); - createBoundFunctionProperty(context, console, "error", - V8Console::errorCallback); - createBoundFunctionProperty(context, console, "info", - V8Console::infoCallback); - createBoundFunctionProperty(context, console, "log", V8Console::logCallback); - createBoundFunctionProperty(context, console, "warn", - V8Console::warnCallback); - createBoundFunctionProperty(context, console, "dir", V8Console::dirCallback); - createBoundFunctionProperty(context, console, "dirxml", - V8Console::dirxmlCallback); - createBoundFunctionProperty(context, console, "table", - V8Console::tableCallback); - createBoundFunctionProperty(context, console, "trace", - V8Console::traceCallback); - createBoundFunctionProperty(context, console, "group", - V8Console::groupCallback); - createBoundFunctionProperty(context, console, "groupCollapsed", - V8Console::groupCollapsedCallback); - createBoundFunctionProperty(context, console, "groupEnd", - V8Console::groupEndCallback); - createBoundFunctionProperty(context, console, "clear", - V8Console::clearCallback); - createBoundFunctionProperty(context, console, "count", - V8Console::countCallback); - createBoundFunctionProperty(context, console, "assert", - V8Console::assertCallback); - createBoundFunctionProperty(context, console, "markTimeline", - V8Console::markTimelineCallback); - createBoundFunctionProperty(context, console, "profile", - V8Console::profileCallback); - createBoundFunctionProperty(context, console, "profileEnd", - V8Console::profileEndCallback); - createBoundFunctionProperty(context, console, "timeline", - V8Console::timelineCallback); - createBoundFunctionProperty(context, console, "timelineEnd", - V8Console::timelineEndCallback); - createBoundFunctionProperty(context, console, "time", - V8Console::timeCallback); - createBoundFunctionProperty(context, console, "timeEnd", - V8Console::timeEndCallback); - createBoundFunctionProperty(context, console, "timeStamp", - V8Console::timeStampCallback); - - if (hasMemoryAttribute) - console->SetAccessorProperty( - toV8StringInternalized(isolate, "memory"), - v8::Function::New(context, V8Console::memoryGetterCallback, console, 0, - v8::ConstructorBehavior::kThrow) - .ToLocalChecked(), - v8::Function::New(context, V8Console::memorySetterCallback, - v8::Local(), 0, - v8::ConstructorBehavior::kThrow) - .ToLocalChecked(), - static_cast(v8::None), v8::DEFAULT); - - console->SetPrivate(context, inspectedContextPrivateKey(isolate), - v8::External::New(isolate, inspectedContext)); - return console; -} - -void V8Console::clearInspectedContextIfNeeded(v8::Local context, - v8::Local console) { - v8::Isolate* isolate = context->GetIsolate(); - console->SetPrivate(context, inspectedContextPrivateKey(isolate), - v8::External::New(isolate, nullptr)); -} - -v8::Local V8Console::createCommandLineAPI( - InspectedContext* inspectedContext) { - v8::Local context = inspectedContext->context(); - v8::Isolate* isolate = context->GetIsolate(); - v8::MicrotasksScope microtasksScope(isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - - v8::Local commandLineAPI = v8::Object::New(isolate); - bool success = - commandLineAPI->SetPrototype(context, v8::Null(isolate)).FromMaybe(false); - DCHECK(success); - USE(success); - - createBoundFunctionProperty(context, commandLineAPI, "dir", - V8Console::dirCallback, - "function dir(value) { [Command Line API] }"); - createBoundFunctionProperty(context, commandLineAPI, "dirxml", - V8Console::dirxmlCallback, - "function dirxml(value) { [Command Line API] }"); - createBoundFunctionProperty(context, commandLineAPI, "profile", - V8Console::profileCallback, - "function profile(title) { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "profileEnd", V8Console::profileEndCallback, - "function profileEnd(title) { [Command Line API] }"); - createBoundFunctionProperty(context, commandLineAPI, "clear", - V8Console::clearCallback, - "function clear() { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "table", V8Console::tableCallback, - "function table(data, [columns]) { [Command Line API] }"); - - createBoundFunctionProperty(context, commandLineAPI, "keys", - V8Console::keysCallback, - "function keys(object) { [Command Line API] }"); - createBoundFunctionProperty(context, commandLineAPI, "values", - V8Console::valuesCallback, - "function values(object) { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "debug", V8Console::debugFunctionCallback, - "function debug(function) { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "undebug", V8Console::undebugFunctionCallback, - "function undebug(function) { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "monitor", V8Console::monitorFunctionCallback, - "function monitor(function) { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "unmonitor", - V8Console::unmonitorFunctionCallback, - "function unmonitor(function) { [Command Line API] }"); - createBoundFunctionProperty( - context, commandLineAPI, "inspect", V8Console::inspectCallback, - "function inspect(object) { [Command Line API] }"); - createBoundFunctionProperty(context, commandLineAPI, "copy", - V8Console::copyCallback, - "function copy(value) { [Command Line API] }"); - createBoundFunctionProperty(context, commandLineAPI, "$_", - V8Console::lastEvaluationResultCallback); - createBoundFunctionProperty(context, commandLineAPI, "$0", - V8Console::inspectedObject0); - createBoundFunctionProperty(context, commandLineAPI, "$1", - V8Console::inspectedObject1); - createBoundFunctionProperty(context, commandLineAPI, "$2", - V8Console::inspectedObject2); - createBoundFunctionProperty(context, commandLineAPI, "$3", - V8Console::inspectedObject3); - createBoundFunctionProperty(context, commandLineAPI, "$4", - V8Console::inspectedObject4); - - inspectedContext->inspector()->client()->installAdditionalCommandLineAPI( - context, commandLineAPI); - - commandLineAPI->SetPrivate(context, inspectedContextPrivateKey(isolate), - v8::External::New(isolate, inspectedContext)); - return commandLineAPI; -} - -static bool isCommandLineAPIGetter(const String16& name) { - if (name.length() != 2) return false; - // $0 ... $4, $_ - return name[0] == '$' && - ((name[1] >= '0' && name[1] <= '4') || name[1] == '_'); -} - -void V8Console::CommandLineAPIScope::accessorGetterCallback( - v8::Local name, const v8::PropertyCallbackInfo& info) { - CommandLineAPIScope* scope = static_cast( - info.Data().As()->Value()); - DCHECK(scope); - - v8::Local context = info.GetIsolate()->GetCurrentContext(); - if (scope->m_cleanup) { - bool removed = info.Holder()->Delete(context, name).FromMaybe(false); - DCHECK(removed); - USE(removed); - return; - } - v8::Local commandLineAPI = scope->m_commandLineAPI; - - v8::Local value; - if (!commandLineAPI->Get(context, name).ToLocal(&value)) return; - if (isCommandLineAPIGetter(toProtocolStringWithTypeCheck(name))) { - DCHECK(value->IsFunction()); - v8::MicrotasksScope microtasks(info.GetIsolate(), - v8::MicrotasksScope::kDoNotRunMicrotasks); - if (value.As() - ->Call(context, commandLineAPI, 0, nullptr) - .ToLocal(&value)) - info.GetReturnValue().Set(value); - } else { - info.GetReturnValue().Set(value); - } -} - -void V8Console::CommandLineAPIScope::accessorSetterCallback( - v8::Local name, v8::Local value, - const v8::PropertyCallbackInfo& info) { - CommandLineAPIScope* scope = static_cast( - info.Data().As()->Value()); - v8::Local context = info.GetIsolate()->GetCurrentContext(); - if (!info.Holder()->Delete(context, name).FromMaybe(false)) return; - if (!info.Holder()->CreateDataProperty(context, name, value).FromMaybe(false)) - return; - bool removed = - scope->m_installedMethods->Delete(context, name).FromMaybe(false); - DCHECK(removed); - USE(removed); -} - -V8Console::CommandLineAPIScope::CommandLineAPIScope( - v8::Local context, v8::Local commandLineAPI, - v8::Local global) - : m_context(context), - m_commandLineAPI(commandLineAPI), - m_global(global), - m_installedMethods(v8::Set::New(context->GetIsolate())), - m_cleanup(false) { - v8::Local names; - if (!m_commandLineAPI->GetOwnPropertyNames(context).ToLocal(&names)) return; - v8::Local externalThis = - v8::External::New(context->GetIsolate(), this); - for (uint32_t i = 0; i < names->Length(); ++i) { - v8::Local name; - if (!names->Get(context, i).ToLocal(&name) || !name->IsName()) continue; - if (m_global->Has(context, name).FromMaybe(true)) continue; - if (!m_installedMethods->Add(context, name).ToLocal(&m_installedMethods)) - continue; - if (!m_global - ->SetAccessor(context, v8::Local::Cast(name), - CommandLineAPIScope::accessorGetterCallback, - CommandLineAPIScope::accessorSetterCallback, - externalThis, v8::DEFAULT, v8::DontEnum) - .FromMaybe(false)) { - bool removed = m_installedMethods->Delete(context, name).FromMaybe(false); - DCHECK(removed); - USE(removed); - continue; - } - } -} - -V8Console::CommandLineAPIScope::~CommandLineAPIScope() { - m_cleanup = true; - v8::Local names = m_installedMethods->AsArray(); - for (uint32_t i = 0; i < names->Length(); ++i) { - v8::Local name; - if (!names->Get(m_context, i).ToLocal(&name) || !name->IsName()) continue; - if (name->IsString()) { - v8::Local descriptor; - bool success = m_global - ->GetOwnPropertyDescriptor( - m_context, v8::Local::Cast(name)) - .ToLocal(&descriptor); - DCHECK(success); - USE(success); - } - } -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-console.h b/deps/v8_inspector/src/inspector/v8-console.h deleted file mode 100644 index c643d49a4154a4..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-console.h +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8CONSOLE_H_ -#define V8_INSPECTOR_V8CONSOLE_H_ - -#include "src/base/macros.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class InspectedContext; - -// Console API -// https://console.spec.whatwg.org/#console-interface -class V8Console { - public: - static v8::Local createConsole(InspectedContext*, - bool hasMemoryAttribute); - static void clearInspectedContextIfNeeded(v8::Local, - v8::Local console); - static v8::Local createCommandLineAPI(InspectedContext*); - - class CommandLineAPIScope { - public: - CommandLineAPIScope(v8::Local, - v8::Local commandLineAPI, - v8::Local global); - ~CommandLineAPIScope(); - - private: - static void accessorGetterCallback( - v8::Local, const v8::PropertyCallbackInfo&); - static void accessorSetterCallback(v8::Local, - v8::Local, - const v8::PropertyCallbackInfo&); - - v8::Local m_context; - v8::Local m_commandLineAPI; - v8::Local m_global; - v8::Local m_installedMethods; - bool m_cleanup; - - DISALLOW_COPY_AND_ASSIGN(CommandLineAPIScope); - }; - - private: - static void debugCallback(const v8::FunctionCallbackInfo&); - static void errorCallback(const v8::FunctionCallbackInfo&); - static void infoCallback(const v8::FunctionCallbackInfo&); - static void logCallback(const v8::FunctionCallbackInfo&); - static void warnCallback(const v8::FunctionCallbackInfo&); - static void dirCallback(const v8::FunctionCallbackInfo&); - static void dirxmlCallback(const v8::FunctionCallbackInfo&); - static void tableCallback(const v8::FunctionCallbackInfo&); - static void traceCallback(const v8::FunctionCallbackInfo&); - static void groupCallback(const v8::FunctionCallbackInfo&); - static void groupCollapsedCallback( - const v8::FunctionCallbackInfo&); - static void groupEndCallback(const v8::FunctionCallbackInfo&); - static void clearCallback(const v8::FunctionCallbackInfo&); - static void countCallback(const v8::FunctionCallbackInfo&); - static void assertCallback(const v8::FunctionCallbackInfo&); - static void markTimelineCallback(const v8::FunctionCallbackInfo&); - static void profileCallback(const v8::FunctionCallbackInfo&); - static void profileEndCallback(const v8::FunctionCallbackInfo&); - static void timelineCallback(const v8::FunctionCallbackInfo&); - static void timelineEndCallback(const v8::FunctionCallbackInfo&); - static void timeCallback(const v8::FunctionCallbackInfo&); - static void timeEndCallback(const v8::FunctionCallbackInfo&); - static void timeStampCallback(const v8::FunctionCallbackInfo&); - // TODO(foolip): There is no spec for the Memory Info API, see blink-dev: - // https://groups.google.com/a/chromium.org/d/msg/blink-dev/g5YRCGpC9vs/b4OJz71NmPwJ - static void memoryGetterCallback(const v8::FunctionCallbackInfo&); - static void memorySetterCallback(const v8::FunctionCallbackInfo&); - - // CommandLineAPI - static void keysCallback(const v8::FunctionCallbackInfo&); - static void valuesCallback(const v8::FunctionCallbackInfo&); - static void debugFunctionCallback(const v8::FunctionCallbackInfo&); - static void undebugFunctionCallback( - const v8::FunctionCallbackInfo&); - static void monitorFunctionCallback( - const v8::FunctionCallbackInfo&); - static void unmonitorFunctionCallback( - const v8::FunctionCallbackInfo&); - static void lastEvaluationResultCallback( - const v8::FunctionCallbackInfo&); - static void inspectCallback(const v8::FunctionCallbackInfo&); - static void copyCallback(const v8::FunctionCallbackInfo&); - static void inspectedObject(const v8::FunctionCallbackInfo&, - unsigned num); - static void inspectedObject0( - const v8::FunctionCallbackInfo& info) { - inspectedObject(info, 0); - } - static void inspectedObject1( - const v8::FunctionCallbackInfo& info) { - inspectedObject(info, 1); - } - static void inspectedObject2( - const v8::FunctionCallbackInfo& info) { - inspectedObject(info, 2); - } - static void inspectedObject3( - const v8::FunctionCallbackInfo& info) { - inspectedObject(info, 3); - } - static void inspectedObject4( - const v8::FunctionCallbackInfo& info) { - inspectedObject(info, 4); - } -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8CONSOLE_H_ diff --git a/deps/v8_inspector/src/inspector/v8-debugger-agent-impl.cc b/deps/v8_inspector/src/inspector/v8-debugger-agent-impl.cc deleted file mode 100644 index 80e261119e8dad..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-debugger-agent-impl.cc +++ /dev/null @@ -1,1255 +0,0 @@ -// Copyright 2015 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. - -#include "src/inspector/v8-debugger-agent-impl.h" - -#include - -#include "src/inspector/injected-script.h" -#include "src/inspector/inspected-context.h" -#include "src/inspector/java-script-call-frame.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/remote-object-id.h" -#include "src/inspector/script-breakpoint.h" -#include "src/inspector/search-util.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger-script.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-regex.h" -#include "src/inspector/v8-runtime-agent-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -using protocol::Array; -using protocol::Maybe; -using protocol::Debugger::BreakpointId; -using protocol::Debugger::CallFrame; -using protocol::Runtime::ExceptionDetails; -using protocol::Runtime::ScriptId; -using protocol::Runtime::StackTrace; -using protocol::Runtime::RemoteObject; - -namespace DebuggerAgentState { -static const char javaScriptBreakpoints[] = "javaScriptBreakopints"; -static const char pauseOnExceptionsState[] = "pauseOnExceptionsState"; -static const char asyncCallStackDepth[] = "asyncCallStackDepth"; -static const char blackboxPattern[] = "blackboxPattern"; -static const char debuggerEnabled[] = "debuggerEnabled"; - -// Breakpoint properties. -static const char url[] = "url"; -static const char isRegex[] = "isRegex"; -static const char lineNumber[] = "lineNumber"; -static const char columnNumber[] = "columnNumber"; -static const char condition[] = "condition"; -static const char skipAllPauses[] = "skipAllPauses"; - -} // namespace DebuggerAgentState - -static const int maxSkipStepFrameCount = 128; -static const char backtraceObjectGroup[] = "backtrace"; - -static String16 breakpointIdSuffix( - V8DebuggerAgentImpl::BreakpointSource source) { - switch (source) { - case V8DebuggerAgentImpl::UserBreakpointSource: - break; - case V8DebuggerAgentImpl::DebugCommandBreakpointSource: - return ":debug"; - case V8DebuggerAgentImpl::MonitorCommandBreakpointSource: - return ":monitor"; - } - return String16(); -} - -static String16 generateBreakpointId( - const String16& scriptId, int lineNumber, int columnNumber, - V8DebuggerAgentImpl::BreakpointSource source) { - return scriptId + ":" + String16::fromInteger(lineNumber) + ":" + - String16::fromInteger(columnNumber) + breakpointIdSuffix(source); -} - -static bool positionComparator(const std::pair& a, - const std::pair& b) { - if (a.first != b.first) return a.first < b.first; - return a.second < b.second; -} - -static bool hasInternalError(ErrorString* errorString, bool hasError) { - if (hasError) *errorString = "Internal error"; - return hasError; -} - -static std::unique_ptr buildProtocolLocation( - const String16& scriptId, int lineNumber, int columnNumber) { - return protocol::Debugger::Location::create() - .setScriptId(scriptId) - .setLineNumber(lineNumber) - .setColumnNumber(columnNumber) - .build(); -} - -V8DebuggerAgentImpl::V8DebuggerAgentImpl( - V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, - protocol::DictionaryValue* state) - : m_inspector(session->inspector()), - m_debugger(m_inspector->debugger()), - m_session(session), - m_enabled(false), - m_state(state), - m_frontend(frontendChannel), - m_isolate(m_inspector->isolate()), - m_breakReason(protocol::Debugger::Paused::ReasonEnum::Other), - m_scheduledDebuggerStep(NoStep), - m_skipNextDebuggerStepOut(false), - m_javaScriptPauseScheduled(false), - m_steppingFromFramework(false), - m_pausingOnNativeEvent(false), - m_skippedStepFrameCount(0), - m_recursionLevelForStepOut(0), - m_recursionLevelForStepFrame(0), - m_skipAllPauses(false) { - clearBreakDetails(); -} - -V8DebuggerAgentImpl::~V8DebuggerAgentImpl() {} - -bool V8DebuggerAgentImpl::checkEnabled(ErrorString* errorString) { - if (enabled()) return true; - *errorString = "Debugger agent is not enabled"; - return false; -} - -void V8DebuggerAgentImpl::enable() { - // m_inspector->addListener may result in reporting all parsed scripts to - // the agent so it should already be in enabled state by then. - m_enabled = true; - m_state->setBoolean(DebuggerAgentState::debuggerEnabled, true); - m_debugger->enable(); - - std::vector> compiledScripts; - m_debugger->getCompiledScripts(m_session->contextGroupId(), compiledScripts); - for (size_t i = 0; i < compiledScripts.size(); i++) - didParseSource(std::move(compiledScripts[i]), true); - - // FIXME(WK44513): breakpoints activated flag should be synchronized between - // all front-ends - m_debugger->setBreakpointsActivated(true); -} - -bool V8DebuggerAgentImpl::enabled() { return m_enabled; } - -void V8DebuggerAgentImpl::enable(ErrorString* errorString) { - if (enabled()) return; - - if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId())) { - *errorString = "Script execution is prohibited"; - return; - } - - enable(); -} - -void V8DebuggerAgentImpl::disable(ErrorString*) { - if (!enabled()) return; - - m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, - protocol::DictionaryValue::create()); - m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState, - V8Debugger::DontPauseOnExceptions); - m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, 0); - - if (!m_pausedContext.IsEmpty()) m_debugger->continueProgram(); - m_debugger->disable(); - m_pausedContext.Reset(); - JavaScriptCallFrames emptyCallFrames; - m_pausedCallFrames.swap(emptyCallFrames); - m_scripts.clear(); - m_blackboxedPositions.clear(); - m_breakpointIdToDebuggerBreakpointIds.clear(); - m_debugger->setAsyncCallStackDepth(this, 0); - m_continueToLocationBreakpointId = String16(); - clearBreakDetails(); - m_scheduledDebuggerStep = NoStep; - m_skipNextDebuggerStepOut = false; - m_javaScriptPauseScheduled = false; - m_steppingFromFramework = false; - m_pausingOnNativeEvent = false; - m_skippedStepFrameCount = 0; - m_recursionLevelForStepFrame = 0; - m_skipAllPauses = false; - m_blackboxPattern = nullptr; - m_state->remove(DebuggerAgentState::blackboxPattern); - m_enabled = false; - m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false); -} - -void V8DebuggerAgentImpl::restore() { - DCHECK(!m_enabled); - if (!m_state->booleanProperty(DebuggerAgentState::debuggerEnabled, false)) - return; - if (!m_inspector->client()->canExecuteScripts(m_session->contextGroupId())) - return; - - enable(); - ErrorString error; - - int pauseState = V8Debugger::DontPauseOnExceptions; - m_state->getInteger(DebuggerAgentState::pauseOnExceptionsState, &pauseState); - setPauseOnExceptionsImpl(&error, pauseState); - DCHECK(error.isEmpty()); - - m_skipAllPauses = - m_state->booleanProperty(DebuggerAgentState::skipAllPauses, false); - - int asyncCallStackDepth = 0; - m_state->getInteger(DebuggerAgentState::asyncCallStackDepth, - &asyncCallStackDepth); - m_debugger->setAsyncCallStackDepth(this, asyncCallStackDepth); - - String16 blackboxPattern; - if (m_state->getString(DebuggerAgentState::blackboxPattern, - &blackboxPattern)) { - if (!setBlackboxPattern(&error, blackboxPattern)) UNREACHABLE(); - } -} - -void V8DebuggerAgentImpl::setBreakpointsActive(ErrorString* errorString, - bool active) { - if (!checkEnabled(errorString)) return; - m_debugger->setBreakpointsActivated(active); -} - -void V8DebuggerAgentImpl::setSkipAllPauses(ErrorString*, bool skip) { - m_skipAllPauses = skip; - m_state->setBoolean(DebuggerAgentState::skipAllPauses, m_skipAllPauses); -} - -static std::unique_ptr -buildObjectForBreakpointCookie(const String16& url, int lineNumber, - int columnNumber, const String16& condition, - bool isRegex) { - std::unique_ptr breakpointObject = - protocol::DictionaryValue::create(); - breakpointObject->setString(DebuggerAgentState::url, url); - breakpointObject->setInteger(DebuggerAgentState::lineNumber, lineNumber); - breakpointObject->setInteger(DebuggerAgentState::columnNumber, columnNumber); - breakpointObject->setString(DebuggerAgentState::condition, condition); - breakpointObject->setBoolean(DebuggerAgentState::isRegex, isRegex); - return breakpointObject; -} - -static bool matches(V8InspectorImpl* inspector, const String16& url, - const String16& pattern, bool isRegex) { - if (isRegex) { - V8Regex regex(inspector, pattern, true); - return regex.match(url) != -1; - } - return url == pattern; -} - -void V8DebuggerAgentImpl::setBreakpointByUrl( - ErrorString* errorString, int lineNumber, - const Maybe& optionalURL, const Maybe& optionalURLRegex, - const Maybe& optionalColumnNumber, - const Maybe& optionalCondition, String16* outBreakpointId, - std::unique_ptr>* locations) { - *locations = Array::create(); - if (optionalURL.isJust() == optionalURLRegex.isJust()) { - *errorString = "Either url or urlRegex must be specified."; - return; - } - - String16 url = optionalURL.isJust() ? optionalURL.fromJust() - : optionalURLRegex.fromJust(); - int columnNumber = 0; - if (optionalColumnNumber.isJust()) { - columnNumber = optionalColumnNumber.fromJust(); - if (columnNumber < 0) { - *errorString = "Incorrect column number"; - return; - } - } - String16 condition = optionalCondition.fromMaybe(""); - bool isRegex = optionalURLRegex.isJust(); - - String16 breakpointId = (isRegex ? "/" + url + "/" : url) + ":" + - String16::fromInteger(lineNumber) + ":" + - String16::fromInteger(columnNumber); - protocol::DictionaryValue* breakpointsCookie = - m_state->getObject(DebuggerAgentState::javaScriptBreakpoints); - if (!breakpointsCookie) { - std::unique_ptr newValue = - protocol::DictionaryValue::create(); - breakpointsCookie = newValue.get(); - m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, - std::move(newValue)); - } - if (breakpointsCookie->get(breakpointId)) { - *errorString = "Breakpoint at specified location already exists."; - return; - } - - breakpointsCookie->setObject( - breakpointId, buildObjectForBreakpointCookie( - url, lineNumber, columnNumber, condition, isRegex)); - - ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition); - for (const auto& script : m_scripts) { - if (!matches(m_inspector, script.second->sourceURL(), url, isRegex)) - continue; - std::unique_ptr location = resolveBreakpoint( - breakpointId, script.first, breakpoint, UserBreakpointSource); - if (location) (*locations)->addItem(std::move(location)); - } - - *outBreakpointId = breakpointId; -} - -static bool parseLocation( - ErrorString* errorString, - std::unique_ptr location, String16* scriptId, - int* lineNumber, int* columnNumber) { - *scriptId = location->getScriptId(); - *lineNumber = location->getLineNumber(); - *columnNumber = location->getColumnNumber(0); - return true; -} - -void V8DebuggerAgentImpl::setBreakpoint( - ErrorString* errorString, - std::unique_ptr location, - const Maybe& optionalCondition, String16* outBreakpointId, - std::unique_ptr* actualLocation) { - String16 scriptId; - int lineNumber; - int columnNumber; - - if (!parseLocation(errorString, std::move(location), &scriptId, &lineNumber, - &columnNumber)) - return; - - String16 condition = optionalCondition.fromMaybe(""); - - String16 breakpointId = generateBreakpointId( - scriptId, lineNumber, columnNumber, UserBreakpointSource); - if (m_breakpointIdToDebuggerBreakpointIds.find(breakpointId) != - m_breakpointIdToDebuggerBreakpointIds.end()) { - *errorString = "Breakpoint at specified location already exists."; - return; - } - ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition); - *actualLocation = resolveBreakpoint(breakpointId, scriptId, breakpoint, - UserBreakpointSource); - if (*actualLocation) - *outBreakpointId = breakpointId; - else - *errorString = "Could not resolve breakpoint"; -} - -void V8DebuggerAgentImpl::removeBreakpoint(ErrorString* errorString, - const String16& breakpointId) { - if (!checkEnabled(errorString)) return; - protocol::DictionaryValue* breakpointsCookie = - m_state->getObject(DebuggerAgentState::javaScriptBreakpoints); - if (breakpointsCookie) breakpointsCookie->remove(breakpointId); - removeBreakpoint(breakpointId); -} - -void V8DebuggerAgentImpl::removeBreakpoint(const String16& breakpointId) { - DCHECK(enabled()); - BreakpointIdToDebuggerBreakpointIdsMap::iterator - debuggerBreakpointIdsIterator = - m_breakpointIdToDebuggerBreakpointIds.find(breakpointId); - if (debuggerBreakpointIdsIterator == - m_breakpointIdToDebuggerBreakpointIds.end()) - return; - const std::vector& ids = debuggerBreakpointIdsIterator->second; - for (size_t i = 0; i < ids.size(); ++i) { - const String16& debuggerBreakpointId = ids[i]; - - m_debugger->removeBreakpoint(debuggerBreakpointId); - m_serverBreakpoints.erase(debuggerBreakpointId); - } - m_breakpointIdToDebuggerBreakpointIds.erase(breakpointId); -} - -void V8DebuggerAgentImpl::continueToLocation( - ErrorString* errorString, - std::unique_ptr location) { - if (!checkEnabled(errorString)) return; - if (!m_continueToLocationBreakpointId.isEmpty()) { - m_debugger->removeBreakpoint(m_continueToLocationBreakpointId); - m_continueToLocationBreakpointId = ""; - } - - String16 scriptId; - int lineNumber; - int columnNumber; - - if (!parseLocation(errorString, std::move(location), &scriptId, &lineNumber, - &columnNumber)) - return; - - ScriptBreakpoint breakpoint(lineNumber, columnNumber, ""); - m_continueToLocationBreakpointId = m_debugger->setBreakpoint( - scriptId, breakpoint, &lineNumber, &columnNumber); - resume(errorString); -} - -bool V8DebuggerAgentImpl::isCurrentCallStackEmptyOrBlackboxed() { - DCHECK(enabled()); - JavaScriptCallFrames callFrames = m_debugger->currentCallFrames(); - for (size_t index = 0; index < callFrames.size(); ++index) { - if (!isCallFrameWithUnknownScriptOrBlackboxed(callFrames[index].get())) - return false; - } - return true; -} - -bool V8DebuggerAgentImpl::isTopPausedCallFrameBlackboxed() { - DCHECK(enabled()); - JavaScriptCallFrame* frame = - m_pausedCallFrames.size() ? m_pausedCallFrames[0].get() : nullptr; - return isCallFrameWithUnknownScriptOrBlackboxed(frame); -} - -bool V8DebuggerAgentImpl::isCallFrameWithUnknownScriptOrBlackboxed( - JavaScriptCallFrame* frame) { - if (!frame) return true; - ScriptsMap::iterator it = - m_scripts.find(String16::fromInteger(frame->sourceID())); - if (it == m_scripts.end()) { - // Unknown scripts are blackboxed. - return true; - } - if (m_blackboxPattern) { - const String16& scriptSourceURL = it->second->sourceURL(); - if (!scriptSourceURL.isEmpty() && - m_blackboxPattern->match(scriptSourceURL) != -1) - return true; - } - auto itBlackboxedPositions = - m_blackboxedPositions.find(String16::fromInteger(frame->sourceID())); - if (itBlackboxedPositions == m_blackboxedPositions.end()) return false; - - const std::vector>& ranges = - itBlackboxedPositions->second; - auto itRange = std::lower_bound( - ranges.begin(), ranges.end(), - std::make_pair(frame->line(), frame->column()), positionComparator); - // Ranges array contains positions in script where blackbox state is changed. - // [(0,0) ... ranges[0]) isn't blackboxed, [ranges[0] ... ranges[1]) is - // blackboxed... - return std::distance(ranges.begin(), itRange) % 2; -} - -V8DebuggerAgentImpl::SkipPauseRequest -V8DebuggerAgentImpl::shouldSkipExceptionPause( - JavaScriptCallFrame* topCallFrame) { - if (m_steppingFromFramework) return RequestNoSkip; - if (isCallFrameWithUnknownScriptOrBlackboxed(topCallFrame)) - return RequestContinue; - return RequestNoSkip; -} - -V8DebuggerAgentImpl::SkipPauseRequest V8DebuggerAgentImpl::shouldSkipStepPause( - JavaScriptCallFrame* topCallFrame) { - if (m_steppingFromFramework) return RequestNoSkip; - - if (m_skipNextDebuggerStepOut) { - m_skipNextDebuggerStepOut = false; - if (m_scheduledDebuggerStep == StepOut) return RequestStepOut; - } - - if (!isCallFrameWithUnknownScriptOrBlackboxed(topCallFrame)) - return RequestNoSkip; - - if (m_skippedStepFrameCount >= maxSkipStepFrameCount) return RequestStepOut; - - if (!m_skippedStepFrameCount) m_recursionLevelForStepFrame = 1; - - ++m_skippedStepFrameCount; - return RequestStepFrame; -} - -std::unique_ptr -V8DebuggerAgentImpl::resolveBreakpoint(const String16& breakpointId, - const String16& scriptId, - const ScriptBreakpoint& breakpoint, - BreakpointSource source) { - DCHECK(enabled()); - // FIXME: remove these checks once crbug.com/520702 is resolved. - CHECK(!breakpointId.isEmpty()); - CHECK(!scriptId.isEmpty()); - ScriptsMap::iterator scriptIterator = m_scripts.find(scriptId); - if (scriptIterator == m_scripts.end()) return nullptr; - if (breakpoint.lineNumber < scriptIterator->second->startLine() || - scriptIterator->second->endLine() < breakpoint.lineNumber) - return nullptr; - - int actualLineNumber; - int actualColumnNumber; - String16 debuggerBreakpointId = m_debugger->setBreakpoint( - scriptId, breakpoint, &actualLineNumber, &actualColumnNumber); - if (debuggerBreakpointId.isEmpty()) return nullptr; - - m_serverBreakpoints[debuggerBreakpointId] = - std::make_pair(breakpointId, source); - CHECK(!breakpointId.isEmpty()); - - m_breakpointIdToDebuggerBreakpointIds[breakpointId].push_back( - debuggerBreakpointId); - return buildProtocolLocation(scriptId, actualLineNumber, actualColumnNumber); -} - -void V8DebuggerAgentImpl::searchInContent( - ErrorString* error, const String16& scriptId, const String16& query, - const Maybe& optionalCaseSensitive, - const Maybe& optionalIsRegex, - std::unique_ptr>* results) { - v8::HandleScope handles(m_isolate); - ScriptsMap::iterator it = m_scripts.find(scriptId); - if (it == m_scripts.end()) { - *error = String16("No script for id: " + scriptId); - return; - } - - std::vector> matches = - searchInTextByLinesImpl(m_session, - toProtocolString(it->second->source(m_isolate)), - query, optionalCaseSensitive.fromMaybe(false), - optionalIsRegex.fromMaybe(false)); - *results = protocol::Array::create(); - for (size_t i = 0; i < matches.size(); ++i) - (*results)->addItem(std::move(matches[i])); -} - -void V8DebuggerAgentImpl::setScriptSource( - ErrorString* errorString, const String16& scriptId, - const String16& newContent, const Maybe& dryRun, - Maybe>* newCallFrames, - Maybe* stackChanged, Maybe* asyncStackTrace, - Maybe* optOutCompileError) { - if (!checkEnabled(errorString)) return; - - v8::HandleScope handles(m_isolate); - v8::Local newSource = toV8String(m_isolate, newContent); - if (!m_debugger->setScriptSource(scriptId, newSource, dryRun.fromMaybe(false), - errorString, optOutCompileError, - &m_pausedCallFrames, stackChanged)) - return; - - ScriptsMap::iterator it = m_scripts.find(scriptId); - if (it != m_scripts.end()) it->second->setSource(m_isolate, newSource); - - std::unique_ptr> callFrames = currentCallFrames(errorString); - if (!callFrames) return; - *newCallFrames = std::move(callFrames); - *asyncStackTrace = currentAsyncStackTrace(); -} - -void V8DebuggerAgentImpl::restartFrame( - ErrorString* errorString, const String16& callFrameId, - std::unique_ptr>* newCallFrames, - Maybe* asyncStackTrace) { - if (!assertPaused(errorString)) return; - InjectedScript::CallFrameScope scope( - errorString, m_inspector, m_session->contextGroupId(), callFrameId); - if (!scope.initialize()) return; - if (scope.frameOrdinal() >= m_pausedCallFrames.size()) { - *errorString = "Could not find call frame with given id"; - return; - } - - v8::Local resultValue; - v8::Local result; - if (!m_pausedCallFrames[scope.frameOrdinal()]->restart().ToLocal( - &resultValue) || - scope.tryCatch().HasCaught() || - !resultValue->ToBoolean(scope.context()).ToLocal(&result) || - !result->Value()) { - *errorString = "Internal error"; - return; - } - JavaScriptCallFrames frames = m_debugger->currentCallFrames(); - m_pausedCallFrames.swap(frames); - - *newCallFrames = currentCallFrames(errorString); - if (!*newCallFrames) return; - *asyncStackTrace = currentAsyncStackTrace(); -} - -void V8DebuggerAgentImpl::getScriptSource(ErrorString* error, - const String16& scriptId, - String16* scriptSource) { - if (!checkEnabled(error)) return; - ScriptsMap::iterator it = m_scripts.find(scriptId); - if (it == m_scripts.end()) { - *error = "No script for id: " + scriptId; - return; - } - v8::HandleScope handles(m_isolate); - *scriptSource = toProtocolString(it->second->source(m_isolate)); -} - -void V8DebuggerAgentImpl::schedulePauseOnNextStatement( - const String16& breakReason, - std::unique_ptr data) { - if (!enabled() || m_scheduledDebuggerStep == StepInto || - m_javaScriptPauseScheduled || m_debugger->isPaused() || - !m_debugger->breakpointsActivated()) - return; - m_breakReason = breakReason; - m_breakAuxData = std::move(data); - m_pausingOnNativeEvent = true; - m_skipNextDebuggerStepOut = false; - m_debugger->setPauseOnNextStatement(true); -} - -void V8DebuggerAgentImpl::schedulePauseOnNextStatementIfSteppingInto() { - DCHECK(enabled()); - if (m_scheduledDebuggerStep != StepInto || m_javaScriptPauseScheduled || - m_debugger->isPaused()) - return; - clearBreakDetails(); - m_pausingOnNativeEvent = false; - m_skippedStepFrameCount = 0; - m_recursionLevelForStepFrame = 0; - m_debugger->setPauseOnNextStatement(true); -} - -void V8DebuggerAgentImpl::cancelPauseOnNextStatement() { - if (m_javaScriptPauseScheduled || m_debugger->isPaused()) return; - clearBreakDetails(); - m_pausingOnNativeEvent = false; - m_debugger->setPauseOnNextStatement(false); -} - -void V8DebuggerAgentImpl::pause(ErrorString* errorString) { - if (!checkEnabled(errorString)) return; - if (m_javaScriptPauseScheduled || m_debugger->isPaused()) return; - clearBreakDetails(); - m_javaScriptPauseScheduled = true; - m_scheduledDebuggerStep = NoStep; - m_skippedStepFrameCount = 0; - m_steppingFromFramework = false; - m_debugger->setPauseOnNextStatement(true); -} - -void V8DebuggerAgentImpl::resume(ErrorString* errorString) { - if (!assertPaused(errorString)) return; - m_scheduledDebuggerStep = NoStep; - m_steppingFromFramework = false; - m_session->releaseObjectGroup(backtraceObjectGroup); - m_debugger->continueProgram(); -} - -void V8DebuggerAgentImpl::stepOver(ErrorString* errorString) { - if (!assertPaused(errorString)) return; - // StepOver at function return point should fallback to StepInto. - JavaScriptCallFrame* frame = - !m_pausedCallFrames.empty() ? m_pausedCallFrames[0].get() : nullptr; - if (frame && frame->isAtReturn()) { - stepInto(errorString); - return; - } - m_scheduledDebuggerStep = StepOver; - m_steppingFromFramework = isTopPausedCallFrameBlackboxed(); - m_session->releaseObjectGroup(backtraceObjectGroup); - m_debugger->stepOverStatement(); -} - -void V8DebuggerAgentImpl::stepInto(ErrorString* errorString) { - if (!assertPaused(errorString)) return; - m_scheduledDebuggerStep = StepInto; - m_steppingFromFramework = isTopPausedCallFrameBlackboxed(); - m_session->releaseObjectGroup(backtraceObjectGroup); - m_debugger->stepIntoStatement(); -} - -void V8DebuggerAgentImpl::stepOut(ErrorString* errorString) { - if (!assertPaused(errorString)) return; - m_scheduledDebuggerStep = StepOut; - m_skipNextDebuggerStepOut = false; - m_recursionLevelForStepOut = 1; - m_steppingFromFramework = isTopPausedCallFrameBlackboxed(); - m_session->releaseObjectGroup(backtraceObjectGroup); - m_debugger->stepOutOfFunction(); -} - -void V8DebuggerAgentImpl::setPauseOnExceptions( - ErrorString* errorString, const String16& stringPauseState) { - if (!checkEnabled(errorString)) return; - V8Debugger::PauseOnExceptionsState pauseState; - if (stringPauseState == "none") { - pauseState = V8Debugger::DontPauseOnExceptions; - } else if (stringPauseState == "all") { - pauseState = V8Debugger::PauseOnAllExceptions; - } else if (stringPauseState == "uncaught") { - pauseState = V8Debugger::PauseOnUncaughtExceptions; - } else { - *errorString = "Unknown pause on exceptions mode: " + stringPauseState; - return; - } - setPauseOnExceptionsImpl(errorString, pauseState); -} - -void V8DebuggerAgentImpl::setPauseOnExceptionsImpl(ErrorString* errorString, - int pauseState) { - m_debugger->setPauseOnExceptionsState( - static_cast(pauseState)); - if (m_debugger->getPauseOnExceptionsState() != pauseState) - *errorString = "Internal error. Could not change pause on exceptions state"; - else - m_state->setInteger(DebuggerAgentState::pauseOnExceptionsState, pauseState); -} - -void V8DebuggerAgentImpl::evaluateOnCallFrame( - ErrorString* errorString, const String16& callFrameId, - const String16& expression, const Maybe& objectGroup, - const Maybe& includeCommandLineAPI, const Maybe& silent, - const Maybe& returnByValue, const Maybe& generatePreview, - std::unique_ptr* result, - Maybe* exceptionDetails) { - if (!assertPaused(errorString)) return; - InjectedScript::CallFrameScope scope( - errorString, m_inspector, m_session->contextGroupId(), callFrameId); - if (!scope.initialize()) return; - if (scope.frameOrdinal() >= m_pausedCallFrames.size()) { - *errorString = "Could not find call frame with given id"; - return; - } - - if (includeCommandLineAPI.fromMaybe(false) && !scope.installCommandLineAPI()) - return; - if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole(); - - v8::MaybeLocal maybeResultValue = - m_pausedCallFrames[scope.frameOrdinal()]->evaluate( - toV8String(m_isolate, expression)); - - // Re-initialize after running client's code, as it could have destroyed - // context or session. - if (!scope.initialize()) return; - scope.injectedScript()->wrapEvaluateResult( - errorString, maybeResultValue, scope.tryCatch(), - objectGroup.fromMaybe(""), returnByValue.fromMaybe(false), - generatePreview.fromMaybe(false), result, exceptionDetails); -} - -void V8DebuggerAgentImpl::setVariableValue( - ErrorString* errorString, int scopeNumber, const String16& variableName, - std::unique_ptr newValueArgument, - const String16& callFrameId) { - if (!checkEnabled(errorString)) return; - if (!assertPaused(errorString)) return; - InjectedScript::CallFrameScope scope( - errorString, m_inspector, m_session->contextGroupId(), callFrameId); - if (!scope.initialize()) return; - - v8::Local newValue; - if (!scope.injectedScript() - ->resolveCallArgument(errorString, newValueArgument.get()) - .ToLocal(&newValue)) - return; - - if (scope.frameOrdinal() >= m_pausedCallFrames.size()) { - *errorString = "Could not find call frame with given id"; - return; - } - v8::MaybeLocal result = - m_pausedCallFrames[scope.frameOrdinal()]->setVariableValue( - scopeNumber, toV8String(m_isolate, variableName), newValue); - if (scope.tryCatch().HasCaught() || result.IsEmpty()) { - *errorString = "Internal error"; - return; - } -} - -void V8DebuggerAgentImpl::setAsyncCallStackDepth(ErrorString* errorString, - int depth) { - if (!checkEnabled(errorString)) return; - m_state->setInteger(DebuggerAgentState::asyncCallStackDepth, depth); - m_debugger->setAsyncCallStackDepth(this, depth); -} - -void V8DebuggerAgentImpl::setBlackboxPatterns( - ErrorString* errorString, - std::unique_ptr> patterns) { - if (!patterns->length()) { - m_blackboxPattern = nullptr; - m_state->remove(DebuggerAgentState::blackboxPattern); - return; - } - - String16Builder patternBuilder; - patternBuilder.append('('); - for (size_t i = 0; i < patterns->length() - 1; ++i) { - patternBuilder.append(patterns->get(i)); - patternBuilder.append("|"); - } - patternBuilder.append(patterns->get(patterns->length() - 1)); - patternBuilder.append(')'); - String16 pattern = patternBuilder.toString(); - if (!setBlackboxPattern(errorString, pattern)) return; - m_state->setString(DebuggerAgentState::blackboxPattern, pattern); -} - -bool V8DebuggerAgentImpl::setBlackboxPattern(ErrorString* errorString, - const String16& pattern) { - std::unique_ptr regex(new V8Regex( - m_inspector, pattern, true /** caseSensitive */, false /** multiline */)); - if (!regex->isValid()) { - *errorString = "Pattern parser error: " + regex->errorMessage(); - return false; - } - m_blackboxPattern = std::move(regex); - return true; -} - -void V8DebuggerAgentImpl::setBlackboxedRanges( - ErrorString* error, const String16& scriptId, - std::unique_ptr> - inPositions) { - if (m_scripts.find(scriptId) == m_scripts.end()) { - *error = "No script with passed id."; - return; - } - - if (!inPositions->length()) { - m_blackboxedPositions.erase(scriptId); - return; - } - - std::vector> positions; - positions.reserve(inPositions->length()); - for (size_t i = 0; i < inPositions->length(); ++i) { - protocol::Debugger::ScriptPosition* position = inPositions->get(i); - if (position->getLineNumber() < 0) { - *error = "Position missing 'line' or 'line' < 0."; - return; - } - if (position->getColumnNumber() < 0) { - *error = "Position missing 'column' or 'column' < 0."; - return; - } - positions.push_back( - std::make_pair(position->getLineNumber(), position->getColumnNumber())); - } - - for (size_t i = 1; i < positions.size(); ++i) { - if (positions[i - 1].first < positions[i].first) continue; - if (positions[i - 1].first == positions[i].first && - positions[i - 1].second < positions[i].second) - continue; - *error = - "Input positions array is not sorted or contains duplicate values."; - return; - } - - m_blackboxedPositions[scriptId] = positions; -} - -void V8DebuggerAgentImpl::willExecuteScript(int scriptId) { - changeJavaScriptRecursionLevel(+1); - // Fast return. - if (m_scheduledDebuggerStep != StepInto) return; - schedulePauseOnNextStatementIfSteppingInto(); -} - -void V8DebuggerAgentImpl::didExecuteScript() { - changeJavaScriptRecursionLevel(-1); -} - -void V8DebuggerAgentImpl::changeJavaScriptRecursionLevel(int step) { - if (m_javaScriptPauseScheduled && !m_skipAllPauses && - !m_debugger->isPaused()) { - // Do not ever loose user's pause request until we have actually paused. - m_debugger->setPauseOnNextStatement(true); - } - if (m_scheduledDebuggerStep == StepOut) { - m_recursionLevelForStepOut += step; - if (!m_recursionLevelForStepOut) { - // When StepOut crosses a task boundary (i.e. js -> c++) from where it was - // requested, - // switch stepping to step into a next JS task, as if we exited to a - // blackboxed framework. - m_scheduledDebuggerStep = StepInto; - m_skipNextDebuggerStepOut = false; - } - } - if (m_recursionLevelForStepFrame) { - m_recursionLevelForStepFrame += step; - if (!m_recursionLevelForStepFrame) { - // We have walked through a blackboxed framework and got back to where we - // started. - // If there was no stepping scheduled, we should cancel the stepping - // explicitly, - // since there may be a scheduled StepFrame left. - // Otherwise, if we were stepping in/over, the StepFrame will stop at the - // right location, - // whereas if we were stepping out, we should continue doing so after - // debugger pauses - // from the old StepFrame. - m_skippedStepFrameCount = 0; - if (m_scheduledDebuggerStep == NoStep) - m_debugger->clearStepping(); - else if (m_scheduledDebuggerStep == StepOut) - m_skipNextDebuggerStepOut = true; - } - } -} - -std::unique_ptr> V8DebuggerAgentImpl::currentCallFrames( - ErrorString* errorString) { - if (m_pausedContext.IsEmpty() || !m_pausedCallFrames.size()) - return Array::create(); - ErrorString ignored; - v8::HandleScope handles(m_isolate); - v8::Local debuggerContext = - v8::Debug::GetDebugContext(m_isolate); - v8::Context::Scope contextScope(debuggerContext); - - v8::Local objects = v8::Array::New(m_isolate); - - for (size_t frameOrdinal = 0; frameOrdinal < m_pausedCallFrames.size(); - ++frameOrdinal) { - const std::unique_ptr& currentCallFrame = - m_pausedCallFrames[frameOrdinal]; - - v8::Local details = currentCallFrame->details(); - if (hasInternalError(errorString, details.IsEmpty())) - return Array::create(); - - int contextId = currentCallFrame->contextId(); - InjectedScript* injectedScript = - contextId ? m_session->findInjectedScript(&ignored, contextId) - : nullptr; - - String16 callFrameId = - RemoteCallFrameId::serialize(contextId, static_cast(frameOrdinal)); - if (hasInternalError( - errorString, - !details - ->Set(debuggerContext, - toV8StringInternalized(m_isolate, "callFrameId"), - toV8String(m_isolate, callFrameId)) - .FromMaybe(false))) - return Array::create(); - - if (injectedScript) { - v8::Local scopeChain; - if (hasInternalError( - errorString, - !details->Get(debuggerContext, - toV8StringInternalized(m_isolate, "scopeChain")) - .ToLocal(&scopeChain) || - !scopeChain->IsArray())) - return Array::create(); - v8::Local scopeChainArray = scopeChain.As(); - if (!injectedScript->wrapPropertyInArray( - errorString, scopeChainArray, - toV8StringInternalized(m_isolate, "object"), - backtraceObjectGroup)) - return Array::create(); - if (!injectedScript->wrapObjectProperty( - errorString, details, toV8StringInternalized(m_isolate, "this"), - backtraceObjectGroup)) - return Array::create(); - if (details - ->Has(debuggerContext, - toV8StringInternalized(m_isolate, "returnValue")) - .FromMaybe(false)) { - if (!injectedScript->wrapObjectProperty( - errorString, details, - toV8StringInternalized(m_isolate, "returnValue"), - backtraceObjectGroup)) - return Array::create(); - } - } else { - if (hasInternalError(errorString, !details - ->Set(debuggerContext, - toV8StringInternalized( - m_isolate, "scopeChain"), - v8::Array::New(m_isolate, 0)) - .FromMaybe(false))) - return Array::create(); - v8::Local remoteObject = v8::Object::New(m_isolate); - if (hasInternalError( - errorString, - !remoteObject - ->Set(debuggerContext, - toV8StringInternalized(m_isolate, "type"), - toV8StringInternalized(m_isolate, "undefined")) - .FromMaybe(false))) - return Array::create(); - if (hasInternalError(errorString, - !details - ->Set(debuggerContext, - toV8StringInternalized(m_isolate, "this"), - remoteObject) - .FromMaybe(false))) - return Array::create(); - if (hasInternalError( - errorString, - !details - ->Delete(debuggerContext, - toV8StringInternalized(m_isolate, "returnValue")) - .FromMaybe(false))) - return Array::create(); - } - - if (hasInternalError( - errorString, - !objects - ->Set(debuggerContext, static_cast(frameOrdinal), details) - .FromMaybe(false))) - return Array::create(); - } - - std::unique_ptr protocolValue = - toProtocolValue(errorString, debuggerContext, objects); - if (!protocolValue) return Array::create(); - protocol::ErrorSupport errorSupport; - std::unique_ptr> callFrames = - Array::parse(protocolValue.get(), &errorSupport); - if (hasInternalError(errorString, !callFrames)) - return Array::create(); - return callFrames; -} - -std::unique_ptr V8DebuggerAgentImpl::currentAsyncStackTrace() { - if (m_pausedContext.IsEmpty()) return nullptr; - V8StackTraceImpl* stackTrace = m_debugger->currentAsyncCallChain(); - return stackTrace ? stackTrace->buildInspectorObjectForTail(m_debugger) - : nullptr; -} - -void V8DebuggerAgentImpl::didParseSource( - std::unique_ptr script, bool success) { - v8::HandleScope handles(m_isolate); - String16 scriptSource = toProtocolString(script->source(m_isolate)); - if (!success) script->setSourceURL(findSourceURL(scriptSource, false)); - if (!success) - script->setSourceMappingURL(findSourceMapURL(scriptSource, false)); - - std::unique_ptr executionContextAuxData; - if (!script->executionContextAuxData().isEmpty()) - executionContextAuxData = protocol::DictionaryValue::cast( - protocol::parseJSON(script->executionContextAuxData())); - bool isLiveEdit = script->isLiveEdit(); - bool hasSourceURL = script->hasSourceURL(); - String16 scriptId = script->scriptId(); - String16 scriptURL = script->sourceURL(); - - const Maybe& sourceMapURLParam = script->sourceMappingURL(); - const Maybe& executionContextAuxDataParam( - std::move(executionContextAuxData)); - const bool* isLiveEditParam = isLiveEdit ? &isLiveEdit : nullptr; - const bool* hasSourceURLParam = hasSourceURL ? &hasSourceURL : nullptr; - if (success) - m_frontend.scriptParsed( - scriptId, scriptURL, script->startLine(), script->startColumn(), - script->endLine(), script->endColumn(), script->executionContextId(), - script->hash(), executionContextAuxDataParam, isLiveEditParam, - sourceMapURLParam, hasSourceURLParam); - else - m_frontend.scriptFailedToParse( - scriptId, scriptURL, script->startLine(), script->startColumn(), - script->endLine(), script->endColumn(), script->executionContextId(), - script->hash(), executionContextAuxDataParam, sourceMapURLParam, - hasSourceURLParam); - - m_scripts[scriptId] = std::move(script); - - if (scriptURL.isEmpty() || !success) return; - - protocol::DictionaryValue* breakpointsCookie = - m_state->getObject(DebuggerAgentState::javaScriptBreakpoints); - if (!breakpointsCookie) return; - - for (size_t i = 0; i < breakpointsCookie->size(); ++i) { - auto cookie = breakpointsCookie->at(i); - protocol::DictionaryValue* breakpointObject = - protocol::DictionaryValue::cast(cookie.second); - bool isRegex; - breakpointObject->getBoolean(DebuggerAgentState::isRegex, &isRegex); - String16 url; - breakpointObject->getString(DebuggerAgentState::url, &url); - if (!matches(m_inspector, scriptURL, url, isRegex)) continue; - ScriptBreakpoint breakpoint; - breakpointObject->getInteger(DebuggerAgentState::lineNumber, - &breakpoint.lineNumber); - breakpointObject->getInteger(DebuggerAgentState::columnNumber, - &breakpoint.columnNumber); - breakpointObject->getString(DebuggerAgentState::condition, - &breakpoint.condition); - std::unique_ptr location = resolveBreakpoint( - cookie.first, scriptId, breakpoint, UserBreakpointSource); - if (location) - m_frontend.breakpointResolved(cookie.first, std::move(location)); - } -} - -V8DebuggerAgentImpl::SkipPauseRequest V8DebuggerAgentImpl::didPause( - v8::Local context, v8::Local exception, - const std::vector& hitBreakpoints, bool isPromiseRejection) { - JavaScriptCallFrames callFrames = m_debugger->currentCallFrames(1); - JavaScriptCallFrame* topCallFrame = - !callFrames.empty() ? callFrames.begin()->get() : nullptr; - - V8DebuggerAgentImpl::SkipPauseRequest result; - if (m_skipAllPauses) - result = RequestContinue; - else if (!hitBreakpoints.empty()) - result = RequestNoSkip; // Don't skip explicit breakpoints even if set in - // frameworks. - else if (!exception.IsEmpty()) - result = shouldSkipExceptionPause(topCallFrame); - else if (m_scheduledDebuggerStep != NoStep || m_javaScriptPauseScheduled || - m_pausingOnNativeEvent) - result = shouldSkipStepPause(topCallFrame); - else - result = RequestNoSkip; - - m_skipNextDebuggerStepOut = false; - if (result != RequestNoSkip) return result; - // Skip pauses inside V8 internal scripts and on syntax errors. - if (!topCallFrame) return RequestContinue; - - DCHECK(m_pausedContext.IsEmpty()); - JavaScriptCallFrames frames = m_debugger->currentCallFrames(); - m_pausedCallFrames.swap(frames); - m_pausedContext.Reset(m_isolate, context); - v8::HandleScope handles(m_isolate); - - if (!exception.IsEmpty()) { - ErrorString ignored; - InjectedScript* injectedScript = - m_session->findInjectedScript(&ignored, V8Debugger::contextId(context)); - if (injectedScript) { - m_breakReason = - isPromiseRejection - ? protocol::Debugger::Paused::ReasonEnum::PromiseRejection - : protocol::Debugger::Paused::ReasonEnum::Exception; - ErrorString errorString; - auto obj = injectedScript->wrapObject(&errorString, exception, - backtraceObjectGroup); - m_breakAuxData = obj ? obj->serialize() : nullptr; - // m_breakAuxData might be null after this. - } - } - - std::unique_ptr> hitBreakpointIds = Array::create(); - - for (const auto& point : hitBreakpoints) { - DebugServerBreakpointToBreakpointIdAndSourceMap::iterator - breakpointIterator = m_serverBreakpoints.find(point); - if (breakpointIterator != m_serverBreakpoints.end()) { - const String16& localId = breakpointIterator->second.first; - hitBreakpointIds->addItem(localId); - - BreakpointSource source = breakpointIterator->second.second; - if (m_breakReason == protocol::Debugger::Paused::ReasonEnum::Other && - source == DebugCommandBreakpointSource) - m_breakReason = protocol::Debugger::Paused::ReasonEnum::DebugCommand; - } - } - - ErrorString errorString; - m_frontend.paused(currentCallFrames(&errorString), m_breakReason, - std::move(m_breakAuxData), std::move(hitBreakpointIds), - currentAsyncStackTrace()); - m_scheduledDebuggerStep = NoStep; - m_javaScriptPauseScheduled = false; - m_steppingFromFramework = false; - m_pausingOnNativeEvent = false; - m_skippedStepFrameCount = 0; - m_recursionLevelForStepFrame = 0; - - if (!m_continueToLocationBreakpointId.isEmpty()) { - m_debugger->removeBreakpoint(m_continueToLocationBreakpointId); - m_continueToLocationBreakpointId = ""; - } - return result; -} - -void V8DebuggerAgentImpl::didContinue() { - m_pausedContext.Reset(); - JavaScriptCallFrames emptyCallFrames; - m_pausedCallFrames.swap(emptyCallFrames); - clearBreakDetails(); - m_frontend.resumed(); -} - -void V8DebuggerAgentImpl::breakProgram( - const String16& breakReason, - std::unique_ptr data) { - if (!enabled() || m_skipAllPauses || !m_pausedContext.IsEmpty() || - isCurrentCallStackEmptyOrBlackboxed() || - !m_debugger->breakpointsActivated()) - return; - m_breakReason = breakReason; - m_breakAuxData = std::move(data); - m_scheduledDebuggerStep = NoStep; - m_steppingFromFramework = false; - m_pausingOnNativeEvent = false; - m_debugger->breakProgram(); -} - -void V8DebuggerAgentImpl::breakProgramOnException( - const String16& breakReason, - std::unique_ptr data) { - if (!enabled() || - m_debugger->getPauseOnExceptionsState() == - V8Debugger::DontPauseOnExceptions) - return; - breakProgram(breakReason, std::move(data)); -} - -bool V8DebuggerAgentImpl::assertPaused(ErrorString* errorString) { - if (m_pausedContext.IsEmpty()) { - *errorString = "Can only perform operation while paused."; - return false; - } - return true; -} - -void V8DebuggerAgentImpl::clearBreakDetails() { - m_breakReason = protocol::Debugger::Paused::ReasonEnum::Other; - m_breakAuxData = nullptr; -} - -void V8DebuggerAgentImpl::setBreakpointAt(const String16& scriptId, - int lineNumber, int columnNumber, - BreakpointSource source, - const String16& condition) { - String16 breakpointId = - generateBreakpointId(scriptId, lineNumber, columnNumber, source); - ScriptBreakpoint breakpoint(lineNumber, columnNumber, condition); - resolveBreakpoint(breakpointId, scriptId, breakpoint, source); -} - -void V8DebuggerAgentImpl::removeBreakpointAt(const String16& scriptId, - int lineNumber, int columnNumber, - BreakpointSource source) { - removeBreakpoint( - generateBreakpointId(scriptId, lineNumber, columnNumber, source)); -} - -void V8DebuggerAgentImpl::reset() { - if (!enabled()) return; - m_scheduledDebuggerStep = NoStep; - m_scripts.clear(); - m_blackboxedPositions.clear(); - m_breakpointIdToDebuggerBreakpointIds.clear(); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-debugger-agent-impl.h b/deps/v8_inspector/src/inspector/v8-debugger-agent-impl.h deleted file mode 100644 index 62aa67b64bb33a..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-debugger-agent-impl.h +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2015 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8DEBUGGERAGENTIMPL_H_ -#define V8_INSPECTOR_V8DEBUGGERAGENTIMPL_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/java-script-call-frame.h" -#include "src/inspector/protocol/Debugger.h" -#include "src/inspector/protocol/Forward.h" - -namespace v8_inspector { - -struct ScriptBreakpoint; -class JavaScriptCallFrame; -class PromiseTracker; -class V8Debugger; -class V8DebuggerScript; -class V8InspectorImpl; -class V8InspectorSessionImpl; -class V8Regex; -class V8StackTraceImpl; - -using protocol::ErrorString; -using protocol::Maybe; - -class V8DebuggerAgentImpl : public protocol::Debugger::Backend { - public: - enum SkipPauseRequest { - RequestNoSkip, - RequestContinue, - RequestStepInto, - RequestStepOut, - RequestStepFrame - }; - - enum BreakpointSource { - UserBreakpointSource, - DebugCommandBreakpointSource, - MonitorCommandBreakpointSource - }; - - V8DebuggerAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, - protocol::DictionaryValue* state); - ~V8DebuggerAgentImpl() override; - void restore(); - - // Part of the protocol. - void enable(ErrorString*) override; - void disable(ErrorString*) override; - void setBreakpointsActive(ErrorString*, bool active) override; - void setSkipAllPauses(ErrorString*, bool skip) override; - void setBreakpointByUrl( - ErrorString*, int lineNumber, const Maybe& optionalURL, - const Maybe& optionalURLRegex, - const Maybe& optionalColumnNumber, - const Maybe& optionalCondition, String16*, - std::unique_ptr>* locations) - override; - void setBreakpoint( - ErrorString*, std::unique_ptr, - const Maybe& optionalCondition, String16*, - std::unique_ptr* actualLocation) override; - void removeBreakpoint(ErrorString*, const String16& breakpointId) override; - void continueToLocation( - ErrorString*, std::unique_ptr) override; - void searchInContent( - ErrorString*, const String16& scriptId, const String16& query, - const Maybe& optionalCaseSensitive, - const Maybe& optionalIsRegex, - std::unique_ptr>*) - override; - void setScriptSource( - ErrorString*, const String16& inScriptId, const String16& inScriptSource, - const Maybe& dryRun, - Maybe>* optOutCallFrames, - Maybe* optOutStackChanged, - Maybe* optOutAsyncStackTrace, - Maybe* optOutCompileError) override; - void restartFrame( - ErrorString*, const String16& callFrameId, - std::unique_ptr>* - newCallFrames, - Maybe* asyncStackTrace) override; - void getScriptSource(ErrorString*, const String16& scriptId, - String16* scriptSource) override; - void pause(ErrorString*) override; - void resume(ErrorString*) override; - void stepOver(ErrorString*) override; - void stepInto(ErrorString*) override; - void stepOut(ErrorString*) override; - void setPauseOnExceptions(ErrorString*, const String16& pauseState) override; - void evaluateOnCallFrame( - ErrorString*, const String16& callFrameId, const String16& expression, - const Maybe& objectGroup, - const Maybe& includeCommandLineAPI, const Maybe& silent, - const Maybe& returnByValue, const Maybe& generatePreview, - std::unique_ptr* result, - Maybe*) override; - void setVariableValue( - ErrorString*, int scopeNumber, const String16& variableName, - std::unique_ptr newValue, - const String16& callFrame) override; - void setAsyncCallStackDepth(ErrorString*, int depth) override; - void setBlackboxPatterns( - ErrorString*, - std::unique_ptr> patterns) override; - void setBlackboxedRanges( - ErrorString*, const String16& scriptId, - std::unique_ptr> - positions) override; - - bool enabled(); - - void setBreakpointAt(const String16& scriptId, int lineNumber, - int columnNumber, BreakpointSource, - const String16& condition = String16()); - void removeBreakpointAt(const String16& scriptId, int lineNumber, - int columnNumber, BreakpointSource); - void schedulePauseOnNextStatement( - const String16& breakReason, - std::unique_ptr data); - void cancelPauseOnNextStatement(); - void breakProgram(const String16& breakReason, - std::unique_ptr data); - void breakProgramOnException(const String16& breakReason, - std::unique_ptr data); - - void reset(); - - // Interface for V8InspectorImpl - SkipPauseRequest didPause(v8::Local, - v8::Local exception, - const std::vector& hitBreakpoints, - bool isPromiseRejection); - void didContinue(); - void didParseSource(std::unique_ptr, bool success); - void willExecuteScript(int scriptId); - void didExecuteScript(); - - v8::Isolate* isolate() { return m_isolate; } - - private: - bool checkEnabled(ErrorString*); - void enable(); - - SkipPauseRequest shouldSkipExceptionPause(JavaScriptCallFrame* topCallFrame); - SkipPauseRequest shouldSkipStepPause(JavaScriptCallFrame* topCallFrame); - - void schedulePauseOnNextStatementIfSteppingInto(); - - std::unique_ptr> - currentCallFrames(ErrorString*); - std::unique_ptr currentAsyncStackTrace(); - - void changeJavaScriptRecursionLevel(int step); - - void setPauseOnExceptionsImpl(ErrorString*, int); - - std::unique_ptr resolveBreakpoint( - const String16& breakpointId, const String16& scriptId, - const ScriptBreakpoint&, BreakpointSource); - void removeBreakpoint(const String16& breakpointId); - bool assertPaused(ErrorString*); - void clearBreakDetails(); - - bool isCurrentCallStackEmptyOrBlackboxed(); - bool isTopPausedCallFrameBlackboxed(); - bool isCallFrameWithUnknownScriptOrBlackboxed(JavaScriptCallFrame*); - - void internalSetAsyncCallStackDepth(int); - void increaseCachedSkipStackGeneration(); - - bool setBlackboxPattern(ErrorString*, const String16& pattern); - - using ScriptsMap = - protocol::HashMap>; - using BreakpointIdToDebuggerBreakpointIdsMap = - protocol::HashMap>; - using DebugServerBreakpointToBreakpointIdAndSourceMap = - protocol::HashMap>; - using MuteBreakpoins = protocol::HashMap>; - - enum DebuggerStep { NoStep = 0, StepInto, StepOver, StepOut }; - - V8InspectorImpl* m_inspector; - V8Debugger* m_debugger; - V8InspectorSessionImpl* m_session; - bool m_enabled; - protocol::DictionaryValue* m_state; - protocol::Debugger::Frontend m_frontend; - v8::Isolate* m_isolate; - v8::Global m_pausedContext; - JavaScriptCallFrames m_pausedCallFrames; - ScriptsMap m_scripts; - BreakpointIdToDebuggerBreakpointIdsMap m_breakpointIdToDebuggerBreakpointIds; - DebugServerBreakpointToBreakpointIdAndSourceMap m_serverBreakpoints; - String16 m_continueToLocationBreakpointId; - String16 m_breakReason; - std::unique_ptr m_breakAuxData; - DebuggerStep m_scheduledDebuggerStep; - bool m_skipNextDebuggerStepOut; - bool m_javaScriptPauseScheduled; - bool m_steppingFromFramework; - bool m_pausingOnNativeEvent; - - int m_skippedStepFrameCount; - int m_recursionLevelForStepOut; - int m_recursionLevelForStepFrame; - bool m_skipAllPauses; - - std::unique_ptr m_blackboxPattern; - protocol::HashMap>> - m_blackboxedPositions; - - DISALLOW_COPY_AND_ASSIGN(V8DebuggerAgentImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8DEBUGGERAGENTIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-debugger-script.cc b/deps/v8_inspector/src/inspector/v8-debugger-script.cc deleted file mode 100644 index 485188a48f4eac..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-debugger-script.cc +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2014 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. - -#include "src/inspector/v8-debugger-script.h" - -#include "src/inspector/protocol-platform.h" -#include "src/inspector/string-util.h" - -namespace v8_inspector { - -static const char hexDigits[17] = "0123456789ABCDEF"; - -static void appendUnsignedAsHex(uint64_t number, String16Builder* destination) { - for (size_t i = 0; i < 8; ++i) { - UChar c = hexDigits[number & 0xF]; - destination->append(c); - number >>= 4; - } -} - -// Hash algorithm for substrings is described in "Über die Komplexität der -// Multiplikation in -// eingeschränkten Branchingprogrammmodellen" by Woelfe. -// http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000 -static String16 calculateHash(const String16& str) { - static uint64_t prime[] = {0x3FB75161, 0xAB1F4E4F, 0x82675BC5, 0xCD924D35, - 0x81ABE279}; - static uint64_t random[] = {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, - 0xC3D2E1F0}; - static uint32_t randomOdd[] = {0xB4663807, 0xCC322BF5, 0xD4F91BBD, 0xA7BEA11D, - 0x8F462907}; - - uint64_t hashes[] = {0, 0, 0, 0, 0}; - uint64_t zi[] = {1, 1, 1, 1, 1}; - - const size_t hashesSize = arraysize(hashes); - - size_t current = 0; - const uint32_t* data = nullptr; - size_t sizeInBytes = sizeof(UChar) * str.length(); - data = reinterpret_cast(str.characters16()); - for (size_t i = 0; i < sizeInBytes / 4; i += 4) { - uint32_t v = data[i]; - uint64_t xi = v * randomOdd[current] & 0x7FFFFFFF; - hashes[current] = (hashes[current] + zi[current] * xi) % prime[current]; - zi[current] = (zi[current] * random[current]) % prime[current]; - current = current == hashesSize - 1 ? 0 : current + 1; - } - if (sizeInBytes % 4) { - uint32_t v = 0; - for (size_t i = sizeInBytes - sizeInBytes % 4; i < sizeInBytes; ++i) { - v <<= 8; - v |= reinterpret_cast(data)[i]; - } - uint64_t xi = v * randomOdd[current] & 0x7FFFFFFF; - hashes[current] = (hashes[current] + zi[current] * xi) % prime[current]; - zi[current] = (zi[current] * random[current]) % prime[current]; - current = current == hashesSize - 1 ? 0 : current + 1; - } - - for (size_t i = 0; i < hashesSize; ++i) - hashes[i] = (hashes[i] + zi[i] * (prime[i] - 1)) % prime[i]; - - String16Builder hash; - for (size_t i = 0; i < hashesSize; ++i) appendUnsignedAsHex(hashes[i], &hash); - return hash.toString(); -} - -static v8::Local GetChecked(v8::Local context, - v8::Local object, - const char* name) { - return object - ->Get(context, toV8StringInternalized(context->GetIsolate(), name)) - .ToLocalChecked(); -} - -static int GetCheckedInt(v8::Local context, - v8::Local object, const char* name) { - return static_cast(GetChecked(context, object, name) - ->ToInteger(context) - .ToLocalChecked() - ->Value()); -} - -V8DebuggerScript::V8DebuggerScript(v8::Local context, - v8::Local object, - bool isLiveEdit) { - v8::Isolate* isolate = context->GetIsolate(); - v8::Local idValue = GetChecked(context, object, "id"); - DCHECK(!idValue.IsEmpty() && idValue->IsInt32()); - m_id = String16::fromInteger(idValue->Int32Value(context).FromJust()); - - m_url = toProtocolStringWithTypeCheck(GetChecked(context, object, "name")); - m_sourceURL = - toProtocolStringWithTypeCheck(GetChecked(context, object, "sourceURL")); - m_sourceMappingURL = toProtocolStringWithTypeCheck( - GetChecked(context, object, "sourceMappingURL")); - m_startLine = GetCheckedInt(context, object, "startLine"); - m_startColumn = GetCheckedInt(context, object, "startColumn"); - m_endLine = GetCheckedInt(context, object, "endLine"); - m_endColumn = GetCheckedInt(context, object, "endColumn"); - m_executionContextAuxData = toProtocolStringWithTypeCheck( - GetChecked(context, object, "executionContextAuxData")); - m_executionContextId = GetCheckedInt(context, object, "executionContextId"); - m_isLiveEdit = isLiveEdit; - - v8::Local sourceValue; - if (!object->Get(context, toV8StringInternalized(isolate, "source")) - .ToLocal(&sourceValue) || - !sourceValue->IsString()) - return; - setSource(isolate, sourceValue.As()); -} - -V8DebuggerScript::~V8DebuggerScript() {} - -const String16& V8DebuggerScript::sourceURL() const { - return m_sourceURL.isEmpty() ? m_url : m_sourceURL; -} - -v8::Local V8DebuggerScript::source(v8::Isolate* isolate) const { - return m_source.Get(isolate); -} - -void V8DebuggerScript::setSourceURL(const String16& sourceURL) { - m_sourceURL = sourceURL; -} - -void V8DebuggerScript::setSourceMappingURL(const String16& sourceMappingURL) { - m_sourceMappingURL = sourceMappingURL; -} - -void V8DebuggerScript::setSource(v8::Isolate* isolate, - v8::Local source) { - m_source.Reset(isolate, source); - m_hash = calculateHash(toProtocolString(source)); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-debugger-script.h b/deps/v8_inspector/src/inspector/v8-debugger-script.h deleted file mode 100644 index 78c44b5eb97cb4..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-debugger-script.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2008 Apple Inc. All rights reserved. - * Copyright (C) 2010 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of - * its contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_V8DEBUGGERSCRIPT_H_ -#define V8_INSPECTOR_V8DEBUGGERSCRIPT_H_ - -#include "src/base/macros.h" -#include "src/inspector/string-16.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class V8DebuggerScript { - public: - V8DebuggerScript(v8::Local, v8::Local, - bool isLiveEdit); - ~V8DebuggerScript(); - - const String16& scriptId() const { return m_id; } - const String16& url() const { return m_url; } - bool hasSourceURL() const { return !m_sourceURL.isEmpty(); } - const String16& sourceURL() const; - const String16& sourceMappingURL() const { return m_sourceMappingURL; } - v8::Local source(v8::Isolate*) const; - const String16& hash() const { return m_hash; } - int startLine() const { return m_startLine; } - int startColumn() const { return m_startColumn; } - int endLine() const { return m_endLine; } - int endColumn() const { return m_endColumn; } - int executionContextId() const { return m_executionContextId; } - const String16& executionContextAuxData() const { - return m_executionContextAuxData; - } - bool isLiveEdit() const { return m_isLiveEdit; } - - void setSourceURL(const String16&); - void setSourceMappingURL(const String16&); - void setSource(v8::Isolate*, v8::Local); - - private: - String16 m_id; - String16 m_url; - String16 m_sourceURL; - String16 m_sourceMappingURL; - v8::Global m_source; - String16 m_hash; - int m_startLine; - int m_startColumn; - int m_endLine; - int m_endColumn; - int m_executionContextId; - String16 m_executionContextAuxData; - bool m_isLiveEdit; - - DISALLOW_COPY_AND_ASSIGN(V8DebuggerScript); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8DEBUGGERSCRIPT_H_ diff --git a/deps/v8_inspector/src/inspector/v8-debugger.cc b/deps/v8_inspector/src/inspector/v8-debugger.cc deleted file mode 100644 index d393f81ad4a38a..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-debugger.cc +++ /dev/null @@ -1,1002 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-debugger.h" - -#include "src/inspector/debugger-script.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/script-breakpoint.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger-agent-impl.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-internal-value-type.h" -#include "src/inspector/v8-stack-trace-impl.h" -#include "src/inspector/v8-value-copier.h" - -namespace v8_inspector { - -namespace { -const char stepIntoV8MethodName[] = "stepIntoStatement"; -const char stepOutV8MethodName[] = "stepOutOfFunction"; -static const char v8AsyncTaskEventEnqueue[] = "enqueue"; -static const char v8AsyncTaskEventEnqueueRecurring[] = "enqueueRecurring"; -static const char v8AsyncTaskEventWillHandle[] = "willHandle"; -static const char v8AsyncTaskEventDidHandle[] = "didHandle"; -static const char v8AsyncTaskEventCancel[] = "cancel"; - -inline v8::Local v8Boolean(bool value, v8::Isolate* isolate) { - return value ? v8::True(isolate) : v8::False(isolate); -} - -} // namespace - -static bool inLiveEditScope = false; - -v8::MaybeLocal V8Debugger::callDebuggerMethod( - const char* functionName, int argc, v8::Local argv[]) { - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - DCHECK(m_isolate->InContext()); - v8::Local context = m_isolate->GetCurrentContext(); - v8::Local debuggerScript = m_debuggerScript.Get(m_isolate); - v8::Local function = v8::Local::Cast( - debuggerScript - ->Get(context, toV8StringInternalized(m_isolate, functionName)) - .ToLocalChecked()); - return function->Call(context, debuggerScript, argc, argv); -} - -V8Debugger::V8Debugger(v8::Isolate* isolate, V8InspectorImpl* inspector) - : m_isolate(isolate), - m_inspector(inspector), - m_lastContextId(0), - m_enableCount(0), - m_breakpointsActivated(true), - m_runningNestedMessageLoop(false), - m_ignoreScriptParsedEventsCounter(0), - m_maxAsyncCallStackDepth(0) {} - -V8Debugger::~V8Debugger() {} - -void V8Debugger::enable() { - if (m_enableCount++) return; - DCHECK(!enabled()); - v8::HandleScope scope(m_isolate); - v8::Debug::SetDebugEventListener(m_isolate, &V8Debugger::v8DebugEventCallback, - v8::External::New(m_isolate, this)); - m_debuggerContext.Reset(m_isolate, v8::Debug::GetDebugContext(m_isolate)); - compileDebuggerScript(); -} - -void V8Debugger::disable() { - if (--m_enableCount) return; - DCHECK(enabled()); - clearBreakpoints(); - m_debuggerScript.Reset(); - m_debuggerContext.Reset(); - allAsyncTasksCanceled(); - v8::Debug::SetDebugEventListener(m_isolate, nullptr); -} - -bool V8Debugger::enabled() const { return !m_debuggerScript.IsEmpty(); } - -// static -int V8Debugger::contextId(v8::Local context) { - v8::Local data = - context->GetEmbedderData(static_cast(v8::Context::kDebugIdIndex)); - if (data.IsEmpty() || !data->IsString()) return 0; - String16 dataString = toProtocolString(data.As()); - if (dataString.isEmpty()) return 0; - size_t commaPos = dataString.find(","); - if (commaPos == String16::kNotFound) return 0; - size_t commaPos2 = dataString.find(",", commaPos + 1); - if (commaPos2 == String16::kNotFound) return 0; - return dataString.substring(commaPos + 1, commaPos2 - commaPos - 1) - .toInteger(); -} - -// static -int V8Debugger::getGroupId(v8::Local context) { - v8::Local data = - context->GetEmbedderData(static_cast(v8::Context::kDebugIdIndex)); - if (data.IsEmpty() || !data->IsString()) return 0; - String16 dataString = toProtocolString(data.As()); - if (dataString.isEmpty()) return 0; - size_t commaPos = dataString.find(","); - if (commaPos == String16::kNotFound) return 0; - return dataString.substring(0, commaPos).toInteger(); -} - -void V8Debugger::getCompiledScripts( - int contextGroupId, - std::vector>& result) { - v8::HandleScope scope(m_isolate); - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local context = debuggerContext(); - v8::Local debuggerScript = m_debuggerScript.Get(m_isolate); - DCHECK(!debuggerScript->IsUndefined()); - v8::Local getScriptsFunction = v8::Local::Cast( - debuggerScript - ->Get(context, toV8StringInternalized(m_isolate, "getScripts")) - .ToLocalChecked()); - v8::Local argv[] = {v8::Integer::New(m_isolate, contextGroupId)}; - v8::Local value; - if (!getScriptsFunction->Call(context, debuggerScript, arraysize(argv), argv) - .ToLocal(&value)) - return; - DCHECK(value->IsArray()); - v8::Local scriptsArray = v8::Local::Cast(value); - result.reserve(scriptsArray->Length()); - for (unsigned i = 0; i < scriptsArray->Length(); ++i) { - v8::Local scriptObject = v8::Local::Cast( - scriptsArray->Get(context, v8::Integer::New(m_isolate, i)) - .ToLocalChecked()); - result.push_back(wrapUnique( - new V8DebuggerScript(context, scriptObject, inLiveEditScope))); - } -} - -String16 V8Debugger::setBreakpoint(const String16& sourceID, - const ScriptBreakpoint& scriptBreakpoint, - int* actualLineNumber, - int* actualColumnNumber) { - v8::HandleScope scope(m_isolate); - v8::Local context = debuggerContext(); - v8::Context::Scope contextScope(context); - - v8::Local info = v8::Object::New(m_isolate); - bool success = false; - success = info->Set(context, toV8StringInternalized(m_isolate, "sourceID"), - toV8String(m_isolate, sourceID)) - .FromMaybe(false); - DCHECK(success); - success = info->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), - v8::Integer::New(m_isolate, scriptBreakpoint.lineNumber)) - .FromMaybe(false); - DCHECK(success); - success = - info->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), - v8::Integer::New(m_isolate, scriptBreakpoint.columnNumber)) - .FromMaybe(false); - DCHECK(success); - success = info->Set(context, toV8StringInternalized(m_isolate, "condition"), - toV8String(m_isolate, scriptBreakpoint.condition)) - .FromMaybe(false); - DCHECK(success); - - v8::Local setBreakpointFunction = v8::Local::Cast( - m_debuggerScript.Get(m_isolate) - ->Get(context, toV8StringInternalized(m_isolate, "setBreakpoint")) - .ToLocalChecked()); - v8::Local breakpointId = - v8::Debug::Call(debuggerContext(), setBreakpointFunction, info) - .ToLocalChecked(); - if (!breakpointId->IsString()) return ""; - *actualLineNumber = - info->Get(context, toV8StringInternalized(m_isolate, "lineNumber")) - .ToLocalChecked() - ->Int32Value(context) - .FromJust(); - *actualColumnNumber = - info->Get(context, toV8StringInternalized(m_isolate, "columnNumber")) - .ToLocalChecked() - ->Int32Value(context) - .FromJust(); - return toProtocolString(breakpointId.As()); -} - -void V8Debugger::removeBreakpoint(const String16& breakpointId) { - v8::HandleScope scope(m_isolate); - v8::Local context = debuggerContext(); - v8::Context::Scope contextScope(context); - - v8::Local info = v8::Object::New(m_isolate); - bool success = false; - success = - info->Set(context, toV8StringInternalized(m_isolate, "breakpointId"), - toV8String(m_isolate, breakpointId)) - .FromMaybe(false); - DCHECK(success); - - v8::Local removeBreakpointFunction = - v8::Local::Cast( - m_debuggerScript.Get(m_isolate) - ->Get(context, - toV8StringInternalized(m_isolate, "removeBreakpoint")) - .ToLocalChecked()); - v8::Debug::Call(debuggerContext(), removeBreakpointFunction, info) - .ToLocalChecked(); -} - -void V8Debugger::clearBreakpoints() { - v8::HandleScope scope(m_isolate); - v8::Local context = debuggerContext(); - v8::Context::Scope contextScope(context); - - v8::Local clearBreakpoints = v8::Local::Cast( - m_debuggerScript.Get(m_isolate) - ->Get(context, toV8StringInternalized(m_isolate, "clearBreakpoints")) - .ToLocalChecked()); - v8::Debug::Call(debuggerContext(), clearBreakpoints).ToLocalChecked(); -} - -void V8Debugger::setBreakpointsActivated(bool activated) { - if (!enabled()) { - UNREACHABLE(); - return; - } - v8::HandleScope scope(m_isolate); - v8::Local context = debuggerContext(); - v8::Context::Scope contextScope(context); - - v8::Local info = v8::Object::New(m_isolate); - bool success = false; - success = info->Set(context, toV8StringInternalized(m_isolate, "enabled"), - v8::Boolean::New(m_isolate, activated)) - .FromMaybe(false); - DCHECK(success); - v8::Local setBreakpointsActivated = - v8::Local::Cast( - m_debuggerScript.Get(m_isolate) - ->Get(context, toV8StringInternalized(m_isolate, - "setBreakpointsActivated")) - .ToLocalChecked()); - v8::Debug::Call(debuggerContext(), setBreakpointsActivated, info) - .ToLocalChecked(); - - m_breakpointsActivated = activated; -} - -V8Debugger::PauseOnExceptionsState V8Debugger::getPauseOnExceptionsState() { - DCHECK(enabled()); - v8::HandleScope scope(m_isolate); - v8::Local context = debuggerContext(); - v8::Context::Scope contextScope(context); - - v8::Local argv[] = {v8::Undefined(m_isolate)}; - v8::Local result = - callDebuggerMethod("pauseOnExceptionsState", 0, argv).ToLocalChecked(); - return static_cast( - result->Int32Value(context).FromJust()); -} - -void V8Debugger::setPauseOnExceptionsState( - PauseOnExceptionsState pauseOnExceptionsState) { - DCHECK(enabled()); - v8::HandleScope scope(m_isolate); - v8::Context::Scope contextScope(debuggerContext()); - - v8::Local argv[] = { - v8::Int32::New(m_isolate, pauseOnExceptionsState)}; - callDebuggerMethod("setPauseOnExceptionsState", 1, argv); -} - -void V8Debugger::setPauseOnNextStatement(bool pause) { - if (m_runningNestedMessageLoop) return; - if (pause) - v8::Debug::DebugBreak(m_isolate); - else - v8::Debug::CancelDebugBreak(m_isolate); -} - -bool V8Debugger::canBreakProgram() { - if (!m_breakpointsActivated) return false; - return m_isolate->InContext(); -} - -void V8Debugger::breakProgram() { - if (isPaused()) { - DCHECK(!m_runningNestedMessageLoop); - v8::Local exception; - v8::Local hitBreakpoints; - handleProgramBreak(m_pausedContext, m_executionState, exception, - hitBreakpoints); - return; - } - - if (!canBreakProgram()) return; - - v8::HandleScope scope(m_isolate); - v8::Local breakFunction; - if (!v8::Function::New(m_isolate->GetCurrentContext(), - &V8Debugger::breakProgramCallback, - v8::External::New(m_isolate, this), 0, - v8::ConstructorBehavior::kThrow) - .ToLocal(&breakFunction)) - return; - v8::Debug::Call(debuggerContext(), breakFunction).ToLocalChecked(); -} - -void V8Debugger::continueProgram() { - if (isPaused()) m_inspector->client()->quitMessageLoopOnPause(); - m_pausedContext.Clear(); - m_executionState.Clear(); -} - -void V8Debugger::stepIntoStatement() { - DCHECK(isPaused()); - DCHECK(!m_executionState.IsEmpty()); - v8::HandleScope handleScope(m_isolate); - v8::Local argv[] = {m_executionState}; - callDebuggerMethod(stepIntoV8MethodName, 1, argv); - continueProgram(); -} - -void V8Debugger::stepOverStatement() { - DCHECK(isPaused()); - DCHECK(!m_executionState.IsEmpty()); - v8::HandleScope handleScope(m_isolate); - v8::Local argv[] = {m_executionState}; - callDebuggerMethod("stepOverStatement", 1, argv); - continueProgram(); -} - -void V8Debugger::stepOutOfFunction() { - DCHECK(isPaused()); - DCHECK(!m_executionState.IsEmpty()); - v8::HandleScope handleScope(m_isolate); - v8::Local argv[] = {m_executionState}; - callDebuggerMethod(stepOutV8MethodName, 1, argv); - continueProgram(); -} - -void V8Debugger::clearStepping() { - DCHECK(enabled()); - v8::HandleScope scope(m_isolate); - v8::Context::Scope contextScope(debuggerContext()); - - v8::Local argv[] = {v8::Undefined(m_isolate)}; - callDebuggerMethod("clearStepping", 0, argv); -} - -bool V8Debugger::setScriptSource( - const String16& sourceID, v8::Local newSource, bool dryRun, - ErrorString* error, - Maybe* exceptionDetails, - JavaScriptCallFrames* newCallFrames, Maybe* stackChanged) { - class EnableLiveEditScope { - public: - explicit EnableLiveEditScope(v8::Isolate* isolate) : m_isolate(isolate) { - v8::Debug::SetLiveEditEnabled(m_isolate, true); - inLiveEditScope = true; - } - ~EnableLiveEditScope() { - v8::Debug::SetLiveEditEnabled(m_isolate, false); - inLiveEditScope = false; - } - - private: - v8::Isolate* m_isolate; - }; - - DCHECK(enabled()); - v8::HandleScope scope(m_isolate); - - std::unique_ptr contextScope; - if (!isPaused()) - contextScope = wrapUnique(new v8::Context::Scope(debuggerContext())); - - v8::Local argv[] = {toV8String(m_isolate, sourceID), newSource, - v8Boolean(dryRun, m_isolate)}; - - v8::Local v8result; - { - EnableLiveEditScope enableLiveEditScope(m_isolate); - v8::TryCatch tryCatch(m_isolate); - tryCatch.SetVerbose(false); - v8::MaybeLocal maybeResult = - callDebuggerMethod("liveEditScriptSource", 3, argv); - if (tryCatch.HasCaught()) { - v8::Local message = tryCatch.Message(); - if (!message.IsEmpty()) - *error = toProtocolStringWithTypeCheck(message->Get()); - else - *error = "Unknown error."; - return false; - } - v8result = maybeResult.ToLocalChecked(); - } - DCHECK(!v8result.IsEmpty()); - v8::Local context = m_isolate->GetCurrentContext(); - v8::Local resultTuple = - v8result->ToObject(context).ToLocalChecked(); - int code = static_cast(resultTuple->Get(context, 0) - .ToLocalChecked() - ->ToInteger(context) - .ToLocalChecked() - ->Value()); - switch (code) { - case 0: { - *stackChanged = resultTuple->Get(context, 1) - .ToLocalChecked() - ->BooleanValue(context) - .FromJust(); - // Call stack may have changed after if the edited function was on the - // stack. - if (!dryRun && isPaused()) { - JavaScriptCallFrames frames = currentCallFrames(); - newCallFrames->swap(frames); - } - return true; - } - // Compile error. - case 1: { - *exceptionDetails = - protocol::Runtime::ExceptionDetails::create() - .setExceptionId(m_inspector->nextExceptionId()) - .setText(toProtocolStringWithTypeCheck( - resultTuple->Get(context, 2).ToLocalChecked())) - .setLineNumber(static_cast(resultTuple->Get(context, 3) - .ToLocalChecked() - ->ToInteger(context) - .ToLocalChecked() - ->Value()) - - 1) - .setColumnNumber(static_cast(resultTuple->Get(context, 4) - .ToLocalChecked() - ->ToInteger(context) - .ToLocalChecked() - ->Value()) - - 1) - .build(); - return false; - } - } - *error = "Unknown error."; - return false; -} - -JavaScriptCallFrames V8Debugger::currentCallFrames(int limit) { - if (!m_isolate->InContext()) return JavaScriptCallFrames(); - v8::Local currentCallFramesV8; - if (m_executionState.IsEmpty()) { - v8::Local currentCallFramesFunction = - v8::Local::Cast( - m_debuggerScript.Get(m_isolate) - ->Get(debuggerContext(), - toV8StringInternalized(m_isolate, "currentCallFrames")) - .ToLocalChecked()); - currentCallFramesV8 = - v8::Debug::Call(debuggerContext(), currentCallFramesFunction, - v8::Integer::New(m_isolate, limit)) - .ToLocalChecked(); - } else { - v8::Local argv[] = {m_executionState, - v8::Integer::New(m_isolate, limit)}; - currentCallFramesV8 = - callDebuggerMethod("currentCallFrames", arraysize(argv), argv) - .ToLocalChecked(); - } - DCHECK(!currentCallFramesV8.IsEmpty()); - if (!currentCallFramesV8->IsArray()) return JavaScriptCallFrames(); - v8::Local callFramesArray = currentCallFramesV8.As(); - JavaScriptCallFrames callFrames; - for (uint32_t i = 0; i < callFramesArray->Length(); ++i) { - v8::Local callFrameValue; - if (!callFramesArray->Get(debuggerContext(), i).ToLocal(&callFrameValue)) - return JavaScriptCallFrames(); - if (!callFrameValue->IsObject()) return JavaScriptCallFrames(); - v8::Local callFrameObject = callFrameValue.As(); - callFrames.push_back(JavaScriptCallFrame::create( - debuggerContext(), v8::Local::Cast(callFrameObject))); - } - return callFrames; -} - -static V8Debugger* toV8Debugger(v8::Local data) { - void* p = v8::Local::Cast(data)->Value(); - return static_cast(p); -} - -void V8Debugger::breakProgramCallback( - const v8::FunctionCallbackInfo& info) { - DCHECK_EQ(info.Length(), 2); - V8Debugger* thisPtr = toV8Debugger(info.Data()); - if (!thisPtr->enabled()) return; - v8::Local pausedContext = - thisPtr->m_isolate->GetCurrentContext(); - v8::Local exception; - v8::Local hitBreakpoints; - thisPtr->handleProgramBreak(pausedContext, - v8::Local::Cast(info[0]), exception, - hitBreakpoints); -} - -void V8Debugger::handleProgramBreak(v8::Local pausedContext, - v8::Local executionState, - v8::Local exception, - v8::Local hitBreakpointNumbers, - bool isPromiseRejection) { - // Don't allow nested breaks. - if (m_runningNestedMessageLoop) return; - - V8DebuggerAgentImpl* agent = - m_inspector->enabledDebuggerAgentForGroup(getGroupId(pausedContext)); - if (!agent) return; - - std::vector breakpointIds; - if (!hitBreakpointNumbers.IsEmpty()) { - breakpointIds.reserve(hitBreakpointNumbers->Length()); - for (uint32_t i = 0; i < hitBreakpointNumbers->Length(); i++) { - v8::Local hitBreakpointNumber = - hitBreakpointNumbers->Get(debuggerContext(), i).ToLocalChecked(); - DCHECK(hitBreakpointNumber->IsInt32()); - breakpointIds.push_back(String16::fromInteger( - hitBreakpointNumber->Int32Value(debuggerContext()).FromJust())); - } - } - - m_pausedContext = pausedContext; - m_executionState = executionState; - V8DebuggerAgentImpl::SkipPauseRequest result = agent->didPause( - pausedContext, exception, breakpointIds, isPromiseRejection); - if (result == V8DebuggerAgentImpl::RequestNoSkip) { - m_runningNestedMessageLoop = true; - int groupId = getGroupId(pausedContext); - DCHECK(groupId); - m_inspector->client()->runMessageLoopOnPause(groupId); - // The agent may have been removed in the nested loop. - agent = - m_inspector->enabledDebuggerAgentForGroup(getGroupId(pausedContext)); - if (agent) agent->didContinue(); - m_runningNestedMessageLoop = false; - } - m_pausedContext.Clear(); - m_executionState.Clear(); - - if (result == V8DebuggerAgentImpl::RequestStepFrame) { - v8::Local argv[] = {executionState}; - callDebuggerMethod("stepFrameStatement", 1, argv); - } else if (result == V8DebuggerAgentImpl::RequestStepInto) { - v8::Local argv[] = {executionState}; - callDebuggerMethod(stepIntoV8MethodName, 1, argv); - } else if (result == V8DebuggerAgentImpl::RequestStepOut) { - v8::Local argv[] = {executionState}; - callDebuggerMethod(stepOutV8MethodName, 1, argv); - } -} - -void V8Debugger::v8DebugEventCallback( - const v8::Debug::EventDetails& eventDetails) { - V8Debugger* thisPtr = toV8Debugger(eventDetails.GetCallbackData()); - thisPtr->handleV8DebugEvent(eventDetails); -} - -v8::Local V8Debugger::callInternalGetterFunction( - v8::Local object, const char* functionName) { - v8::MicrotasksScope microtasks(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::Local getterValue = - object - ->Get(m_isolate->GetCurrentContext(), - toV8StringInternalized(m_isolate, functionName)) - .ToLocalChecked(); - DCHECK(!getterValue.IsEmpty() && getterValue->IsFunction()); - return v8::Local::Cast(getterValue) - ->Call(m_isolate->GetCurrentContext(), object, 0, 0) - .ToLocalChecked(); -} - -void V8Debugger::handleV8DebugEvent( - const v8::Debug::EventDetails& eventDetails) { - if (!enabled()) return; - v8::DebugEvent event = eventDetails.GetEvent(); - if (event != v8::AsyncTaskEvent && event != v8::Break && - event != v8::Exception && event != v8::AfterCompile && - event != v8::BeforeCompile && event != v8::CompileError) - return; - - v8::Local eventContext = eventDetails.GetEventContext(); - DCHECK(!eventContext.IsEmpty()); - - if (event == v8::AsyncTaskEvent) { - v8::HandleScope scope(m_isolate); - handleV8AsyncTaskEvent(eventContext, eventDetails.GetExecutionState(), - eventDetails.GetEventData()); - return; - } - - V8DebuggerAgentImpl* agent = - m_inspector->enabledDebuggerAgentForGroup(getGroupId(eventContext)); - if (agent) { - v8::HandleScope scope(m_isolate); - if (m_ignoreScriptParsedEventsCounter == 0 && - (event == v8::AfterCompile || event == v8::CompileError)) { - v8::Context::Scope contextScope(debuggerContext()); - v8::Local argv[] = {eventDetails.GetEventData()}; - v8::Local value = - callDebuggerMethod("getAfterCompileScript", 1, argv).ToLocalChecked(); - if (value->IsNull()) return; - DCHECK(value->IsObject()); - v8::Local scriptObject = v8::Local::Cast(value); - agent->didParseSource( - wrapUnique(new V8DebuggerScript(debuggerContext(), scriptObject, - inLiveEditScope)), - event == v8::AfterCompile); - } else if (event == v8::Exception) { - v8::Local eventData = eventDetails.GetEventData(); - v8::Local exception = - callInternalGetterFunction(eventData, "exception"); - v8::Local promise = - callInternalGetterFunction(eventData, "promise"); - bool isPromiseRejection = !promise.IsEmpty() && promise->IsObject(); - handleProgramBreak(eventContext, eventDetails.GetExecutionState(), - exception, v8::Local(), isPromiseRejection); - } else if (event == v8::Break) { - v8::Local argv[] = {eventDetails.GetEventData()}; - v8::Local hitBreakpoints = - callDebuggerMethod("getBreakpointNumbers", 1, argv).ToLocalChecked(); - DCHECK(hitBreakpoints->IsArray()); - handleProgramBreak(eventContext, eventDetails.GetExecutionState(), - v8::Local(), - hitBreakpoints.As()); - } - } -} - -void V8Debugger::handleV8AsyncTaskEvent(v8::Local context, - v8::Local executionState, - v8::Local eventData) { - if (!m_maxAsyncCallStackDepth) return; - - String16 type = toProtocolStringWithTypeCheck( - callInternalGetterFunction(eventData, "type")); - String16 name = toProtocolStringWithTypeCheck( - callInternalGetterFunction(eventData, "name")); - int id = static_cast(callInternalGetterFunction(eventData, "id") - ->ToInteger(context) - .ToLocalChecked() - ->Value()); - // Async task events from Promises are given misaligned pointers to prevent - // from overlapping with other Blink task identifiers. There is a single - // namespace of such ids, managed by src/js/promise.js. - void* ptr = reinterpret_cast(id * 2 + 1); - if (type == v8AsyncTaskEventEnqueue) - asyncTaskScheduled(name, ptr, false); - else if (type == v8AsyncTaskEventEnqueueRecurring) - asyncTaskScheduled(name, ptr, true); - else if (type == v8AsyncTaskEventWillHandle) - asyncTaskStarted(ptr); - else if (type == v8AsyncTaskEventDidHandle) - asyncTaskFinished(ptr); - else if (type == v8AsyncTaskEventCancel) - asyncTaskCanceled(ptr); - else - UNREACHABLE(); -} - -V8StackTraceImpl* V8Debugger::currentAsyncCallChain() { - if (!m_currentStacks.size()) return nullptr; - return m_currentStacks.back().get(); -} - -void V8Debugger::compileDebuggerScript() { - if (!m_debuggerScript.IsEmpty()) { - UNREACHABLE(); - return; - } - - v8::HandleScope scope(m_isolate); - v8::Context::Scope contextScope(debuggerContext()); - - v8::Local scriptValue = - v8::String::NewFromUtf8(m_isolate, DebuggerScript_js, - v8::NewStringType::kInternalized, - sizeof(DebuggerScript_js)) - .ToLocalChecked(); - v8::Local value; - if (!m_inspector->compileAndRunInternalScript(debuggerContext(), scriptValue) - .ToLocal(&value)) { - UNREACHABLE(); - return; - } - DCHECK(value->IsObject()); - m_debuggerScript.Reset(m_isolate, value.As()); -} - -v8::Local V8Debugger::debuggerContext() const { - DCHECK(!m_debuggerContext.IsEmpty()); - return m_debuggerContext.Get(m_isolate); -} - -v8::MaybeLocal V8Debugger::functionScopes( - v8::Local context, v8::Local function) { - if (!enabled()) { - UNREACHABLE(); - return v8::Local::New(m_isolate, v8::Undefined(m_isolate)); - } - v8::Local argv[] = {function}; - v8::Local scopesValue; - if (!callDebuggerMethod("getFunctionScopes", 1, argv).ToLocal(&scopesValue)) - return v8::MaybeLocal(); - v8::Local copied; - if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, - scopesValue) - .ToLocal(&copied) || - !copied->IsArray()) - return v8::MaybeLocal(); - if (!markAsInternal(context, v8::Local::Cast(copied), - V8InternalValueType::kScopeList)) - return v8::MaybeLocal(); - if (!markArrayEntriesAsInternal(context, v8::Local::Cast(copied), - V8InternalValueType::kScope)) - return v8::MaybeLocal(); - return copied; -} - -v8::MaybeLocal V8Debugger::internalProperties( - v8::Local context, v8::Local value) { - v8::Local properties; - if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties)) - return v8::MaybeLocal(); - if (value->IsFunction()) { - v8::Local function = value.As(); - v8::Local location = functionLocation(context, function); - if (location->IsObject()) { - createDataProperty( - context, properties, properties->Length(), - toV8StringInternalized(m_isolate, "[[FunctionLocation]]")); - createDataProperty(context, properties, properties->Length(), location); - } - if (function->IsGeneratorFunction()) { - createDataProperty(context, properties, properties->Length(), - toV8StringInternalized(m_isolate, "[[IsGenerator]]")); - createDataProperty(context, properties, properties->Length(), - v8::True(m_isolate)); - } - } - if (!enabled()) return properties; - if (value->IsMap() || value->IsWeakMap() || value->IsSet() || - value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) { - v8::Local entries = - collectionEntries(context, v8::Local::Cast(value)); - if (entries->IsArray()) { - createDataProperty(context, properties, properties->Length(), - toV8StringInternalized(m_isolate, "[[Entries]]")); - createDataProperty(context, properties, properties->Length(), entries); - } - } - if (value->IsGeneratorObject()) { - v8::Local location = - generatorObjectLocation(context, v8::Local::Cast(value)); - if (location->IsObject()) { - createDataProperty( - context, properties, properties->Length(), - toV8StringInternalized(m_isolate, "[[GeneratorLocation]]")); - createDataProperty(context, properties, properties->Length(), location); - } - } - if (value->IsFunction()) { - v8::Local function = value.As(); - v8::Local boundFunction = function->GetBoundFunction(); - v8::Local scopes; - if (boundFunction->IsUndefined() && - functionScopes(context, function).ToLocal(&scopes)) { - createDataProperty(context, properties, properties->Length(), - toV8StringInternalized(m_isolate, "[[Scopes]]")); - createDataProperty(context, properties, properties->Length(), scopes); - } - } - return properties; -} - -v8::Local V8Debugger::collectionEntries( - v8::Local context, v8::Local object) { - if (!enabled()) { - UNREACHABLE(); - return v8::Undefined(m_isolate); - } - v8::Local argv[] = {object}; - v8::Local entriesValue = - callDebuggerMethod("getCollectionEntries", 1, argv).ToLocalChecked(); - if (!entriesValue->IsArray()) return v8::Undefined(m_isolate); - - v8::Local entries = entriesValue.As(); - v8::Local copiedArray = - v8::Array::New(m_isolate, entries->Length()); - if (!copiedArray->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) - return v8::Undefined(m_isolate); - for (uint32_t i = 0; i < entries->Length(); ++i) { - v8::Local item; - if (!entries->Get(debuggerContext(), i).ToLocal(&item)) - return v8::Undefined(m_isolate); - v8::Local copied; - if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, - item) - .ToLocal(&copied)) - return v8::Undefined(m_isolate); - if (!createDataProperty(context, copiedArray, i, copied).FromMaybe(false)) - return v8::Undefined(m_isolate); - } - if (!markArrayEntriesAsInternal(context, - v8::Local::Cast(copiedArray), - V8InternalValueType::kEntry)) - return v8::Undefined(m_isolate); - return copiedArray; -} - -v8::Local V8Debugger::generatorObjectLocation( - v8::Local context, v8::Local object) { - if (!enabled()) { - UNREACHABLE(); - return v8::Null(m_isolate); - } - v8::Local argv[] = {object}; - v8::Local location = - callDebuggerMethod("getGeneratorObjectLocation", 1, argv) - .ToLocalChecked(); - v8::Local copied; - if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, - location) - .ToLocal(&copied) || - !copied->IsObject()) - return v8::Null(m_isolate); - if (!markAsInternal(context, v8::Local::Cast(copied), - V8InternalValueType::kLocation)) - return v8::Null(m_isolate); - return copied; -} - -v8::Local V8Debugger::functionLocation( - v8::Local context, v8::Local function) { - int scriptId = function->ScriptId(); - if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate); - int lineNumber = function->GetScriptLineNumber(); - int columnNumber = function->GetScriptColumnNumber(); - if (lineNumber == v8::Function::kLineOffsetNotFound || - columnNumber == v8::Function::kLineOffsetNotFound) - return v8::Null(m_isolate); - v8::Local location = v8::Object::New(m_isolate); - if (!location->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) - return v8::Null(m_isolate); - if (!createDataProperty( - context, location, toV8StringInternalized(m_isolate, "scriptId"), - toV8String(m_isolate, String16::fromInteger(scriptId))) - .FromMaybe(false)) - return v8::Null(m_isolate); - if (!createDataProperty(context, location, - toV8StringInternalized(m_isolate, "lineNumber"), - v8::Integer::New(m_isolate, lineNumber)) - .FromMaybe(false)) - return v8::Null(m_isolate); - if (!createDataProperty(context, location, - toV8StringInternalized(m_isolate, "columnNumber"), - v8::Integer::New(m_isolate, columnNumber)) - .FromMaybe(false)) - return v8::Null(m_isolate); - if (!markAsInternal(context, location, V8InternalValueType::kLocation)) - return v8::Null(m_isolate); - return location; -} - -bool V8Debugger::isPaused() { return !m_pausedContext.IsEmpty(); } - -std::unique_ptr V8Debugger::createStackTrace( - v8::Local stackTrace) { - int contextGroupId = - m_isolate->InContext() ? getGroupId(m_isolate->GetCurrentContext()) : 0; - return V8StackTraceImpl::create(this, contextGroupId, stackTrace, - V8StackTraceImpl::maxCallStackSizeToCapture); -} - -int V8Debugger::markContext(const V8ContextInfo& info) { - DCHECK(info.context->GetIsolate() == m_isolate); - int contextId = ++m_lastContextId; - String16 debugData = String16::fromInteger(info.contextGroupId) + "," + - String16::fromInteger(contextId) + "," + - toString16(info.auxData); - v8::Context::Scope contextScope(info.context); - info.context->SetEmbedderData(static_cast(v8::Context::kDebugIdIndex), - toV8String(m_isolate, debugData)); - return contextId; -} - -void V8Debugger::setAsyncCallStackDepth(V8DebuggerAgentImpl* agent, int depth) { - if (depth <= 0) - m_maxAsyncCallStackDepthMap.erase(agent); - else - m_maxAsyncCallStackDepthMap[agent] = depth; - - int maxAsyncCallStackDepth = 0; - for (const auto& pair : m_maxAsyncCallStackDepthMap) { - if (pair.second > maxAsyncCallStackDepth) - maxAsyncCallStackDepth = pair.second; - } - - if (m_maxAsyncCallStackDepth == maxAsyncCallStackDepth) return; - m_maxAsyncCallStackDepth = maxAsyncCallStackDepth; - if (!maxAsyncCallStackDepth) allAsyncTasksCanceled(); -} - -void V8Debugger::asyncTaskScheduled(const StringView& taskName, void* task, - bool recurring) { - if (!m_maxAsyncCallStackDepth) return; - asyncTaskScheduled(toString16(taskName), task, recurring); -} - -void V8Debugger::asyncTaskScheduled(const String16& taskName, void* task, - bool recurring) { - if (!m_maxAsyncCallStackDepth) return; - v8::HandleScope scope(m_isolate); - int contextGroupId = - m_isolate->InContext() ? getGroupId(m_isolate->GetCurrentContext()) : 0; - std::unique_ptr chain = V8StackTraceImpl::capture( - this, contextGroupId, V8StackTraceImpl::maxCallStackSizeToCapture, - taskName); - if (chain) { - m_asyncTaskStacks[task] = std::move(chain); - if (recurring) m_recurringTasks.insert(task); - } -} - -void V8Debugger::asyncTaskCanceled(void* task) { - if (!m_maxAsyncCallStackDepth) return; - m_asyncTaskStacks.erase(task); - m_recurringTasks.erase(task); -} - -void V8Debugger::asyncTaskStarted(void* task) { - if (!m_maxAsyncCallStackDepth) return; - m_currentTasks.push_back(task); - AsyncTaskToStackTrace::iterator stackIt = m_asyncTaskStacks.find(task); - // Needs to support following order of events: - // - asyncTaskScheduled - // <-- attached here --> - // - asyncTaskStarted - // - asyncTaskCanceled <-- canceled before finished - // <-- async stack requested here --> - // - asyncTaskFinished - std::unique_ptr stack; - if (stackIt != m_asyncTaskStacks.end() && stackIt->second) - stack = stackIt->second->cloneImpl(); - m_currentStacks.push_back(std::move(stack)); -} - -void V8Debugger::asyncTaskFinished(void* task) { - if (!m_maxAsyncCallStackDepth) return; - // We could start instrumenting half way and the stack is empty. - if (!m_currentStacks.size()) return; - - DCHECK(m_currentTasks.back() == task); - m_currentTasks.pop_back(); - - m_currentStacks.pop_back(); - if (m_recurringTasks.find(task) == m_recurringTasks.end()) - m_asyncTaskStacks.erase(task); -} - -void V8Debugger::allAsyncTasksCanceled() { - m_asyncTaskStacks.clear(); - m_recurringTasks.clear(); - m_currentStacks.clear(); - m_currentTasks.clear(); -} - -void V8Debugger::muteScriptParsedEvents() { - ++m_ignoreScriptParsedEventsCounter; -} - -void V8Debugger::unmuteScriptParsedEvents() { - --m_ignoreScriptParsedEventsCounter; - DCHECK_GE(m_ignoreScriptParsedEventsCounter, 0); -} - -std::unique_ptr V8Debugger::captureStackTrace( - bool fullStack) { - if (!m_isolate->InContext()) return nullptr; - - v8::HandleScope handles(m_isolate); - int contextGroupId = getGroupId(m_isolate->GetCurrentContext()); - if (!contextGroupId) return nullptr; - - size_t stackSize = - fullStack ? V8StackTraceImpl::maxCallStackSizeToCapture : 1; - if (m_inspector->enabledRuntimeAgentForGroup(contextGroupId)) - stackSize = V8StackTraceImpl::maxCallStackSizeToCapture; - - return V8StackTraceImpl::capture(this, contextGroupId, stackSize); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-debugger.h b/deps/v8_inspector/src/inspector/v8-debugger.h deleted file mode 100644 index 83c1b21b02a712..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-debugger.h +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8DEBUGGER_H_ -#define V8_INSPECTOR_V8DEBUGGER_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/java-script-call-frame.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Runtime.h" -#include "src/inspector/v8-debugger-script.h" - -#include "include/v8-debug.h" -#include "include/v8-inspector.h" - -namespace v8_inspector { - -struct ScriptBreakpoint; -class V8DebuggerAgentImpl; -class V8InspectorImpl; -class V8StackTraceImpl; - -using protocol::ErrorString; - -class V8Debugger { - public: - V8Debugger(v8::Isolate*, V8InspectorImpl*); - ~V8Debugger(); - - static int contextId(v8::Local); - static int getGroupId(v8::Local); - int markContext(const V8ContextInfo&); - - bool enabled() const; - - String16 setBreakpoint(const String16& sourceID, const ScriptBreakpoint&, - int* actualLineNumber, int* actualColumnNumber); - void removeBreakpoint(const String16& breakpointId); - void setBreakpointsActivated(bool); - bool breakpointsActivated() const { return m_breakpointsActivated; } - - enum PauseOnExceptionsState { - DontPauseOnExceptions, - PauseOnAllExceptions, - PauseOnUncaughtExceptions - }; - PauseOnExceptionsState getPauseOnExceptionsState(); - void setPauseOnExceptionsState(PauseOnExceptionsState); - void setPauseOnNextStatement(bool); - bool canBreakProgram(); - void breakProgram(); - void continueProgram(); - void stepIntoStatement(); - void stepOverStatement(); - void stepOutOfFunction(); - void clearStepping(); - - bool setScriptSource(const String16& sourceID, - v8::Local newSource, bool dryRun, - ErrorString*, - protocol::Maybe*, - JavaScriptCallFrames* newCallFrames, - protocol::Maybe* stackChanged); - JavaScriptCallFrames currentCallFrames(int limit = 0); - - // Each script inherits debug data from v8::Context where it has been - // compiled. - // Only scripts whose debug data matches |contextGroupId| will be reported. - // Passing 0 will result in reporting all scripts. - void getCompiledScripts(int contextGroupId, - std::vector>&); - void enable(); - void disable(); - - bool isPaused(); - v8::Local pausedContext() { return m_pausedContext; } - - int maxAsyncCallChainDepth() { return m_maxAsyncCallStackDepth; } - V8StackTraceImpl* currentAsyncCallChain(); - void setAsyncCallStackDepth(V8DebuggerAgentImpl*, int); - std::unique_ptr createStackTrace(v8::Local); - std::unique_ptr captureStackTrace(bool fullStack); - - v8::MaybeLocal internalProperties(v8::Local, - v8::Local); - - void asyncTaskScheduled(const StringView& taskName, void* task, - bool recurring); - void asyncTaskScheduled(const String16& taskName, void* task, bool recurring); - void asyncTaskCanceled(void* task); - void asyncTaskStarted(void* task); - void asyncTaskFinished(void* task); - void allAsyncTasksCanceled(); - - void muteScriptParsedEvents(); - void unmuteScriptParsedEvents(); - - V8InspectorImpl* inspector() { return m_inspector; } - - private: - void compileDebuggerScript(); - v8::MaybeLocal callDebuggerMethod(const char* functionName, - int argc, - v8::Local argv[]); - v8::Local debuggerContext() const; - void clearBreakpoints(); - - static void breakProgramCallback(const v8::FunctionCallbackInfo&); - void handleProgramBreak(v8::Local pausedContext, - v8::Local executionState, - v8::Local exception, - v8::Local hitBreakpoints, - bool isPromiseRejection = false); - static void v8DebugEventCallback(const v8::Debug::EventDetails&); - v8::Local callInternalGetterFunction(v8::Local, - const char* functionName); - void handleV8DebugEvent(const v8::Debug::EventDetails&); - void handleV8AsyncTaskEvent(v8::Local, - v8::Local executionState, - v8::Local eventData); - - v8::Local collectionEntries(v8::Local, - v8::Local); - v8::Local generatorObjectLocation(v8::Local, - v8::Local); - v8::Local functionLocation(v8::Local, - v8::Local); - v8::MaybeLocal functionScopes(v8::Local, - v8::Local); - - v8::Isolate* m_isolate; - V8InspectorImpl* m_inspector; - int m_lastContextId; - int m_enableCount; - bool m_breakpointsActivated; - v8::Global m_debuggerScript; - v8::Global m_debuggerContext; - v8::Local m_executionState; - v8::Local m_pausedContext; - bool m_runningNestedMessageLoop; - int m_ignoreScriptParsedEventsCounter; - - using AsyncTaskToStackTrace = - protocol::HashMap>; - AsyncTaskToStackTrace m_asyncTaskStacks; - protocol::HashSet m_recurringTasks; - int m_maxAsyncCallStackDepth; - std::vector m_currentTasks; - std::vector> m_currentStacks; - protocol::HashMap m_maxAsyncCallStackDepthMap; - - DISALLOW_COPY_AND_ASSIGN(V8Debugger); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8DEBUGGER_H_ diff --git a/deps/v8_inspector/src/inspector/v8-function-call.cc b/deps/v8_inspector/src/inspector/v8-function-call.cc deleted file mode 100644 index 3880e3100e497e..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-function-call.cc +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "src/inspector/v8-function-call.h" - -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -V8FunctionCall::V8FunctionCall(V8InspectorImpl* inspector, - v8::Local context, - v8::Local value, const String16& name) - : m_inspector(inspector), - m_context(context), - m_name(toV8String(context->GetIsolate(), name)), - m_value(value) {} - -void V8FunctionCall::appendArgument(v8::Local value) { - m_arguments.push_back(value); -} - -void V8FunctionCall::appendArgument(const String16& argument) { - m_arguments.push_back(toV8String(m_context->GetIsolate(), argument)); -} - -void V8FunctionCall::appendArgument(int argument) { - m_arguments.push_back(v8::Number::New(m_context->GetIsolate(), argument)); -} - -void V8FunctionCall::appendArgument(bool argument) { - m_arguments.push_back(argument ? v8::True(m_context->GetIsolate()) - : v8::False(m_context->GetIsolate())); -} - -v8::Local V8FunctionCall::call(bool& hadException, - bool reportExceptions) { - v8::TryCatch tryCatch(m_context->GetIsolate()); - tryCatch.SetVerbose(reportExceptions); - - v8::Local result = callWithoutExceptionHandling(); - hadException = tryCatch.HasCaught(); - return result; -} - -v8::Local V8FunctionCall::callWithoutExceptionHandling() { - v8::Local thisObject = v8::Local::Cast(m_value); - v8::Local value; - if (!thisObject->Get(m_context, m_name).ToLocal(&value)) - return v8::Local(); - - DCHECK(value->IsFunction()); - - v8::Local function = v8::Local::Cast(value); - std::unique_ptr[]> info( - new v8::Local[m_arguments.size()]); - for (size_t i = 0; i < m_arguments.size(); ++i) { - info[i] = m_arguments[i]; - DCHECK(!info[i].IsEmpty()); - } - - int contextGroupId = V8Debugger::getGroupId(m_context); - if (contextGroupId) { - m_inspector->client()->muteMetrics(contextGroupId); - m_inspector->muteExceptions(contextGroupId); - } - v8::MicrotasksScope microtasksScope(m_context->GetIsolate(), - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::MaybeLocal maybeResult = function->Call( - m_context, thisObject, static_cast(m_arguments.size()), info.get()); - if (contextGroupId) { - m_inspector->client()->unmuteMetrics(contextGroupId); - m_inspector->unmuteExceptions(contextGroupId); - } - - v8::Local result; - if (!maybeResult.ToLocal(&result)) return v8::Local(); - return result; -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-function-call.h b/deps/v8_inspector/src/inspector/v8-function-call.h deleted file mode 100644 index 0337caa339e202..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-function-call.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2009 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_V8FUNCTIONCALL_H_ -#define V8_INSPECTOR_V8FUNCTIONCALL_H_ - -#include "src/inspector/string-16.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class V8InspectorImpl; - -class V8FunctionCall { - public: - V8FunctionCall(V8InspectorImpl*, v8::Local, v8::Local, - const String16& name); - - void appendArgument(v8::Local); - void appendArgument(const String16&); - void appendArgument(int); - void appendArgument(bool); - - v8::Local call(bool& hadException, bool reportExceptions = true); - v8::Local callWithoutExceptionHandling(); - - protected: - V8InspectorImpl* m_inspector; - v8::Local m_context; - std::vector> m_arguments; - v8::Local m_name; - v8::Local m_value; -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8FUNCTIONCALL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-heap-profiler-agent-impl.cc b/deps/v8_inspector/src/inspector/v8-heap-profiler-agent-impl.cc deleted file mode 100644 index 84c890bf3f72bf..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-heap-profiler-agent-impl.cc +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-heap-profiler-agent-impl.h" - -#include "src/inspector/injected-script.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" - -#include "include/v8-inspector.h" -#include "include/v8-profiler.h" -#include "include/v8-version.h" - -namespace v8_inspector { - -namespace { - -namespace HeapProfilerAgentState { -static const char heapProfilerEnabled[] = "heapProfilerEnabled"; -static const char heapObjectsTrackingEnabled[] = "heapObjectsTrackingEnabled"; -static const char allocationTrackingEnabled[] = "allocationTrackingEnabled"; -static const char samplingHeapProfilerEnabled[] = "samplingHeapProfilerEnabled"; -static const char samplingHeapProfilerInterval[] = - "samplingHeapProfilerInterval"; -} - -class HeapSnapshotProgress final : public v8::ActivityControl { - public: - explicit HeapSnapshotProgress(protocol::HeapProfiler::Frontend* frontend) - : m_frontend(frontend) {} - ControlOption ReportProgressValue(int done, int total) override { - m_frontend->reportHeapSnapshotProgress(done, total, - protocol::Maybe()); - if (done >= total) { - m_frontend->reportHeapSnapshotProgress(total, total, true); - } - m_frontend->flush(); - return kContinue; - } - - private: - protocol::HeapProfiler::Frontend* m_frontend; -}; - -class GlobalObjectNameResolver final - : public v8::HeapProfiler::ObjectNameResolver { - public: - explicit GlobalObjectNameResolver(V8InspectorSessionImpl* session) - : m_offset(0), m_strings(10000), m_session(session) {} - - const char* GetName(v8::Local object) override { - InspectedContext* context = m_session->inspector()->getContext( - m_session->contextGroupId(), - V8Debugger::contextId(object->CreationContext())); - if (!context) return ""; - String16 name = context->origin(); - size_t length = name.length(); - if (m_offset + length + 1 >= m_strings.size()) return ""; - for (size_t i = 0; i < length; ++i) { - UChar ch = name[i]; - m_strings[m_offset + i] = ch > 0xff ? '?' : static_cast(ch); - } - m_strings[m_offset + length] = '\0'; - char* result = &*m_strings.begin() + m_offset; - m_offset += length + 1; - return result; - } - - private: - size_t m_offset; - std::vector m_strings; - V8InspectorSessionImpl* m_session; -}; - -class HeapSnapshotOutputStream final : public v8::OutputStream { - public: - explicit HeapSnapshotOutputStream(protocol::HeapProfiler::Frontend* frontend) - : m_frontend(frontend) {} - void EndOfStream() override {} - int GetChunkSize() override { return 102400; } - WriteResult WriteAsciiChunk(char* data, int size) override { - m_frontend->addHeapSnapshotChunk(String16(data, size)); - m_frontend->flush(); - return kContinue; - } - - private: - protocol::HeapProfiler::Frontend* m_frontend; -}; - -v8::Local objectByHeapObjectId(v8::Isolate* isolate, int id) { - v8::HeapProfiler* profiler = isolate->GetHeapProfiler(); - v8::Local value = profiler->FindObjectById(id); - if (value.IsEmpty() || !value->IsObject()) return v8::Local(); - return value.As(); -} - -class InspectableHeapObject final : public V8InspectorSession::Inspectable { - public: - explicit InspectableHeapObject(int heapObjectId) - : m_heapObjectId(heapObjectId) {} - v8::Local get(v8::Local context) override { - return objectByHeapObjectId(context->GetIsolate(), m_heapObjectId); - } - - private: - int m_heapObjectId; -}; - -class HeapStatsStream final : public v8::OutputStream { - public: - explicit HeapStatsStream(protocol::HeapProfiler::Frontend* frontend) - : m_frontend(frontend) {} - - void EndOfStream() override {} - - WriteResult WriteAsciiChunk(char* data, int size) override { - DCHECK(false); - return kAbort; - } - - WriteResult WriteHeapStatsChunk(v8::HeapStatsUpdate* updateData, - int count) override { - DCHECK_GT(count, 0); - std::unique_ptr> statsDiff = - protocol::Array::create(); - for (int i = 0; i < count; ++i) { - statsDiff->addItem(updateData[i].index); - statsDiff->addItem(updateData[i].count); - statsDiff->addItem(updateData[i].size); - } - m_frontend->heapStatsUpdate(std::move(statsDiff)); - return kContinue; - } - - private: - protocol::HeapProfiler::Frontend* m_frontend; -}; - -} // namespace - -V8HeapProfilerAgentImpl::V8HeapProfilerAgentImpl( - V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, - protocol::DictionaryValue* state) - : m_session(session), - m_isolate(session->inspector()->isolate()), - m_frontend(frontendChannel), - m_state(state), - m_hasTimer(false) {} - -V8HeapProfilerAgentImpl::~V8HeapProfilerAgentImpl() {} - -void V8HeapProfilerAgentImpl::restore() { - if (m_state->booleanProperty(HeapProfilerAgentState::heapProfilerEnabled, - false)) - m_frontend.resetProfiles(); - if (m_state->booleanProperty( - HeapProfilerAgentState::heapObjectsTrackingEnabled, false)) - startTrackingHeapObjectsInternal(m_state->booleanProperty( - HeapProfilerAgentState::allocationTrackingEnabled, false)); - if (m_state->booleanProperty( - HeapProfilerAgentState::samplingHeapProfilerEnabled, false)) { - ErrorString error; - double samplingInterval = m_state->doubleProperty( - HeapProfilerAgentState::samplingHeapProfilerInterval, -1); - DCHECK_GE(samplingInterval, 0); - startSampling(&error, Maybe(samplingInterval)); - } -} - -void V8HeapProfilerAgentImpl::collectGarbage(ErrorString*) { - m_isolate->LowMemoryNotification(); -} - -void V8HeapProfilerAgentImpl::startTrackingHeapObjects( - ErrorString*, const protocol::Maybe& trackAllocations) { - m_state->setBoolean(HeapProfilerAgentState::heapObjectsTrackingEnabled, true); - bool allocationTrackingEnabled = trackAllocations.fromMaybe(false); - m_state->setBoolean(HeapProfilerAgentState::allocationTrackingEnabled, - allocationTrackingEnabled); - startTrackingHeapObjectsInternal(allocationTrackingEnabled); -} - -void V8HeapProfilerAgentImpl::stopTrackingHeapObjects( - ErrorString* error, const protocol::Maybe& reportProgress) { - requestHeapStatsUpdate(); - takeHeapSnapshot(error, reportProgress); - stopTrackingHeapObjectsInternal(); -} - -void V8HeapProfilerAgentImpl::enable(ErrorString*) { - m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, true); -} - -void V8HeapProfilerAgentImpl::disable(ErrorString* error) { - stopTrackingHeapObjectsInternal(); - if (m_state->booleanProperty( - HeapProfilerAgentState::samplingHeapProfilerEnabled, false)) { - v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler(); - if (profiler) profiler->StopSamplingHeapProfiler(); - } - m_isolate->GetHeapProfiler()->ClearObjectIds(); - m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, false); -} - -void V8HeapProfilerAgentImpl::takeHeapSnapshot( - ErrorString* errorString, const protocol::Maybe& reportProgress) { - v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler(); - if (!profiler) { - *errorString = "Cannot access v8 heap profiler"; - return; - } - std::unique_ptr progress; - if (reportProgress.fromMaybe(false)) - progress = wrapUnique(new HeapSnapshotProgress(&m_frontend)); - - GlobalObjectNameResolver resolver(m_session); - const v8::HeapSnapshot* snapshot = - profiler->TakeHeapSnapshot(progress.get(), &resolver); - if (!snapshot) { - *errorString = "Failed to take heap snapshot"; - return; - } - HeapSnapshotOutputStream stream(&m_frontend); - snapshot->Serialize(&stream); - const_cast(snapshot)->Delete(); -} - -void V8HeapProfilerAgentImpl::getObjectByHeapObjectId( - ErrorString* error, const String16& heapSnapshotObjectId, - const protocol::Maybe& objectGroup, - std::unique_ptr* result) { - bool ok; - int id = heapSnapshotObjectId.toInteger(&ok); - if (!ok) { - *error = "Invalid heap snapshot object id"; - return; - } - - v8::HandleScope handles(m_isolate); - v8::Local heapObject = objectByHeapObjectId(m_isolate, id); - if (heapObject.IsEmpty()) { - *error = "Object is not available"; - return; - } - - if (!m_session->inspector()->client()->isInspectableHeapObject(heapObject)) { - *error = "Object is not available"; - return; - } - - *result = m_session->wrapObject(heapObject->CreationContext(), heapObject, - objectGroup.fromMaybe(""), false); - if (!result) *error = "Object is not available"; -} - -void V8HeapProfilerAgentImpl::addInspectedHeapObject( - ErrorString* errorString, const String16& inspectedHeapObjectId) { - bool ok; - int id = inspectedHeapObjectId.toInteger(&ok); - if (!ok) { - *errorString = "Invalid heap snapshot object id"; - return; - } - - v8::HandleScope handles(m_isolate); - v8::Local heapObject = objectByHeapObjectId(m_isolate, id); - if (heapObject.IsEmpty()) { - *errorString = "Object is not available"; - return; - } - - if (!m_session->inspector()->client()->isInspectableHeapObject(heapObject)) { - *errorString = "Object is not available"; - return; - } - - m_session->addInspectedObject(wrapUnique(new InspectableHeapObject(id))); -} - -void V8HeapProfilerAgentImpl::getHeapObjectId(ErrorString* errorString, - const String16& objectId, - String16* heapSnapshotObjectId) { - v8::HandleScope handles(m_isolate); - v8::Local value; - v8::Local context; - if (!m_session->unwrapObject(errorString, objectId, &value, &context, - nullptr) || - value->IsUndefined()) - return; - - v8::SnapshotObjectId id = m_isolate->GetHeapProfiler()->GetObjectId(value); - *heapSnapshotObjectId = String16::fromInteger(static_cast(id)); -} - -void V8HeapProfilerAgentImpl::requestHeapStatsUpdate() { - HeapStatsStream stream(&m_frontend); - v8::SnapshotObjectId lastSeenObjectId = - m_isolate->GetHeapProfiler()->GetHeapStats(&stream); - m_frontend.lastSeenObjectId( - lastSeenObjectId, m_session->inspector()->client()->currentTimeMS()); -} - -// static -void V8HeapProfilerAgentImpl::onTimer(void* data) { - reinterpret_cast(data)->requestHeapStatsUpdate(); -} - -void V8HeapProfilerAgentImpl::startTrackingHeapObjectsInternal( - bool trackAllocations) { - m_isolate->GetHeapProfiler()->StartTrackingHeapObjects(trackAllocations); - if (!m_hasTimer) { - m_hasTimer = true; - m_session->inspector()->client()->startRepeatingTimer( - 0.05, &V8HeapProfilerAgentImpl::onTimer, reinterpret_cast(this)); - } -} - -void V8HeapProfilerAgentImpl::stopTrackingHeapObjectsInternal() { - if (m_hasTimer) { - m_session->inspector()->client()->cancelTimer( - reinterpret_cast(this)); - m_hasTimer = false; - } - m_isolate->GetHeapProfiler()->StopTrackingHeapObjects(); - m_state->setBoolean(HeapProfilerAgentState::heapObjectsTrackingEnabled, - false); - m_state->setBoolean(HeapProfilerAgentState::allocationTrackingEnabled, false); -} - -void V8HeapProfilerAgentImpl::startSampling( - ErrorString* errorString, const Maybe& samplingInterval) { - v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler(); - if (!profiler) { - *errorString = "Cannot access v8 heap profiler"; - return; - } - const unsigned defaultSamplingInterval = 1 << 15; - double samplingIntervalValue = - samplingInterval.fromMaybe(defaultSamplingInterval); - m_state->setDouble(HeapProfilerAgentState::samplingHeapProfilerInterval, - samplingIntervalValue); - m_state->setBoolean(HeapProfilerAgentState::samplingHeapProfilerEnabled, - true); - profiler->StartSamplingHeapProfiler( - static_cast(samplingIntervalValue), 128, - v8::HeapProfiler::kSamplingForceGC); -} - -namespace { -std::unique_ptr -buildSampingHeapProfileNode(const v8::AllocationProfile::Node* node) { - auto children = protocol::Array< - protocol::HeapProfiler::SamplingHeapProfileNode>::create(); - for (const auto* child : node->children) - children->addItem(buildSampingHeapProfileNode(child)); - size_t selfSize = 0; - for (const auto& allocation : node->allocations) - selfSize += allocation.size * allocation.count; - std::unique_ptr callFrame = - protocol::Runtime::CallFrame::create() - .setFunctionName(toProtocolString(node->name)) - .setScriptId(String16::fromInteger(node->script_id)) - .setUrl(toProtocolString(node->script_name)) - .setLineNumber(node->line_number - 1) - .setColumnNumber(node->column_number - 1) - .build(); - std::unique_ptr result = - protocol::HeapProfiler::SamplingHeapProfileNode::create() - .setCallFrame(std::move(callFrame)) - .setSelfSize(selfSize) - .setChildren(std::move(children)) - .build(); - return result; -} -} // namespace - -void V8HeapProfilerAgentImpl::stopSampling( - ErrorString* errorString, - std::unique_ptr* profile) { - v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler(); - if (!profiler) { - *errorString = "Cannot access v8 heap profiler"; - return; - } - v8::HandleScope scope( - m_isolate); // Allocation profile contains Local handles. - std::unique_ptr v8Profile( - profiler->GetAllocationProfile()); - profiler->StopSamplingHeapProfiler(); - m_state->setBoolean(HeapProfilerAgentState::samplingHeapProfilerEnabled, - false); - if (!v8Profile) { - *errorString = "Cannot access v8 sampled heap profile."; - return; - } - v8::AllocationProfile::Node* root = v8Profile->GetRootNode(); - *profile = protocol::HeapProfiler::SamplingHeapProfile::create() - .setHead(buildSampingHeapProfileNode(root)) - .build(); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-heap-profiler-agent-impl.h b/deps/v8_inspector/src/inspector/v8-heap-profiler-agent-impl.h deleted file mode 100644 index caa969870bacc5..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-heap-profiler-agent-impl.h +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8HEAPPROFILERAGENTIMPL_H_ -#define V8_INSPECTOR_V8HEAPPROFILERAGENTIMPL_H_ - -#include "src/base/macros.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/HeapProfiler.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class V8InspectorSessionImpl; - -using protocol::ErrorString; -using protocol::Maybe; - -class V8HeapProfilerAgentImpl : public protocol::HeapProfiler::Backend { - public: - V8HeapProfilerAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, - protocol::DictionaryValue* state); - ~V8HeapProfilerAgentImpl() override; - void restore(); - - void collectGarbage(ErrorString*) override; - - void enable(ErrorString*) override; - void startTrackingHeapObjects(ErrorString*, - const Maybe& trackAllocations) override; - void stopTrackingHeapObjects(ErrorString*, - const Maybe& reportProgress) override; - - void disable(ErrorString*) override; - - void takeHeapSnapshot(ErrorString*, - const Maybe& reportProgress) override; - - void getObjectByHeapObjectId( - ErrorString*, const String16& heapSnapshotObjectId, - const Maybe& objectGroup, - std::unique_ptr* result) override; - void addInspectedHeapObject(ErrorString*, - const String16& inspectedHeapObjectId) override; - void getHeapObjectId(ErrorString*, const String16& objectId, - String16* heapSnapshotObjectId) override; - - void startSampling(ErrorString*, - const Maybe& samplingInterval) override; - void stopSampling( - ErrorString*, - std::unique_ptr*) override; - - private: - void startTrackingHeapObjectsInternal(bool trackAllocations); - void stopTrackingHeapObjectsInternal(); - void requestHeapStatsUpdate(); - static void onTimer(void*); - - V8InspectorSessionImpl* m_session; - v8::Isolate* m_isolate; - protocol::HeapProfiler::Frontend m_frontend; - protocol::DictionaryValue* m_state; - bool m_hasTimer; - - DISALLOW_COPY_AND_ASSIGN(V8HeapProfilerAgentImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8HEAPPROFILERAGENTIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-injected-script-host.cc b/deps/v8_inspector/src/inspector/v8-injected-script-host.cc deleted file mode 100644 index dc41ef8631febe..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-injected-script-host.cc +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2015 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. - -#include "src/inspector/v8-injected-script-host.h" - -#include "src/base/macros.h" -#include "src/inspector/injected-script-native.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-internal-value-type.h" -#include "src/inspector/v8-value-copier.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -namespace { - -void setFunctionProperty(v8::Local context, - v8::Local obj, const char* name, - v8::FunctionCallback callback, - v8::Local external) { - v8::Local funcName = - toV8StringInternalized(context->GetIsolate(), name); - v8::Local func; - if (!v8::Function::New(context, callback, external, 0, - v8::ConstructorBehavior::kThrow) - .ToLocal(&func)) - return; - func->SetName(funcName); - createDataProperty(context, obj, funcName, func); -} - -V8InspectorImpl* unwrapInspector( - const v8::FunctionCallbackInfo& info) { - DCHECK(!info.Data().IsEmpty()); - DCHECK(info.Data()->IsExternal()); - V8InspectorImpl* inspector = - static_cast(info.Data().As()->Value()); - DCHECK(inspector); - return inspector; -} - -} // namespace - -v8::Local V8InjectedScriptHost::create( - v8::Local context, V8InspectorImpl* inspector) { - v8::Isolate* isolate = inspector->isolate(); - v8::Local injectedScriptHost = v8::Object::New(isolate); - bool success = injectedScriptHost->SetPrototype(context, v8::Null(isolate)) - .FromMaybe(false); - DCHECK(success); - USE(success); - v8::Local debuggerExternal = - v8::External::New(isolate, inspector); - setFunctionProperty(context, injectedScriptHost, "internalConstructorName", - V8InjectedScriptHost::internalConstructorNameCallback, - debuggerExternal); - setFunctionProperty( - context, injectedScriptHost, "formatAccessorsAsProperties", - V8InjectedScriptHost::formatAccessorsAsProperties, debuggerExternal); - setFunctionProperty(context, injectedScriptHost, "subtype", - V8InjectedScriptHost::subtypeCallback, debuggerExternal); - setFunctionProperty(context, injectedScriptHost, "getInternalProperties", - V8InjectedScriptHost::getInternalPropertiesCallback, - debuggerExternal); - setFunctionProperty(context, injectedScriptHost, "objectHasOwnProperty", - V8InjectedScriptHost::objectHasOwnPropertyCallback, - debuggerExternal); - setFunctionProperty(context, injectedScriptHost, "bind", - V8InjectedScriptHost::bindCallback, debuggerExternal); - setFunctionProperty(context, injectedScriptHost, "proxyTargetValue", - V8InjectedScriptHost::proxyTargetValueCallback, - debuggerExternal); - return injectedScriptHost; -} - -void V8InjectedScriptHost::internalConstructorNameCallback( - const v8::FunctionCallbackInfo& info) { - if (info.Length() < 1 || !info[0]->IsObject()) return; - - v8::Local object = info[0].As(); - info.GetReturnValue().Set(object->GetConstructorName()); -} - -void V8InjectedScriptHost::formatAccessorsAsProperties( - const v8::FunctionCallbackInfo& info) { - DCHECK_EQ(info.Length(), 2); - info.GetReturnValue().Set(false); - if (!info[1]->IsFunction()) return; - // Check that function is user-defined. - if (info[1].As()->ScriptId() != v8::UnboundScript::kNoScriptId) - return; - info.GetReturnValue().Set( - unwrapInspector(info)->client()->formatAccessorsAsProperties(info[0])); -} - -void V8InjectedScriptHost::subtypeCallback( - const v8::FunctionCallbackInfo& info) { - if (info.Length() < 1) return; - - v8::Isolate* isolate = info.GetIsolate(); - v8::Local value = info[0]; - if (value->IsObject()) { - v8::Local internalType = v8InternalValueTypeFrom( - isolate->GetCurrentContext(), v8::Local::Cast(value)); - if (internalType->IsString()) { - info.GetReturnValue().Set(internalType); - return; - } - } - if (value->IsArray() || value->IsArgumentsObject()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "array")); - return; - } - if (value->IsTypedArray()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "typedarray")); - return; - } - if (value->IsDate()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "date")); - return; - } - if (value->IsRegExp()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "regexp")); - return; - } - if (value->IsMap() || value->IsWeakMap()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "map")); - return; - } - if (value->IsSet() || value->IsWeakSet()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "set")); - return; - } - if (value->IsMapIterator() || value->IsSetIterator()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "iterator")); - return; - } - if (value->IsGeneratorObject()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "generator")); - return; - } - if (value->IsNativeError()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "error")); - return; - } - if (value->IsProxy()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "proxy")); - return; - } - if (value->IsPromise()) { - info.GetReturnValue().Set(toV8StringInternalized(isolate, "promise")); - return; - } - std::unique_ptr subtype = - unwrapInspector(info)->client()->valueSubtype(value); - if (subtype) { - info.GetReturnValue().Set(toV8String(isolate, subtype->string())); - return; - } -} - -void V8InjectedScriptHost::getInternalPropertiesCallback( - const v8::FunctionCallbackInfo& info) { - if (info.Length() < 1) return; - v8::Local properties; - if (unwrapInspector(info) - ->debugger() - ->internalProperties(info.GetIsolate()->GetCurrentContext(), info[0]) - .ToLocal(&properties)) - info.GetReturnValue().Set(properties); -} - -void V8InjectedScriptHost::objectHasOwnPropertyCallback( - const v8::FunctionCallbackInfo& info) { - if (info.Length() < 2 || !info[0]->IsObject() || !info[1]->IsString()) return; - bool result = info[0] - .As() - ->HasOwnProperty(info.GetIsolate()->GetCurrentContext(), - v8::Local::Cast(info[1])) - .FromMaybe(false); - info.GetReturnValue().Set(v8::Boolean::New(info.GetIsolate(), result)); -} - -void V8InjectedScriptHost::bindCallback( - const v8::FunctionCallbackInfo& info) { - if (info.Length() < 2 || !info[1]->IsString()) return; - InjectedScriptNative* injectedScriptNative = - InjectedScriptNative::fromInjectedScriptHost(info.GetIsolate(), - info.Holder()); - if (!injectedScriptNative) return; - - v8::Local context = info.GetIsolate()->GetCurrentContext(); - v8::Local v8groupName = - info[1]->ToString(context).ToLocalChecked(); - String16 groupName = toProtocolStringWithTypeCheck(v8groupName); - int id = injectedScriptNative->bind(info[0], groupName); - info.GetReturnValue().Set(id); -} - -void V8InjectedScriptHost::proxyTargetValueCallback( - const v8::FunctionCallbackInfo& info) { - if (info.Length() != 1 || !info[0]->IsProxy()) { - UNREACHABLE(); - return; - } - v8::Local target = info[0].As(); - while (target->IsProxy()) - target = v8::Local::Cast(target)->GetTarget(); - info.GetReturnValue().Set(target); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-injected-script-host.h b/deps/v8_inspector/src/inspector/v8-injected-script-host.h deleted file mode 100644 index 7d293af5a754d8..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-injected-script-host.h +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2015 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8INJECTEDSCRIPTHOST_H_ -#define V8_INSPECTOR_V8INJECTEDSCRIPTHOST_H_ - -#include "include/v8.h" - -namespace v8_inspector { - -class V8InspectorImpl; - -// SECURITY NOTE: Although the InjectedScriptHost is intended for use solely by -// the inspector, -// a reference to the InjectedScriptHost may be leaked to the page being -// inspected. Thus, the -// InjectedScriptHost must never implemment methods that have more power over -// the page than the -// page already has itself (e.g. origin restriction bypasses). - -class V8InjectedScriptHost { - public: - // We expect that debugger outlives any JS context and thus - // V8InjectedScriptHost (owned by JS) - // is destroyed before inspector. - static v8::Local create(v8::Local, V8InspectorImpl*); - - private: - static void internalConstructorNameCallback( - const v8::FunctionCallbackInfo&); - static void formatAccessorsAsProperties( - const v8::FunctionCallbackInfo&); - static void subtypeCallback(const v8::FunctionCallbackInfo&); - static void getInternalPropertiesCallback( - const v8::FunctionCallbackInfo&); - static void objectHasOwnPropertyCallback( - const v8::FunctionCallbackInfo&); - static void bindCallback(const v8::FunctionCallbackInfo&); - static void proxyTargetValueCallback( - const v8::FunctionCallbackInfo&); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8INJECTEDSCRIPTHOST_H_ diff --git a/deps/v8_inspector/src/inspector/v8-inspector-impl.cc b/deps/v8_inspector/src/inspector/v8-inspector-impl.cc deleted file mode 100644 index bd68548fbf9f82..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-inspector-impl.cc +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Copyright (c) 2010-2011 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "src/inspector/v8-inspector-impl.h" - -#include "src/inspector/inspected-context.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console-agent-impl.h" -#include "src/inspector/v8-console-message.h" -#include "src/inspector/v8-debugger-agent-impl.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-profiler-agent-impl.h" -#include "src/inspector/v8-runtime-agent-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" - -namespace v8_inspector { - -std::unique_ptr V8Inspector::create(v8::Isolate* isolate, - V8InspectorClient* client) { - return wrapUnique(new V8InspectorImpl(isolate, client)); -} - -V8InspectorImpl::V8InspectorImpl(v8::Isolate* isolate, - V8InspectorClient* client) - : m_isolate(isolate), - m_client(client), - m_debugger(new V8Debugger(isolate, this)), - m_capturingStackTracesCount(0), - m_lastExceptionId(0) {} - -V8InspectorImpl::~V8InspectorImpl() {} - -V8DebuggerAgentImpl* V8InspectorImpl::enabledDebuggerAgentForGroup( - int contextGroupId) { - V8InspectorSessionImpl* session = sessionForContextGroup(contextGroupId); - V8DebuggerAgentImpl* agent = session ? session->debuggerAgent() : nullptr; - return agent && agent->enabled() ? agent : nullptr; -} - -V8RuntimeAgentImpl* V8InspectorImpl::enabledRuntimeAgentForGroup( - int contextGroupId) { - V8InspectorSessionImpl* session = sessionForContextGroup(contextGroupId); - V8RuntimeAgentImpl* agent = session ? session->runtimeAgent() : nullptr; - return agent && agent->enabled() ? agent : nullptr; -} - -V8ProfilerAgentImpl* V8InspectorImpl::enabledProfilerAgentForGroup( - int contextGroupId) { - V8InspectorSessionImpl* session = sessionForContextGroup(contextGroupId); - V8ProfilerAgentImpl* agent = session ? session->profilerAgent() : nullptr; - return agent && agent->enabled() ? agent : nullptr; -} - -v8::MaybeLocal V8InspectorImpl::runCompiledScript( - v8::Local context, v8::Local script) { - v8::MicrotasksScope microtasksScope(m_isolate, - v8::MicrotasksScope::kRunMicrotasks); - int groupId = V8Debugger::getGroupId(context); - if (V8DebuggerAgentImpl* agent = enabledDebuggerAgentForGroup(groupId)) - agent->willExecuteScript(script->GetUnboundScript()->GetId()); - v8::MaybeLocal result = script->Run(context); - // Get agent from the map again, since it could have detached during script - // execution. - if (V8DebuggerAgentImpl* agent = enabledDebuggerAgentForGroup(groupId)) - agent->didExecuteScript(); - return result; -} - -v8::MaybeLocal V8InspectorImpl::callFunction( - v8::Local function, v8::Local context, - v8::Local receiver, int argc, v8::Local info[]) { - v8::MicrotasksScope microtasksScope(m_isolate, - v8::MicrotasksScope::kRunMicrotasks); - int groupId = V8Debugger::getGroupId(context); - if (V8DebuggerAgentImpl* agent = enabledDebuggerAgentForGroup(groupId)) - agent->willExecuteScript(function->ScriptId()); - v8::MaybeLocal result = - function->Call(context, receiver, argc, info); - // Get agent from the map again, since it could have detached during script - // execution. - if (V8DebuggerAgentImpl* agent = enabledDebuggerAgentForGroup(groupId)) - agent->didExecuteScript(); - return result; -} - -v8::MaybeLocal V8InspectorImpl::compileAndRunInternalScript( - v8::Local context, v8::Local source) { - v8::Local script = - compileScript(context, source, String16(), true); - if (script.IsEmpty()) return v8::MaybeLocal(); - v8::MicrotasksScope microtasksScope(m_isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - return script->Run(context); -} - -v8::Local V8InspectorImpl::compileScript( - v8::Local context, v8::Local code, - const String16& fileName, bool markAsInternal) { - v8::ScriptOrigin origin( - toV8String(m_isolate, fileName), v8::Integer::New(m_isolate, 0), - v8::Integer::New(m_isolate, 0), - v8::False(m_isolate), // sharable - v8::Local(), - v8::Boolean::New(m_isolate, markAsInternal), // internal - toV8String(m_isolate, String16()), // sourceMap - v8::True(m_isolate)); // opaqueresource - v8::ScriptCompiler::Source source(code, origin); - v8::Local script; - if (!v8::ScriptCompiler::Compile(context, &source, - v8::ScriptCompiler::kNoCompileOptions) - .ToLocal(&script)) - return v8::Local(); - return script; -} - -void V8InspectorImpl::enableStackCapturingIfNeeded() { - if (!m_capturingStackTracesCount) - V8StackTraceImpl::setCaptureStackTraceForUncaughtExceptions(m_isolate, - true); - ++m_capturingStackTracesCount; -} - -void V8InspectorImpl::disableStackCapturingIfNeeded() { - if (!(--m_capturingStackTracesCount)) - V8StackTraceImpl::setCaptureStackTraceForUncaughtExceptions(m_isolate, - false); -} - -void V8InspectorImpl::muteExceptions(int contextGroupId) { - m_muteExceptionsMap[contextGroupId]++; -} - -void V8InspectorImpl::unmuteExceptions(int contextGroupId) { - m_muteExceptionsMap[contextGroupId]--; -} - -V8ConsoleMessageStorage* V8InspectorImpl::ensureConsoleMessageStorage( - int contextGroupId) { - ConsoleStorageMap::iterator storageIt = - m_consoleStorageMap.find(contextGroupId); - if (storageIt == m_consoleStorageMap.end()) - storageIt = - m_consoleStorageMap - .insert(std::make_pair( - contextGroupId, - wrapUnique(new V8ConsoleMessageStorage(this, contextGroupId)))) - .first; - return storageIt->second.get(); -} - -bool V8InspectorImpl::hasConsoleMessageStorage(int contextGroupId) { - ConsoleStorageMap::iterator storageIt = - m_consoleStorageMap.find(contextGroupId); - return storageIt != m_consoleStorageMap.end(); -} - -std::unique_ptr V8InspectorImpl::createStackTrace( - v8::Local stackTrace) { - return m_debugger->createStackTrace(stackTrace); -} - -std::unique_ptr V8InspectorImpl::connect( - int contextGroupId, V8Inspector::Channel* channel, - const StringView& state) { - DCHECK(m_sessions.find(contextGroupId) == m_sessions.cend()); - std::unique_ptr session = - V8InspectorSessionImpl::create(this, contextGroupId, channel, state); - m_sessions[contextGroupId] = session.get(); - return std::move(session); -} - -void V8InspectorImpl::disconnect(V8InspectorSessionImpl* session) { - DCHECK(m_sessions.find(session->contextGroupId()) != m_sessions.end()); - m_sessions.erase(session->contextGroupId()); -} - -InspectedContext* V8InspectorImpl::getContext(int groupId, - int contextId) const { - if (!groupId || !contextId) return nullptr; - - ContextsByGroupMap::const_iterator contextGroupIt = m_contexts.find(groupId); - if (contextGroupIt == m_contexts.end()) return nullptr; - - ContextByIdMap::iterator contextIt = contextGroupIt->second->find(contextId); - if (contextIt == contextGroupIt->second->end()) return nullptr; - - return contextIt->second.get(); -} - -void V8InspectorImpl::contextCreated(const V8ContextInfo& info) { - int contextId = m_debugger->markContext(info); - - ContextsByGroupMap::iterator contextIt = m_contexts.find(info.contextGroupId); - if (contextIt == m_contexts.end()) - contextIt = m_contexts - .insert(std::make_pair(info.contextGroupId, - wrapUnique(new ContextByIdMap()))) - .first; - - const auto& contextById = contextIt->second; - - DCHECK(contextById->find(contextId) == contextById->cend()); - InspectedContext* context = new InspectedContext(this, info, contextId); - (*contextById)[contextId] = wrapUnique(context); - SessionMap::iterator sessionIt = m_sessions.find(info.contextGroupId); - if (sessionIt != m_sessions.end()) - sessionIt->second->runtimeAgent()->reportExecutionContextCreated(context); -} - -void V8InspectorImpl::contextDestroyed(v8::Local context) { - int contextId = V8Debugger::contextId(context); - int contextGroupId = V8Debugger::getGroupId(context); - - ConsoleStorageMap::iterator storageIt = - m_consoleStorageMap.find(contextGroupId); - if (storageIt != m_consoleStorageMap.end()) - storageIt->second->contextDestroyed(contextId); - - InspectedContext* inspectedContext = getContext(contextGroupId, contextId); - if (!inspectedContext) return; - - SessionMap::iterator iter = m_sessions.find(contextGroupId); - if (iter != m_sessions.end()) - iter->second->runtimeAgent()->reportExecutionContextDestroyed( - inspectedContext); - discardInspectedContext(contextGroupId, contextId); -} - -void V8InspectorImpl::resetContextGroup(int contextGroupId) { - m_consoleStorageMap.erase(contextGroupId); - m_muteExceptionsMap.erase(contextGroupId); - SessionMap::iterator session = m_sessions.find(contextGroupId); - if (session != m_sessions.end()) session->second->reset(); - m_contexts.erase(contextGroupId); -} - -void V8InspectorImpl::willExecuteScript(v8::Local context, - int scriptId) { - if (V8DebuggerAgentImpl* agent = - enabledDebuggerAgentForGroup(V8Debugger::getGroupId(context))) - agent->willExecuteScript(scriptId); -} - -void V8InspectorImpl::didExecuteScript(v8::Local context) { - if (V8DebuggerAgentImpl* agent = - enabledDebuggerAgentForGroup(V8Debugger::getGroupId(context))) - agent->didExecuteScript(); -} - -void V8InspectorImpl::idleStarted() { - for (auto it = m_sessions.begin(); it != m_sessions.end(); ++it) { - if (it->second->profilerAgent()->idleStarted()) return; - } -} - -void V8InspectorImpl::idleFinished() { - for (auto it = m_sessions.begin(); it != m_sessions.end(); ++it) { - if (it->second->profilerAgent()->idleFinished()) return; - } -} - -unsigned V8InspectorImpl::exceptionThrown( - v8::Local context, const StringView& message, - v8::Local exception, const StringView& detailedMessage, - const StringView& url, unsigned lineNumber, unsigned columnNumber, - std::unique_ptr stackTrace, int scriptId) { - int contextGroupId = V8Debugger::getGroupId(context); - if (!contextGroupId || m_muteExceptionsMap[contextGroupId]) return 0; - std::unique_ptr stackTraceImpl = - wrapUnique(static_cast(stackTrace.release())); - unsigned exceptionId = nextExceptionId(); - std::unique_ptr consoleMessage = - V8ConsoleMessage::createForException( - m_client->currentTimeMS(), toString16(detailedMessage), - toString16(url), lineNumber, columnNumber, std::move(stackTraceImpl), - scriptId, m_isolate, toString16(message), - V8Debugger::contextId(context), exception, exceptionId); - ensureConsoleMessageStorage(contextGroupId) - ->addMessage(std::move(consoleMessage)); - return exceptionId; -} - -void V8InspectorImpl::exceptionRevoked(v8::Local context, - unsigned exceptionId, - const StringView& message) { - int contextGroupId = V8Debugger::getGroupId(context); - if (!contextGroupId) return; - - std::unique_ptr consoleMessage = - V8ConsoleMessage::createForRevokedException( - m_client->currentTimeMS(), toString16(message), exceptionId); - ensureConsoleMessageStorage(contextGroupId) - ->addMessage(std::move(consoleMessage)); -} - -std::unique_ptr V8InspectorImpl::captureStackTrace( - bool fullStack) { - return m_debugger->captureStackTrace(fullStack); -} - -void V8InspectorImpl::asyncTaskScheduled(const StringView& taskName, void* task, - bool recurring) { - m_debugger->asyncTaskScheduled(taskName, task, recurring); -} - -void V8InspectorImpl::asyncTaskCanceled(void* task) { - m_debugger->asyncTaskCanceled(task); -} - -void V8InspectorImpl::asyncTaskStarted(void* task) { - m_debugger->asyncTaskStarted(task); -} - -void V8InspectorImpl::asyncTaskFinished(void* task) { - m_debugger->asyncTaskFinished(task); -} - -void V8InspectorImpl::allAsyncTasksCanceled() { - m_debugger->allAsyncTasksCanceled(); -} - -v8::Local V8InspectorImpl::regexContext() { - if (m_regexContext.IsEmpty()) - m_regexContext.Reset(m_isolate, v8::Context::New(m_isolate)); - return m_regexContext.Get(m_isolate); -} - -void V8InspectorImpl::discardInspectedContext(int contextGroupId, - int contextId) { - if (!getContext(contextGroupId, contextId)) return; - m_contexts[contextGroupId]->erase(contextId); - if (m_contexts[contextGroupId]->empty()) m_contexts.erase(contextGroupId); -} - -const V8InspectorImpl::ContextByIdMap* V8InspectorImpl::contextGroup( - int contextGroupId) { - ContextsByGroupMap::iterator iter = m_contexts.find(contextGroupId); - return iter == m_contexts.end() ? nullptr : iter->second.get(); -} - -V8InspectorSessionImpl* V8InspectorImpl::sessionForContextGroup( - int contextGroupId) { - if (!contextGroupId) return nullptr; - SessionMap::iterator iter = m_sessions.find(contextGroupId); - return iter == m_sessions.end() ? nullptr : iter->second; -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-inspector-impl.h b/deps/v8_inspector/src/inspector/v8-inspector-impl.h deleted file mode 100644 index 0ca1a6a7297b02..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-inspector-impl.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2010, Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_V8INSPECTORIMPL_H_ -#define V8_INSPECTOR_V8INSPECTORIMPL_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/protocol/Protocol.h" - -#include "include/v8-debug.h" -#include "include/v8-inspector.h" - -namespace v8_inspector { - -class InspectedContext; -class V8ConsoleMessageStorage; -class V8Debugger; -class V8DebuggerAgentImpl; -class V8InspectorSessionImpl; -class V8ProfilerAgentImpl; -class V8RuntimeAgentImpl; -class V8StackTraceImpl; - -class V8InspectorImpl : public V8Inspector { - public: - V8InspectorImpl(v8::Isolate*, V8InspectorClient*); - ~V8InspectorImpl() override; - - v8::Isolate* isolate() const { return m_isolate; } - V8InspectorClient* client() { return m_client; } - V8Debugger* debugger() { return m_debugger.get(); } - - v8::MaybeLocal runCompiledScript(v8::Local, - v8::Local); - v8::MaybeLocal callFunction(v8::Local, - v8::Local, - v8::Local receiver, - int argc, v8::Local info[]); - v8::MaybeLocal compileAndRunInternalScript(v8::Local, - v8::Local); - v8::Local compileScript(v8::Local, - v8::Local, - const String16& fileName, - bool markAsInternal); - v8::Local regexContext(); - - // V8Inspector implementation. - std::unique_ptr connect(int contextGroupId, - V8Inspector::Channel*, - const StringView& state) override; - void contextCreated(const V8ContextInfo&) override; - void contextDestroyed(v8::Local) override; - void resetContextGroup(int contextGroupId) override; - void willExecuteScript(v8::Local, int scriptId) override; - void didExecuteScript(v8::Local) override; - void idleStarted() override; - void idleFinished() override; - unsigned exceptionThrown(v8::Local, const StringView& message, - v8::Local exception, - const StringView& detailedMessage, - const StringView& url, unsigned lineNumber, - unsigned columnNumber, std::unique_ptr, - int scriptId) override; - void exceptionRevoked(v8::Local, unsigned exceptionId, - const StringView& message) override; - std::unique_ptr createStackTrace( - v8::Local) override; - std::unique_ptr captureStackTrace(bool fullStack) override; - void asyncTaskScheduled(const StringView& taskName, void* task, - bool recurring) override; - void asyncTaskCanceled(void* task) override; - void asyncTaskStarted(void* task) override; - void asyncTaskFinished(void* task) override; - void allAsyncTasksCanceled() override; - - unsigned nextExceptionId() { return ++m_lastExceptionId; } - void enableStackCapturingIfNeeded(); - void disableStackCapturingIfNeeded(); - void muteExceptions(int contextGroupId); - void unmuteExceptions(int contextGroupId); - V8ConsoleMessageStorage* ensureConsoleMessageStorage(int contextGroupId); - bool hasConsoleMessageStorage(int contextGroupId); - using ContextByIdMap = - protocol::HashMap>; - void discardInspectedContext(int contextGroupId, int contextId); - const ContextByIdMap* contextGroup(int contextGroupId); - void disconnect(V8InspectorSessionImpl*); - V8InspectorSessionImpl* sessionForContextGroup(int contextGroupId); - InspectedContext* getContext(int groupId, int contextId) const; - V8DebuggerAgentImpl* enabledDebuggerAgentForGroup(int contextGroupId); - V8RuntimeAgentImpl* enabledRuntimeAgentForGroup(int contextGroupId); - V8ProfilerAgentImpl* enabledProfilerAgentForGroup(int contextGroupId); - - private: - v8::Isolate* m_isolate; - V8InspectorClient* m_client; - std::unique_ptr m_debugger; - v8::Global m_regexContext; - int m_capturingStackTracesCount; - unsigned m_lastExceptionId; - - using MuteExceptionsMap = protocol::HashMap; - MuteExceptionsMap m_muteExceptionsMap; - - using ContextsByGroupMap = - protocol::HashMap>; - ContextsByGroupMap m_contexts; - - using SessionMap = protocol::HashMap; - SessionMap m_sessions; - - using ConsoleStorageMap = - protocol::HashMap>; - ConsoleStorageMap m_consoleStorageMap; - - DISALLOW_COPY_AND_ASSIGN(V8InspectorImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8INSPECTORIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-inspector-session-impl.cc b/deps/v8_inspector/src/inspector/v8-inspector-session-impl.cc deleted file mode 100644 index 9a0f652c4ca4ae..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-inspector-session-impl.cc +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-inspector-session-impl.h" - -#include "src/inspector/injected-script.h" -#include "src/inspector/inspected-context.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/remote-object-id.h" -#include "src/inspector/search-util.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console-agent-impl.h" -#include "src/inspector/v8-debugger-agent-impl.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-heap-profiler-agent-impl.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-profiler-agent-impl.h" -#include "src/inspector/v8-runtime-agent-impl.h" -#include "src/inspector/v8-schema-agent-impl.h" - -namespace v8_inspector { - -// static -bool V8InspectorSession::canDispatchMethod(const StringView& method) { - return stringViewStartsWith(method, - protocol::Runtime::Metainfo::commandPrefix) || - stringViewStartsWith(method, - protocol::Debugger::Metainfo::commandPrefix) || - stringViewStartsWith(method, - protocol::Profiler::Metainfo::commandPrefix) || - stringViewStartsWith( - method, protocol::HeapProfiler::Metainfo::commandPrefix) || - stringViewStartsWith(method, - protocol::Console::Metainfo::commandPrefix) || - stringViewStartsWith(method, - protocol::Schema::Metainfo::commandPrefix); -} - -std::unique_ptr V8InspectorSessionImpl::create( - V8InspectorImpl* inspector, int contextGroupId, - V8Inspector::Channel* channel, const StringView& state) { - return wrapUnique( - new V8InspectorSessionImpl(inspector, contextGroupId, channel, state)); -} - -V8InspectorSessionImpl::V8InspectorSessionImpl(V8InspectorImpl* inspector, - int contextGroupId, - V8Inspector::Channel* channel, - const StringView& savedState) - : m_contextGroupId(contextGroupId), - m_inspector(inspector), - m_channel(channel), - m_customObjectFormatterEnabled(false), - m_dispatcher(this), - m_state(nullptr), - m_runtimeAgent(nullptr), - m_debuggerAgent(nullptr), - m_heapProfilerAgent(nullptr), - m_profilerAgent(nullptr), - m_consoleAgent(nullptr), - m_schemaAgent(nullptr) { - if (savedState.length()) { - std::unique_ptr state = - protocol::parseJSON(toString16(savedState)); - if (state) m_state = protocol::DictionaryValue::cast(std::move(state)); - if (!m_state) m_state = protocol::DictionaryValue::create(); - } else { - m_state = protocol::DictionaryValue::create(); - } - - m_runtimeAgent = wrapUnique(new V8RuntimeAgentImpl( - this, this, agentState(protocol::Runtime::Metainfo::domainName))); - protocol::Runtime::Dispatcher::wire(&m_dispatcher, m_runtimeAgent.get()); - - m_debuggerAgent = wrapUnique(new V8DebuggerAgentImpl( - this, this, agentState(protocol::Debugger::Metainfo::domainName))); - protocol::Debugger::Dispatcher::wire(&m_dispatcher, m_debuggerAgent.get()); - - m_profilerAgent = wrapUnique(new V8ProfilerAgentImpl( - this, this, agentState(protocol::Profiler::Metainfo::domainName))); - protocol::Profiler::Dispatcher::wire(&m_dispatcher, m_profilerAgent.get()); - - m_heapProfilerAgent = wrapUnique(new V8HeapProfilerAgentImpl( - this, this, agentState(protocol::HeapProfiler::Metainfo::domainName))); - protocol::HeapProfiler::Dispatcher::wire(&m_dispatcher, - m_heapProfilerAgent.get()); - - m_consoleAgent = wrapUnique(new V8ConsoleAgentImpl( - this, this, agentState(protocol::Console::Metainfo::domainName))); - protocol::Console::Dispatcher::wire(&m_dispatcher, m_consoleAgent.get()); - - m_schemaAgent = wrapUnique(new V8SchemaAgentImpl( - this, this, agentState(protocol::Schema::Metainfo::domainName))); - protocol::Schema::Dispatcher::wire(&m_dispatcher, m_schemaAgent.get()); - - if (savedState.length()) { - m_runtimeAgent->restore(); - m_debuggerAgent->restore(); - m_heapProfilerAgent->restore(); - m_profilerAgent->restore(); - m_consoleAgent->restore(); - } -} - -V8InspectorSessionImpl::~V8InspectorSessionImpl() { - ErrorString errorString; - m_consoleAgent->disable(&errorString); - m_profilerAgent->disable(&errorString); - m_heapProfilerAgent->disable(&errorString); - m_debuggerAgent->disable(&errorString); - m_runtimeAgent->disable(&errorString); - - discardInjectedScripts(); - m_inspector->disconnect(this); -} - -protocol::DictionaryValue* V8InspectorSessionImpl::agentState( - const String16& name) { - protocol::DictionaryValue* state = m_state->getObject(name); - if (!state) { - std::unique_ptr newState = - protocol::DictionaryValue::create(); - state = newState.get(); - m_state->setObject(name, std::move(newState)); - } - return state; -} - -void V8InspectorSessionImpl::sendProtocolResponse(int callId, - const String16& message) { - m_channel->sendProtocolResponse(callId, toStringView(message)); -} - -void V8InspectorSessionImpl::sendProtocolNotification(const String16& message) { - m_channel->sendProtocolNotification(toStringView(message)); -} - -void V8InspectorSessionImpl::flushProtocolNotifications() { - m_channel->flushProtocolNotifications(); -} - -void V8InspectorSessionImpl::reset() { - m_debuggerAgent->reset(); - m_runtimeAgent->reset(); - discardInjectedScripts(); -} - -void V8InspectorSessionImpl::discardInjectedScripts() { - m_inspectedObjects.clear(); - const V8InspectorImpl::ContextByIdMap* contexts = - m_inspector->contextGroup(m_contextGroupId); - if (!contexts) return; - - std::vector keys; - keys.reserve(contexts->size()); - for (auto& idContext : *contexts) keys.push_back(idContext.first); - for (auto& key : keys) { - contexts = m_inspector->contextGroup(m_contextGroupId); - if (!contexts) continue; - auto contextIt = contexts->find(key); - if (contextIt != contexts->end()) - contextIt->second - ->discardInjectedScript(); // This may destroy some contexts. - } -} - -InjectedScript* V8InspectorSessionImpl::findInjectedScript( - ErrorString* errorString, int contextId) { - if (!contextId) { - *errorString = "Cannot find context with specified id"; - return nullptr; - } - - const V8InspectorImpl::ContextByIdMap* contexts = - m_inspector->contextGroup(m_contextGroupId); - if (!contexts) { - *errorString = "Cannot find context with specified id"; - return nullptr; - } - - auto contextsIt = contexts->find(contextId); - if (contextsIt == contexts->end()) { - *errorString = "Cannot find context with specified id"; - return nullptr; - } - - const std::unique_ptr& context = contextsIt->second; - if (!context->getInjectedScript()) { - context->createInjectedScript(); - if (!context->getInjectedScript()) { - *errorString = "Cannot access specified execution context"; - return nullptr; - } - if (m_customObjectFormatterEnabled) - context->getInjectedScript()->setCustomObjectFormatterEnabled(true); - } - return context->getInjectedScript(); -} - -InjectedScript* V8InspectorSessionImpl::findInjectedScript( - ErrorString* errorString, RemoteObjectIdBase* objectId) { - return objectId ? findInjectedScript(errorString, objectId->contextId()) - : nullptr; -} - -void V8InspectorSessionImpl::releaseObjectGroup(const StringView& objectGroup) { - releaseObjectGroup(toString16(objectGroup)); -} - -void V8InspectorSessionImpl::releaseObjectGroup(const String16& objectGroup) { - const V8InspectorImpl::ContextByIdMap* contexts = - m_inspector->contextGroup(m_contextGroupId); - if (!contexts) return; - - std::vector keys; - for (auto& idContext : *contexts) keys.push_back(idContext.first); - for (auto& key : keys) { - contexts = m_inspector->contextGroup(m_contextGroupId); - if (!contexts) continue; - auto contextsIt = contexts->find(key); - if (contextsIt == contexts->end()) continue; - InjectedScript* injectedScript = contextsIt->second->getInjectedScript(); - if (injectedScript) - injectedScript->releaseObjectGroup( - objectGroup); // This may destroy some contexts. - } -} - -bool V8InspectorSessionImpl::unwrapObject( - std::unique_ptr* error, const StringView& objectId, - v8::Local* object, v8::Local* context, - std::unique_ptr* objectGroup) { - ErrorString errorString; - String16 objectGroupString; - bool result = - unwrapObject(&errorString, toString16(objectId), object, context, - objectGroup ? &objectGroupString : nullptr); - if (error) *error = StringBufferImpl::adopt(errorString); - if (objectGroup) *objectGroup = StringBufferImpl::adopt(objectGroupString); - return result; -} - -bool V8InspectorSessionImpl::unwrapObject(ErrorString* errorString, - const String16& objectId, - v8::Local* object, - v8::Local* context, - String16* objectGroup) { - std::unique_ptr remoteId = - RemoteObjectId::parse(errorString, objectId); - if (!remoteId) return false; - InjectedScript* injectedScript = - findInjectedScript(errorString, remoteId.get()); - if (!injectedScript) return false; - if (!injectedScript->findObject(errorString, *remoteId, object)) return false; - *context = injectedScript->context()->context(); - if (objectGroup) *objectGroup = injectedScript->objectGroupName(*remoteId); - return true; -} - -std::unique_ptr -V8InspectorSessionImpl::wrapObject(v8::Local context, - v8::Local value, - const StringView& groupName) { - return wrapObject(context, value, toString16(groupName), false); -} - -std::unique_ptr -V8InspectorSessionImpl::wrapObject(v8::Local context, - v8::Local value, - const String16& groupName, - bool generatePreview) { - ErrorString errorString; - InjectedScript* injectedScript = - findInjectedScript(&errorString, V8Debugger::contextId(context)); - if (!injectedScript) return nullptr; - return injectedScript->wrapObject(&errorString, value, groupName, false, - generatePreview); -} - -std::unique_ptr -V8InspectorSessionImpl::wrapTable(v8::Local context, - v8::Local table, - v8::Local columns) { - ErrorString errorString; - InjectedScript* injectedScript = - findInjectedScript(&errorString, V8Debugger::contextId(context)); - if (!injectedScript) return nullptr; - return injectedScript->wrapTable(table, columns); -} - -void V8InspectorSessionImpl::setCustomObjectFormatterEnabled(bool enabled) { - m_customObjectFormatterEnabled = enabled; - const V8InspectorImpl::ContextByIdMap* contexts = - m_inspector->contextGroup(m_contextGroupId); - if (!contexts) return; - for (auto& idContext : *contexts) { - InjectedScript* injectedScript = idContext.second->getInjectedScript(); - if (injectedScript) - injectedScript->setCustomObjectFormatterEnabled(enabled); - } -} - -void V8InspectorSessionImpl::reportAllContexts(V8RuntimeAgentImpl* agent) { - const V8InspectorImpl::ContextByIdMap* contexts = - m_inspector->contextGroup(m_contextGroupId); - if (!contexts) return; - for (auto& idContext : *contexts) - agent->reportExecutionContextCreated(idContext.second.get()); -} - -void V8InspectorSessionImpl::dispatchProtocolMessage( - const StringView& message) { - m_dispatcher.dispatch(protocol::parseJSON(message)); -} - -std::unique_ptr V8InspectorSessionImpl::stateJSON() { - String16 json = m_state->toJSONString(); - return StringBufferImpl::adopt(json); -} - -std::vector> -V8InspectorSessionImpl::supportedDomains() { - std::vector> domains = - supportedDomainsImpl(); - std::vector> result; - for (size_t i = 0; i < domains.size(); ++i) - result.push_back(std::move(domains[i])); - return result; -} - -std::vector> -V8InspectorSessionImpl::supportedDomainsImpl() { - std::vector> result; - result.push_back(protocol::Schema::Domain::create() - .setName(protocol::Runtime::Metainfo::domainName) - .setVersion(protocol::Runtime::Metainfo::version) - .build()); - result.push_back(protocol::Schema::Domain::create() - .setName(protocol::Debugger::Metainfo::domainName) - .setVersion(protocol::Debugger::Metainfo::version) - .build()); - result.push_back(protocol::Schema::Domain::create() - .setName(protocol::Profiler::Metainfo::domainName) - .setVersion(protocol::Profiler::Metainfo::version) - .build()); - result.push_back(protocol::Schema::Domain::create() - .setName(protocol::HeapProfiler::Metainfo::domainName) - .setVersion(protocol::HeapProfiler::Metainfo::version) - .build()); - result.push_back(protocol::Schema::Domain::create() - .setName(protocol::Schema::Metainfo::domainName) - .setVersion(protocol::Schema::Metainfo::version) - .build()); - return result; -} - -void V8InspectorSessionImpl::addInspectedObject( - std::unique_ptr inspectable) { - m_inspectedObjects.insert(m_inspectedObjects.begin(), std::move(inspectable)); - if (m_inspectedObjects.size() > kInspectedObjectBufferSize) - m_inspectedObjects.resize(kInspectedObjectBufferSize); -} - -V8InspectorSession::Inspectable* V8InspectorSessionImpl::inspectedObject( - unsigned num) { - if (num >= m_inspectedObjects.size()) return nullptr; - return m_inspectedObjects[num].get(); -} - -void V8InspectorSessionImpl::schedulePauseOnNextStatement( - const StringView& breakReason, const StringView& breakDetails) { - m_debuggerAgent->schedulePauseOnNextStatement( - toString16(breakReason), - protocol::DictionaryValue::cast(protocol::parseJSON(breakDetails))); -} - -void V8InspectorSessionImpl::cancelPauseOnNextStatement() { - m_debuggerAgent->cancelPauseOnNextStatement(); -} - -void V8InspectorSessionImpl::breakProgram(const StringView& breakReason, - const StringView& breakDetails) { - m_debuggerAgent->breakProgram( - toString16(breakReason), - protocol::DictionaryValue::cast(protocol::parseJSON(breakDetails))); -} - -void V8InspectorSessionImpl::setSkipAllPauses(bool skip) { - ErrorString errorString; - m_debuggerAgent->setSkipAllPauses(&errorString, skip); -} - -void V8InspectorSessionImpl::resume() { - ErrorString errorString; - m_debuggerAgent->resume(&errorString); -} - -void V8InspectorSessionImpl::stepOver() { - ErrorString errorString; - m_debuggerAgent->stepOver(&errorString); -} - -std::vector> -V8InspectorSessionImpl::searchInTextByLines(const StringView& text, - const StringView& query, - bool caseSensitive, bool isRegex) { - // TODO(dgozman): search may operate on StringView and avoid copying |text|. - std::vector> matches = - searchInTextByLinesImpl(this, toString16(text), toString16(query), - caseSensitive, isRegex); - std::vector> result; - for (size_t i = 0; i < matches.size(); ++i) - result.push_back(std::move(matches[i])); - return result; -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-inspector-session-impl.h b/deps/v8_inspector/src/inspector/v8-inspector-session-impl.h deleted file mode 100644 index e84e8c99a77c3f..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-inspector-session-impl.h +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8INSPECTORSESSIONIMPL_H_ -#define V8_INSPECTOR_V8INSPECTORSESSIONIMPL_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Runtime.h" -#include "src/inspector/protocol/Schema.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -class InjectedScript; -class RemoteObjectIdBase; -class V8ConsoleAgentImpl; -class V8DebuggerAgentImpl; -class V8InspectorImpl; -class V8HeapProfilerAgentImpl; -class V8ProfilerAgentImpl; -class V8RuntimeAgentImpl; -class V8SchemaAgentImpl; - -using protocol::ErrorString; - -class V8InspectorSessionImpl : public V8InspectorSession, - public protocol::FrontendChannel { - public: - static std::unique_ptr create( - V8InspectorImpl*, int contextGroupId, V8Inspector::Channel*, - const StringView& state); - ~V8InspectorSessionImpl(); - - V8InspectorImpl* inspector() const { return m_inspector; } - V8ConsoleAgentImpl* consoleAgent() { return m_consoleAgent.get(); } - V8DebuggerAgentImpl* debuggerAgent() { return m_debuggerAgent.get(); } - V8SchemaAgentImpl* schemaAgent() { return m_schemaAgent.get(); } - V8ProfilerAgentImpl* profilerAgent() { return m_profilerAgent.get(); } - V8RuntimeAgentImpl* runtimeAgent() { return m_runtimeAgent.get(); } - int contextGroupId() const { return m_contextGroupId; } - - InjectedScript* findInjectedScript(ErrorString*, int contextId); - InjectedScript* findInjectedScript(ErrorString*, RemoteObjectIdBase*); - void reset(); - void discardInjectedScripts(); - void reportAllContexts(V8RuntimeAgentImpl*); - void setCustomObjectFormatterEnabled(bool); - std::unique_ptr wrapObject( - v8::Local, v8::Local, const String16& groupName, - bool generatePreview); - std::unique_ptr wrapTable( - v8::Local, v8::Local table, - v8::Local columns); - std::vector> supportedDomainsImpl(); - bool unwrapObject(ErrorString*, const String16& objectId, - v8::Local*, v8::Local*, - String16* objectGroup); - void releaseObjectGroup(const String16& objectGroup); - - // V8InspectorSession implementation. - void dispatchProtocolMessage(const StringView& message) override; - std::unique_ptr stateJSON() override; - std::vector> supportedDomains() - override; - void addInspectedObject( - std::unique_ptr) override; - void schedulePauseOnNextStatement(const StringView& breakReason, - const StringView& breakDetails) override; - void cancelPauseOnNextStatement() override; - void breakProgram(const StringView& breakReason, - const StringView& breakDetails) override; - void setSkipAllPauses(bool) override; - void resume() override; - void stepOver() override; - std::vector> - searchInTextByLines(const StringView& text, const StringView& query, - bool caseSensitive, bool isRegex) override; - void releaseObjectGroup(const StringView& objectGroup) override; - bool unwrapObject(std::unique_ptr*, const StringView& objectId, - v8::Local*, v8::Local*, - std::unique_ptr* objectGroup) override; - std::unique_ptr wrapObject( - v8::Local, v8::Local, - const StringView& groupName) override; - - V8InspectorSession::Inspectable* inspectedObject(unsigned num); - static const unsigned kInspectedObjectBufferSize = 5; - - private: - V8InspectorSessionImpl(V8InspectorImpl*, int contextGroupId, - V8Inspector::Channel*, const StringView& state); - protocol::DictionaryValue* agentState(const String16& name); - - // protocol::FrontendChannel implementation. - void sendProtocolResponse(int callId, const String16& message) override; - void sendProtocolNotification(const String16& message) override; - void flushProtocolNotifications() override; - - int m_contextGroupId; - V8InspectorImpl* m_inspector; - V8Inspector::Channel* m_channel; - bool m_customObjectFormatterEnabled; - - protocol::UberDispatcher m_dispatcher; - std::unique_ptr m_state; - - std::unique_ptr m_runtimeAgent; - std::unique_ptr m_debuggerAgent; - std::unique_ptr m_heapProfilerAgent; - std::unique_ptr m_profilerAgent; - std::unique_ptr m_consoleAgent; - std::unique_ptr m_schemaAgent; - std::vector> - m_inspectedObjects; - - DISALLOW_COPY_AND_ASSIGN(V8InspectorSessionImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8INSPECTORSESSIONIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-internal-value-type.cc b/deps/v8_inspector/src/inspector/v8-internal-value-type.cc deleted file mode 100644 index cde8bc9f7f9957..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-internal-value-type.cc +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-internal-value-type.h" - -#include "src/inspector/protocol-platform.h" -#include "src/inspector/string-util.h" - -namespace v8_inspector { - -namespace { - -v8::Local internalSubtypePrivate(v8::Isolate* isolate) { - return v8::Private::ForApi( - isolate, - toV8StringInternalized(isolate, "V8InternalType#internalSubtype")); -} - -v8::Local subtypeForInternalType(v8::Isolate* isolate, - V8InternalValueType type) { - switch (type) { - case V8InternalValueType::kEntry: - return toV8StringInternalized(isolate, "internal#entry"); - case V8InternalValueType::kLocation: - return toV8StringInternalized(isolate, "internal#location"); - case V8InternalValueType::kScope: - return toV8StringInternalized(isolate, "internal#scope"); - case V8InternalValueType::kScopeList: - return toV8StringInternalized(isolate, "internal#scopeList"); - } - UNREACHABLE(); - return v8::Local(); -} - -} // namespace - -bool markAsInternal(v8::Local context, - v8::Local object, V8InternalValueType type) { - v8::Isolate* isolate = context->GetIsolate(); - v8::Local privateValue = internalSubtypePrivate(isolate); - v8::Local subtype = subtypeForInternalType(isolate, type); - return object->SetPrivate(context, privateValue, subtype).FromMaybe(false); -} - -bool markArrayEntriesAsInternal(v8::Local context, - v8::Local array, - V8InternalValueType type) { - v8::Isolate* isolate = context->GetIsolate(); - v8::Local privateValue = internalSubtypePrivate(isolate); - v8::Local subtype = subtypeForInternalType(isolate, type); - for (uint32_t i = 0; i < array->Length(); ++i) { - v8::Local entry; - if (!array->Get(context, i).ToLocal(&entry) || !entry->IsObject()) - return false; - if (!entry.As() - ->SetPrivate(context, privateValue, subtype) - .FromMaybe(false)) - return false; - } - return true; -} - -v8::Local v8InternalValueTypeFrom(v8::Local context, - v8::Local object) { - v8::Isolate* isolate = context->GetIsolate(); - v8::Local privateValue = internalSubtypePrivate(isolate); - if (!object->HasPrivate(context, privateValue).FromMaybe(false)) - return v8::Null(isolate); - v8::Local subtypeValue; - if (!object->GetPrivate(context, privateValue).ToLocal(&subtypeValue) || - !subtypeValue->IsString()) - return v8::Null(isolate); - return subtypeValue; -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-internal-value-type.h b/deps/v8_inspector/src/inspector/v8-internal-value-type.h deleted file mode 100644 index e648a0d4a3ec7d..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-internal-value-type.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8INTERNALVALUETYPE_H_ -#define V8_INSPECTOR_V8INTERNALVALUETYPE_H_ - -#include "include/v8.h" - -namespace v8_inspector { - -enum class V8InternalValueType { kEntry, kLocation, kScope, kScopeList }; - -bool markAsInternal(v8::Local, v8::Local, - V8InternalValueType); -bool markArrayEntriesAsInternal(v8::Local, v8::Local, - V8InternalValueType); -v8::Local v8InternalValueTypeFrom(v8::Local, - v8::Local); - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8INTERNALVALUETYPE_H_ diff --git a/deps/v8_inspector/src/inspector/v8-profiler-agent-impl.cc b/deps/v8_inspector/src/inspector/v8-profiler-agent-impl.cc deleted file mode 100644 index 0511ca39b55ca1..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-profiler-agent-impl.cc +++ /dev/null @@ -1,321 +0,0 @@ -// Copyright 2015 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. - -#include "src/inspector/v8-profiler-agent-impl.h" - -#include - -#include "src/base/atomicops.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" - -#include "include/v8-profiler.h" - -namespace v8_inspector { - -namespace ProfilerAgentState { -static const char samplingInterval[] = "samplingInterval"; -static const char userInitiatedProfiling[] = "userInitiatedProfiling"; -static const char profilerEnabled[] = "profilerEnabled"; -} - -namespace { - -std::unique_ptr> -buildInspectorObjectForPositionTicks(const v8::CpuProfileNode* node) { - unsigned lineCount = node->GetHitLineCount(); - if (!lineCount) return nullptr; - auto array = protocol::Array::create(); - std::vector entries(lineCount); - if (node->GetLineTicks(&entries[0], lineCount)) { - for (unsigned i = 0; i < lineCount; i++) { - std::unique_ptr line = - protocol::Profiler::PositionTickInfo::create() - .setLine(entries[i].line) - .setTicks(entries[i].hit_count) - .build(); - array->addItem(std::move(line)); - } - } - return array; -} - -std::unique_ptr buildInspectorObjectFor( - v8::Isolate* isolate, const v8::CpuProfileNode* node) { - v8::HandleScope handleScope(isolate); - auto callFrame = - protocol::Runtime::CallFrame::create() - .setFunctionName(toProtocolString(node->GetFunctionName())) - .setScriptId(String16::fromInteger(node->GetScriptId())) - .setUrl(toProtocolString(node->GetScriptResourceName())) - .setLineNumber(node->GetLineNumber() - 1) - .setColumnNumber(node->GetColumnNumber() - 1) - .build(); - auto result = protocol::Profiler::ProfileNode::create() - .setCallFrame(std::move(callFrame)) - .setHitCount(node->GetHitCount()) - .setId(node->GetNodeId()) - .build(); - - const int childrenCount = node->GetChildrenCount(); - if (childrenCount) { - auto children = protocol::Array::create(); - for (int i = 0; i < childrenCount; i++) - children->addItem(node->GetChild(i)->GetNodeId()); - result->setChildren(std::move(children)); - } - - const char* deoptReason = node->GetBailoutReason(); - if (deoptReason && deoptReason[0] && strcmp(deoptReason, "no reason")) - result->setDeoptReason(deoptReason); - - auto positionTicks = buildInspectorObjectForPositionTicks(node); - if (positionTicks) result->setPositionTicks(std::move(positionTicks)); - - return result; -} - -std::unique_ptr> buildInspectorObjectForSamples( - v8::CpuProfile* v8profile) { - auto array = protocol::Array::create(); - int count = v8profile->GetSamplesCount(); - for (int i = 0; i < count; i++) - array->addItem(v8profile->GetSample(i)->GetNodeId()); - return array; -} - -std::unique_ptr> buildInspectorObjectForTimestamps( - v8::CpuProfile* v8profile) { - auto array = protocol::Array::create(); - int count = v8profile->GetSamplesCount(); - uint64_t lastTime = v8profile->GetStartTime(); - for (int i = 0; i < count; i++) { - uint64_t ts = v8profile->GetSampleTimestamp(i); - array->addItem(static_cast(ts - lastTime)); - lastTime = ts; - } - return array; -} - -void flattenNodesTree(v8::Isolate* isolate, const v8::CpuProfileNode* node, - protocol::Array* list) { - list->addItem(buildInspectorObjectFor(isolate, node)); - const int childrenCount = node->GetChildrenCount(); - for (int i = 0; i < childrenCount; i++) - flattenNodesTree(isolate, node->GetChild(i), list); -} - -std::unique_ptr createCPUProfile( - v8::Isolate* isolate, v8::CpuProfile* v8profile) { - auto nodes = protocol::Array::create(); - flattenNodesTree(isolate, v8profile->GetTopDownRoot(), nodes.get()); - return protocol::Profiler::Profile::create() - .setNodes(std::move(nodes)) - .setStartTime(static_cast(v8profile->GetStartTime())) - .setEndTime(static_cast(v8profile->GetEndTime())) - .setSamples(buildInspectorObjectForSamples(v8profile)) - .setTimeDeltas(buildInspectorObjectForTimestamps(v8profile)) - .build(); -} - -std::unique_ptr currentDebugLocation( - V8InspectorImpl* inspector) { - std::unique_ptr callStack = - inspector->debugger()->captureStackTrace(false /* fullStack */); - auto location = protocol::Debugger::Location::create() - .setScriptId(toString16(callStack->topScriptId())) - .setLineNumber(callStack->topLineNumber()) - .build(); - location->setColumnNumber(callStack->topColumnNumber()); - return location; -} - -volatile int s_lastProfileId = 0; - -} // namespace - -class V8ProfilerAgentImpl::ProfileDescriptor { - public: - ProfileDescriptor(const String16& id, const String16& title) - : m_id(id), m_title(title) {} - String16 m_id; - String16 m_title; -}; - -V8ProfilerAgentImpl::V8ProfilerAgentImpl( - V8InspectorSessionImpl* session, protocol::FrontendChannel* frontendChannel, - protocol::DictionaryValue* state) - : m_session(session), - m_isolate(m_session->inspector()->isolate()), - m_profiler(nullptr), - m_state(state), - m_frontend(frontendChannel), - m_enabled(false), - m_recordingCPUProfile(false) {} - -V8ProfilerAgentImpl::~V8ProfilerAgentImpl() { - if (m_profiler) m_profiler->Dispose(); -} - -void V8ProfilerAgentImpl::consoleProfile(const String16& title) { - if (!m_enabled) return; - String16 id = nextProfileId(); - m_startedProfiles.push_back(ProfileDescriptor(id, title)); - startProfiling(id); - m_frontend.consoleProfileStarted( - id, currentDebugLocation(m_session->inspector()), title); -} - -void V8ProfilerAgentImpl::consoleProfileEnd(const String16& title) { - if (!m_enabled) return; - String16 id; - String16 resolvedTitle; - // Take last started profile if no title was passed. - if (title.isEmpty()) { - if (m_startedProfiles.empty()) return; - id = m_startedProfiles.back().m_id; - resolvedTitle = m_startedProfiles.back().m_title; - m_startedProfiles.pop_back(); - } else { - for (size_t i = 0; i < m_startedProfiles.size(); i++) { - if (m_startedProfiles[i].m_title == title) { - resolvedTitle = title; - id = m_startedProfiles[i].m_id; - m_startedProfiles.erase(m_startedProfiles.begin() + i); - break; - } - } - if (id.isEmpty()) return; - } - std::unique_ptr profile = - stopProfiling(id, true); - if (!profile) return; - std::unique_ptr location = - currentDebugLocation(m_session->inspector()); - m_frontend.consoleProfileFinished(id, std::move(location), std::move(profile), - resolvedTitle); -} - -void V8ProfilerAgentImpl::enable(ErrorString*) { - if (m_enabled) return; - m_enabled = true; - DCHECK(!m_profiler); - m_profiler = v8::CpuProfiler::New(m_isolate); - m_state->setBoolean(ProfilerAgentState::profilerEnabled, true); -} - -void V8ProfilerAgentImpl::disable(ErrorString* errorString) { - if (!m_enabled) return; - for (size_t i = m_startedProfiles.size(); i > 0; --i) - stopProfiling(m_startedProfiles[i - 1].m_id, false); - m_startedProfiles.clear(); - stop(nullptr, nullptr); - m_profiler->Dispose(); - m_profiler = nullptr; - m_enabled = false; - m_state->setBoolean(ProfilerAgentState::profilerEnabled, false); -} - -void V8ProfilerAgentImpl::setSamplingInterval(ErrorString* error, - int interval) { - if (m_recordingCPUProfile) { - *error = "Cannot change sampling interval when profiling."; - return; - } - m_state->setInteger(ProfilerAgentState::samplingInterval, interval); - m_profiler->SetSamplingInterval(interval); -} - -void V8ProfilerAgentImpl::restore() { - DCHECK(!m_enabled); - if (!m_state->booleanProperty(ProfilerAgentState::profilerEnabled, false)) - return; - m_enabled = true; - DCHECK(!m_profiler); - m_profiler = v8::CpuProfiler::New(m_isolate); - int interval = 0; - m_state->getInteger(ProfilerAgentState::samplingInterval, &interval); - if (interval) m_profiler->SetSamplingInterval(interval); - if (m_state->booleanProperty(ProfilerAgentState::userInitiatedProfiling, - false)) { - ErrorString error; - start(&error); - } -} - -void V8ProfilerAgentImpl::start(ErrorString* error) { - if (m_recordingCPUProfile) return; - if (!m_enabled) { - *error = "Profiler is not enabled"; - return; - } - m_recordingCPUProfile = true; - m_frontendInitiatedProfileId = nextProfileId(); - startProfiling(m_frontendInitiatedProfileId); - m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true); -} - -void V8ProfilerAgentImpl::stop( - ErrorString* errorString, - std::unique_ptr* profile) { - if (!m_recordingCPUProfile) { - if (errorString) *errorString = "No recording profiles found"; - return; - } - m_recordingCPUProfile = false; - std::unique_ptr cpuProfile = - stopProfiling(m_frontendInitiatedProfileId, !!profile); - if (profile) { - *profile = std::move(cpuProfile); - if (!profile->get() && errorString) *errorString = "Profile is not found"; - } - m_frontendInitiatedProfileId = String16(); - m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false); -} - -String16 V8ProfilerAgentImpl::nextProfileId() { - return String16::fromInteger( - v8::base::NoBarrier_AtomicIncrement(&s_lastProfileId, 1)); -} - -void V8ProfilerAgentImpl::startProfiling(const String16& title) { - v8::HandleScope handleScope(m_isolate); - m_profiler->StartProfiling(toV8String(m_isolate, title), true); -} - -std::unique_ptr V8ProfilerAgentImpl::stopProfiling( - const String16& title, bool serialize) { - v8::HandleScope handleScope(m_isolate); - v8::CpuProfile* profile = - m_profiler->StopProfiling(toV8String(m_isolate, title)); - if (!profile) return nullptr; - std::unique_ptr result; - if (serialize) result = createCPUProfile(m_isolate, profile); - profile->Delete(); - return result; -} - -bool V8ProfilerAgentImpl::isRecording() const { - return m_recordingCPUProfile || !m_startedProfiles.empty(); -} - -bool V8ProfilerAgentImpl::idleStarted() { - if (m_profiler) m_profiler->SetIdle(true); - return m_profiler; -} - -bool V8ProfilerAgentImpl::idleFinished() { - if (m_profiler) m_profiler->SetIdle(false); - return m_profiler; -} - -void V8ProfilerAgentImpl::collectSample() { - if (m_profiler) m_profiler->CollectSample(); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-profiler-agent-impl.h b/deps/v8_inspector/src/inspector/v8-profiler-agent-impl.h deleted file mode 100644 index ee8997653af518..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-profiler-agent-impl.h +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2015 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8PROFILERAGENTIMPL_H_ -#define V8_INSPECTOR_V8PROFILERAGENTIMPL_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Profiler.h" - -namespace v8 { -class CpuProfiler; -class Isolate; -} - -namespace v8_inspector { - -class V8InspectorSessionImpl; - -using protocol::ErrorString; - -class V8ProfilerAgentImpl : public protocol::Profiler::Backend { - public: - V8ProfilerAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, - protocol::DictionaryValue* state); - ~V8ProfilerAgentImpl() override; - - bool enabled() const { return m_enabled; } - void restore(); - - void enable(ErrorString*) override; - void disable(ErrorString*) override; - void setSamplingInterval(ErrorString*, int) override; - void start(ErrorString*) override; - void stop(ErrorString*, - std::unique_ptr*) override; - - void consoleProfile(const String16& title); - void consoleProfileEnd(const String16& title); - - bool idleStarted(); - bool idleFinished(); - - void collectSample(); - - private: - String16 nextProfileId(); - - void startProfiling(const String16& title); - std::unique_ptr stopProfiling( - const String16& title, bool serialize); - - bool isRecording() const; - - V8InspectorSessionImpl* m_session; - v8::Isolate* m_isolate; - v8::CpuProfiler* m_profiler; - protocol::DictionaryValue* m_state; - protocol::Profiler::Frontend m_frontend; - bool m_enabled; - bool m_recordingCPUProfile; - class ProfileDescriptor; - std::vector m_startedProfiles; - String16 m_frontendInitiatedProfileId; - - DISALLOW_COPY_AND_ASSIGN(V8ProfilerAgentImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8PROFILERAGENTIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-regex.cc b/deps/v8_inspector/src/inspector/v8-regex.cc deleted file mode 100644 index 47af70d3604ae1..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-regex.cc +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-regex.h" - -#include - -#include "src/inspector/string-util.h" -#include "src/inspector/v8-inspector-impl.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -V8Regex::V8Regex(V8InspectorImpl* inspector, const String16& pattern, - bool caseSensitive, bool multiline) - : m_inspector(inspector) { - v8::Isolate* isolate = m_inspector->isolate(); - v8::HandleScope handleScope(isolate); - v8::Local context = m_inspector->regexContext(); - v8::Context::Scope contextScope(context); - v8::TryCatch tryCatch(isolate); - - unsigned flags = v8::RegExp::kNone; - if (!caseSensitive) flags |= v8::RegExp::kIgnoreCase; - if (multiline) flags |= v8::RegExp::kMultiline; - - v8::Local regex; - if (v8::RegExp::New(context, toV8String(isolate, pattern), - static_cast(flags)) - .ToLocal(®ex)) - m_regex.Reset(isolate, regex); - else if (tryCatch.HasCaught()) - m_errorMessage = toProtocolString(tryCatch.Message()->Get()); - else - m_errorMessage = "Internal error"; -} - -int V8Regex::match(const String16& string, int startFrom, - int* matchLength) const { - if (matchLength) *matchLength = 0; - - if (m_regex.IsEmpty() || string.isEmpty()) return -1; - - // v8 strings are limited to int. - if (string.length() > INT_MAX) return -1; - - v8::Isolate* isolate = m_inspector->isolate(); - v8::HandleScope handleScope(isolate); - v8::Local context = m_inspector->regexContext(); - v8::MicrotasksScope microtasks(isolate, - v8::MicrotasksScope::kDoNotRunMicrotasks); - v8::TryCatch tryCatch(isolate); - - v8::Local regex = m_regex.Get(isolate); - v8::Local exec; - if (!regex->Get(context, toV8StringInternalized(isolate, "exec")) - .ToLocal(&exec)) - return -1; - v8::Local argv[] = { - toV8String(isolate, string.substring(startFrom))}; - v8::Local returnValue; - if (!exec.As() - ->Call(context, regex, arraysize(argv), argv) - .ToLocal(&returnValue)) - return -1; - - // RegExp#exec returns null if there's no match, otherwise it returns an - // Array of strings with the first being the whole match string and others - // being subgroups. The Array also has some random properties tacked on like - // "index" which is the offset of the match. - // - // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec - - DCHECK(!returnValue.IsEmpty()); - if (!returnValue->IsArray()) return -1; - - v8::Local result = returnValue.As(); - v8::Local matchOffset; - if (!result->Get(context, toV8StringInternalized(isolate, "index")) - .ToLocal(&matchOffset)) - return -1; - if (matchLength) { - v8::Local match; - if (!result->Get(context, 0).ToLocal(&match)) return -1; - *matchLength = match.As()->Length(); - } - - return matchOffset.As()->Value() + startFrom; -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-regex.h b/deps/v8_inspector/src/inspector/v8-regex.h deleted file mode 100644 index b4b1f8ce13517a..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-regex.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8REGEX_H_ -#define V8_INSPECTOR_V8REGEX_H_ - -#include "src/base/macros.h" -#include "src/inspector/string-16.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class V8InspectorImpl; - -enum MultilineMode { MultilineDisabled, MultilineEnabled }; - -class V8Regex { - public: - V8Regex(V8InspectorImpl*, const String16&, bool caseSensitive, - bool multiline = false); - int match(const String16&, int startFrom = 0, int* matchLength = 0) const; - bool isValid() const { return !m_regex.IsEmpty(); } - const String16& errorMessage() const { return m_errorMessage; } - - private: - V8InspectorImpl* m_inspector; - v8::Global m_regex; - String16 m_errorMessage; - - DISALLOW_COPY_AND_ASSIGN(V8Regex); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8REGEX_H_ diff --git a/deps/v8_inspector/src/inspector/v8-runtime-agent-impl.cc b/deps/v8_inspector/src/inspector/v8-runtime-agent-impl.cc deleted file mode 100644 index 640ec317d23752..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-runtime-agent-impl.cc +++ /dev/null @@ -1,738 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "src/inspector/v8-runtime-agent-impl.h" - -#include "src/inspector/injected-script.h" -#include "src/inspector/inspected-context.h" -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/remote-object-id.h" -#include "src/inspector/string-util.h" -#include "src/inspector/v8-console-message.h" -#include "src/inspector/v8-debugger-agent-impl.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-inspector-session-impl.h" -#include "src/inspector/v8-stack-trace-impl.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -namespace V8RuntimeAgentImplState { -static const char customObjectFormatterEnabled[] = - "customObjectFormatterEnabled"; -static const char runtimeEnabled[] = "runtimeEnabled"; -}; - -using protocol::Runtime::RemoteObject; - -static bool hasInternalError(ErrorString* errorString, bool hasError) { - if (hasError) *errorString = "Internal error"; - return hasError; -} - -namespace { - -template -class ProtocolPromiseHandler { - public: - static void add(V8InspectorImpl* inspector, v8::Local context, - v8::MaybeLocal value, - const String16& notPromiseError, int contextGroupId, - int executionContextId, const String16& objectGroup, - bool returnByValue, bool generatePreview, - std::unique_ptr callback) { - if (value.IsEmpty()) { - callback->sendFailure("Internal error"); - return; - } - if (!value.ToLocalChecked()->IsPromise()) { - callback->sendFailure(notPromiseError); - return; - } - v8::MicrotasksScope microtasks_scope(inspector->isolate(), - v8::MicrotasksScope::kRunMicrotasks); - v8::Local promise = - v8::Local::Cast(value.ToLocalChecked()); - Callback* rawCallback = callback.get(); - ProtocolPromiseHandler* handler = new ProtocolPromiseHandler( - inspector, contextGroupId, executionContextId, objectGroup, - returnByValue, generatePreview, std::move(callback)); - v8::Local wrapper = handler->m_wrapper.Get(inspector->isolate()); - - v8::Local thenCallbackFunction = - v8::Function::New(context, thenCallback, wrapper, 0, - v8::ConstructorBehavior::kThrow) - .ToLocalChecked(); - if (promise->Then(context, thenCallbackFunction).IsEmpty()) { - rawCallback->sendFailure("Internal error"); - return; - } - v8::Local catchCallbackFunction = - v8::Function::New(context, catchCallback, wrapper, 0, - v8::ConstructorBehavior::kThrow) - .ToLocalChecked(); - if (promise->Catch(context, catchCallbackFunction).IsEmpty()) { - rawCallback->sendFailure("Internal error"); - return; - } - } - - private: - static void thenCallback(const v8::FunctionCallbackInfo& info) { - ProtocolPromiseHandler* handler = - static_cast*>( - info.Data().As()->Value()); - DCHECK(handler); - v8::Local value = - info.Length() > 0 - ? info[0] - : v8::Local::Cast(v8::Undefined(info.GetIsolate())); - std::unique_ptr wrappedValue( - handler->wrapObject(value)); - if (!wrappedValue) return; - handler->m_callback->sendSuccess( - std::move(wrappedValue), Maybe()); - } - - static void catchCallback(const v8::FunctionCallbackInfo& info) { - ProtocolPromiseHandler* handler = - static_cast*>( - info.Data().As()->Value()); - DCHECK(handler); - v8::Local value = - info.Length() > 0 - ? info[0] - : v8::Local::Cast(v8::Undefined(info.GetIsolate())); - - std::unique_ptr wrappedValue( - handler->wrapObject(value)); - if (!wrappedValue) return; - - std::unique_ptr stack = - handler->m_inspector->debugger()->captureStackTrace(true); - std::unique_ptr exceptionDetails = - protocol::Runtime::ExceptionDetails::create() - .setExceptionId(handler->m_inspector->nextExceptionId()) - .setText("Uncaught (in promise)") - .setLineNumber(stack && !stack->isEmpty() ? stack->topLineNumber() - : 0) - .setColumnNumber( - stack && !stack->isEmpty() ? stack->topColumnNumber() : 0) - .setException(wrappedValue->clone()) - .build(); - if (stack) - exceptionDetails->setStackTrace(stack->buildInspectorObjectImpl()); - if (stack && !stack->isEmpty()) - exceptionDetails->setScriptId(toString16(stack->topScriptId())); - handler->m_callback->sendSuccess(std::move(wrappedValue), - std::move(exceptionDetails)); - } - - ProtocolPromiseHandler(V8InspectorImpl* inspector, int contextGroupId, - int executionContextId, const String16& objectGroup, - bool returnByValue, bool generatePreview, - std::unique_ptr callback) - : m_inspector(inspector), - m_contextGroupId(contextGroupId), - m_executionContextId(executionContextId), - m_objectGroup(objectGroup), - m_returnByValue(returnByValue), - m_generatePreview(generatePreview), - m_callback(std::move(callback)), - m_wrapper(inspector->isolate(), - v8::External::New(inspector->isolate(), this)) { - m_wrapper.SetWeak(this, cleanup, v8::WeakCallbackType::kParameter); - } - - static void cleanup( - const v8::WeakCallbackInfo>& data) { - if (!data.GetParameter()->m_wrapper.IsEmpty()) { - data.GetParameter()->m_wrapper.Reset(); - data.SetSecondPassCallback(cleanup); - } else { - data.GetParameter()->m_callback->sendFailure("Promise was collected"); - delete data.GetParameter(); - } - } - - std::unique_ptr wrapObject( - v8::Local value) { - ErrorString errorString; - InjectedScript::ContextScope scope(&errorString, m_inspector, - m_contextGroupId, m_executionContextId); - if (!scope.initialize()) { - m_callback->sendFailure(errorString); - return nullptr; - } - std::unique_ptr wrappedValue = - scope.injectedScript()->wrapObject(&errorString, value, m_objectGroup, - m_returnByValue, m_generatePreview); - if (!wrappedValue) { - m_callback->sendFailure(errorString); - return nullptr; - } - return wrappedValue; - } - - V8InspectorImpl* m_inspector; - int m_contextGroupId; - int m_executionContextId; - String16 m_objectGroup; - bool m_returnByValue; - bool m_generatePreview; - std::unique_ptr m_callback; - v8::Global m_wrapper; -}; - -template -bool wrapEvaluateResultAsync(InjectedScript* injectedScript, - v8::MaybeLocal maybeResultValue, - const v8::TryCatch& tryCatch, - const String16& objectGroup, bool returnByValue, - bool generatePreview, Callback* callback) { - std::unique_ptr result; - Maybe exceptionDetails; - - ErrorString errorString; - injectedScript->wrapEvaluateResult( - &errorString, maybeResultValue, tryCatch, objectGroup, returnByValue, - generatePreview, &result, &exceptionDetails); - if (errorString.isEmpty()) { - callback->sendSuccess(std::move(result), exceptionDetails); - return true; - } - callback->sendFailure(errorString); - return false; -} - -int ensureContext(ErrorString* errorString, V8InspectorImpl* inspector, - int contextGroupId, const Maybe& executionContextId) { - int contextId; - if (executionContextId.isJust()) { - contextId = executionContextId.fromJust(); - } else { - v8::HandleScope handles(inspector->isolate()); - v8::Local defaultContext = - inspector->client()->ensureDefaultContextInGroup(contextGroupId); - if (defaultContext.IsEmpty()) { - *errorString = "Cannot find default execution context"; - return 0; - } - contextId = V8Debugger::contextId(defaultContext); - } - return contextId; -} - -} // namespace - -V8RuntimeAgentImpl::V8RuntimeAgentImpl( - V8InspectorSessionImpl* session, protocol::FrontendChannel* FrontendChannel, - protocol::DictionaryValue* state) - : m_session(session), - m_state(state), - m_frontend(FrontendChannel), - m_inspector(session->inspector()), - m_enabled(false) {} - -V8RuntimeAgentImpl::~V8RuntimeAgentImpl() {} - -void V8RuntimeAgentImpl::evaluate( - const String16& expression, const Maybe& objectGroup, - const Maybe& includeCommandLineAPI, const Maybe& silent, - const Maybe& executionContextId, const Maybe& returnByValue, - const Maybe& generatePreview, const Maybe& userGesture, - const Maybe& awaitPromise, - std::unique_ptr callback) { - ErrorString errorString; - int contextId = - ensureContext(&errorString, m_inspector, m_session->contextGroupId(), - executionContextId); - if (!errorString.isEmpty()) { - callback->sendFailure(errorString); - return; - } - - InjectedScript::ContextScope scope(&errorString, m_inspector, - m_session->contextGroupId(), contextId); - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - - if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole(); - if (userGesture.fromMaybe(false)) scope.pretendUserGesture(); - - if (includeCommandLineAPI.fromMaybe(false) && - !scope.installCommandLineAPI()) { - callback->sendFailure(errorString); - return; - } - - bool evalIsDisabled = !scope.context()->IsCodeGenerationFromStringsAllowed(); - // Temporarily enable allow evals for inspector. - if (evalIsDisabled) scope.context()->AllowCodeGenerationFromStrings(true); - - v8::MaybeLocal maybeResultValue; - v8::Local script = m_inspector->compileScript( - scope.context(), toV8String(m_inspector->isolate(), expression), - String16(), false); - if (!script.IsEmpty()) - maybeResultValue = m_inspector->runCompiledScript(scope.context(), script); - - if (evalIsDisabled) scope.context()->AllowCodeGenerationFromStrings(false); - - // Re-initialize after running client's code, as it could have destroyed - // context or session. - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - - if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) { - wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue, - scope.tryCatch(), objectGroup.fromMaybe(""), - returnByValue.fromMaybe(false), - generatePreview.fromMaybe(false), callback.get()); - return; - } - ProtocolPromiseHandler::add( - m_inspector, scope.context(), maybeResultValue, - "Result of the evaluation is not a promise", m_session->contextGroupId(), - scope.injectedScript()->context()->contextId(), objectGroup.fromMaybe(""), - returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), - std::move(callback)); -} - -void V8RuntimeAgentImpl::awaitPromise( - const String16& promiseObjectId, const Maybe& returnByValue, - const Maybe& generatePreview, - std::unique_ptr callback) { - ErrorString errorString; - InjectedScript::ObjectScope scope( - &errorString, m_inspector, m_session->contextGroupId(), promiseObjectId); - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - ProtocolPromiseHandler::add( - m_inspector, scope.context(), scope.object(), - "Could not find promise with given id", m_session->contextGroupId(), - scope.injectedScript()->context()->contextId(), scope.objectGroupName(), - returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), - std::move(callback)); -} - -void V8RuntimeAgentImpl::callFunctionOn( - const String16& objectId, const String16& expression, - const Maybe>& - optionalArguments, - const Maybe& silent, const Maybe& returnByValue, - const Maybe& generatePreview, const Maybe& userGesture, - const Maybe& awaitPromise, - std::unique_ptr callback) { - ErrorString errorString; - InjectedScript::ObjectScope scope(&errorString, m_inspector, - m_session->contextGroupId(), objectId); - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - - std::unique_ptr[]> argv = nullptr; - int argc = 0; - if (optionalArguments.isJust()) { - protocol::Array* arguments = - optionalArguments.fromJust(); - argc = static_cast(arguments->length()); - argv.reset(new v8::Local[argc]); - for (int i = 0; i < argc; ++i) { - v8::Local argumentValue; - if (!scope.injectedScript() - ->resolveCallArgument(&errorString, arguments->get(i)) - .ToLocal(&argumentValue)) { - callback->sendFailure(errorString); - return; - } - argv[i] = argumentValue; - } - } - - if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole(); - if (userGesture.fromMaybe(false)) scope.pretendUserGesture(); - - v8::MaybeLocal maybeFunctionValue = - m_inspector->compileAndRunInternalScript( - scope.context(), - toV8String(m_inspector->isolate(), "(" + expression + ")")); - // Re-initialize after running client's code, as it could have destroyed - // context or session. - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - - if (scope.tryCatch().HasCaught()) { - wrapEvaluateResultAsync(scope.injectedScript(), maybeFunctionValue, - scope.tryCatch(), scope.objectGroupName(), false, - false, callback.get()); - return; - } - - v8::Local functionValue; - if (!maybeFunctionValue.ToLocal(&functionValue) || - !functionValue->IsFunction()) { - callback->sendFailure("Given expression does not evaluate to a function"); - return; - } - - v8::MaybeLocal maybeResultValue = m_inspector->callFunction( - functionValue.As(), scope.context(), scope.object(), argc, - argv.get()); - // Re-initialize after running client's code, as it could have destroyed - // context or session. - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - - if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) { - wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue, - scope.tryCatch(), scope.objectGroupName(), - returnByValue.fromMaybe(false), - generatePreview.fromMaybe(false), callback.get()); - return; - } - - ProtocolPromiseHandler::add( - m_inspector, scope.context(), maybeResultValue, - "Result of the function call is not a promise", - m_session->contextGroupId(), - scope.injectedScript()->context()->contextId(), scope.objectGroupName(), - returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), - std::move(callback)); -} - -void V8RuntimeAgentImpl::getProperties( - ErrorString* errorString, const String16& objectId, - const Maybe& ownProperties, const Maybe& accessorPropertiesOnly, - const Maybe& generatePreview, - std::unique_ptr>* - result, - Maybe>* - internalProperties, - Maybe* exceptionDetails) { - using protocol::Runtime::InternalPropertyDescriptor; - - InjectedScript::ObjectScope scope(errorString, m_inspector, - m_session->contextGroupId(), objectId); - if (!scope.initialize()) return; - - scope.ignoreExceptionsAndMuteConsole(); - if (!scope.object()->IsObject()) { - *errorString = "Value with given id is not an object"; - return; - } - - v8::Local object = scope.object().As(); - scope.injectedScript()->getProperties( - errorString, object, scope.objectGroupName(), - ownProperties.fromMaybe(false), accessorPropertiesOnly.fromMaybe(false), - generatePreview.fromMaybe(false), result, exceptionDetails); - if (!errorString->isEmpty() || exceptionDetails->isJust() || - accessorPropertiesOnly.fromMaybe(false)) - return; - v8::Local propertiesArray; - if (hasInternalError(errorString, !m_inspector->debugger() - ->internalProperties(scope.context(), - scope.object()) - .ToLocal(&propertiesArray))) - return; - std::unique_ptr> - propertiesProtocolArray = - protocol::Array::create(); - for (uint32_t i = 0; i < propertiesArray->Length(); i += 2) { - v8::Local name; - if (hasInternalError( - errorString, - !propertiesArray->Get(scope.context(), i).ToLocal(&name)) || - !name->IsString()) - return; - v8::Local value; - if (hasInternalError( - errorString, - !propertiesArray->Get(scope.context(), i + 1).ToLocal(&value))) - return; - std::unique_ptr wrappedValue = - scope.injectedScript()->wrapObject(errorString, value, - scope.objectGroupName()); - if (!wrappedValue) return; - propertiesProtocolArray->addItem( - InternalPropertyDescriptor::create() - .setName(toProtocolString(name.As())) - .setValue(std::move(wrappedValue)) - .build()); - } - if (!propertiesProtocolArray->length()) return; - *internalProperties = std::move(propertiesProtocolArray); -} - -void V8RuntimeAgentImpl::releaseObject(ErrorString* errorString, - const String16& objectId) { - InjectedScript::ObjectScope scope(errorString, m_inspector, - m_session->contextGroupId(), objectId); - if (!scope.initialize()) return; - scope.injectedScript()->releaseObject(objectId); -} - -void V8RuntimeAgentImpl::releaseObjectGroup(ErrorString*, - const String16& objectGroup) { - m_session->releaseObjectGroup(objectGroup); -} - -void V8RuntimeAgentImpl::runIfWaitingForDebugger(ErrorString* errorString) { - m_inspector->client()->runIfWaitingForDebugger(m_session->contextGroupId()); -} - -void V8RuntimeAgentImpl::setCustomObjectFormatterEnabled(ErrorString*, - bool enabled) { - m_state->setBoolean(V8RuntimeAgentImplState::customObjectFormatterEnabled, - enabled); - m_session->setCustomObjectFormatterEnabled(enabled); -} - -void V8RuntimeAgentImpl::discardConsoleEntries(ErrorString*) { - V8ConsoleMessageStorage* storage = - m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId()); - storage->clear(); -} - -void V8RuntimeAgentImpl::compileScript( - ErrorString* errorString, const String16& expression, - const String16& sourceURL, bool persistScript, - const Maybe& executionContextId, Maybe* scriptId, - Maybe* exceptionDetails) { - if (!m_enabled) { - *errorString = "Runtime agent is not enabled"; - return; - } - int contextId = - ensureContext(errorString, m_inspector, m_session->contextGroupId(), - executionContextId); - if (!errorString->isEmpty()) return; - InjectedScript::ContextScope scope(errorString, m_inspector, - m_session->contextGroupId(), contextId); - if (!scope.initialize()) return; - - if (!persistScript) m_inspector->debugger()->muteScriptParsedEvents(); - v8::Local script = m_inspector->compileScript( - scope.context(), toV8String(m_inspector->isolate(), expression), - sourceURL, false); - if (!persistScript) m_inspector->debugger()->unmuteScriptParsedEvents(); - if (script.IsEmpty()) { - if (scope.tryCatch().HasCaught()) - *exceptionDetails = scope.injectedScript()->createExceptionDetails( - errorString, scope.tryCatch(), String16(), false); - else - *errorString = "Script compilation failed"; - return; - } - - if (!persistScript) return; - - String16 scriptValueId = - String16::fromInteger(script->GetUnboundScript()->GetId()); - std::unique_ptr> global( - new v8::Global(m_inspector->isolate(), script)); - m_compiledScripts[scriptValueId] = std::move(global); - *scriptId = scriptValueId; -} - -void V8RuntimeAgentImpl::runScript( - const String16& scriptId, const Maybe& executionContextId, - const Maybe& objectGroup, const Maybe& silent, - const Maybe& includeCommandLineAPI, const Maybe& returnByValue, - const Maybe& generatePreview, const Maybe& awaitPromise, - std::unique_ptr callback) { - if (!m_enabled) { - callback->sendFailure("Runtime agent is not enabled"); - return; - } - - auto it = m_compiledScripts.find(scriptId); - if (it == m_compiledScripts.end()) { - callback->sendFailure("No script with given id"); - return; - } - - ErrorString errorString; - int contextId = - ensureContext(&errorString, m_inspector, m_session->contextGroupId(), - executionContextId); - if (!errorString.isEmpty()) { - callback->sendFailure(errorString); - return; - } - - InjectedScript::ContextScope scope(&errorString, m_inspector, - m_session->contextGroupId(), contextId); - if (!scope.initialize()) { - callback->sendFailure(errorString); - return; - } - - if (silent.fromMaybe(false)) scope.ignoreExceptionsAndMuteConsole(); - - std::unique_ptr> scriptWrapper = std::move(it->second); - m_compiledScripts.erase(it); - v8::Local script = scriptWrapper->Get(m_inspector->isolate()); - if (script.IsEmpty()) { - callback->sendFailure("Script execution failed"); - return; - } - - if (includeCommandLineAPI.fromMaybe(false) && !scope.installCommandLineAPI()) - return; - - v8::MaybeLocal maybeResultValue = - m_inspector->runCompiledScript(scope.context(), script); - - // Re-initialize after running client's code, as it could have destroyed - // context or session. - if (!scope.initialize()) return; - - if (!awaitPromise.fromMaybe(false) || scope.tryCatch().HasCaught()) { - wrapEvaluateResultAsync(scope.injectedScript(), maybeResultValue, - scope.tryCatch(), objectGroup.fromMaybe(""), - returnByValue.fromMaybe(false), - generatePreview.fromMaybe(false), callback.get()); - return; - } - ProtocolPromiseHandler::add( - m_inspector, scope.context(), maybeResultValue.ToLocalChecked(), - "Result of the script execution is not a promise", - m_session->contextGroupId(), - scope.injectedScript()->context()->contextId(), objectGroup.fromMaybe(""), - returnByValue.fromMaybe(false), generatePreview.fromMaybe(false), - std::move(callback)); -} - -void V8RuntimeAgentImpl::restore() { - if (!m_state->booleanProperty(V8RuntimeAgentImplState::runtimeEnabled, false)) - return; - m_frontend.executionContextsCleared(); - ErrorString error; - enable(&error); - if (m_state->booleanProperty( - V8RuntimeAgentImplState::customObjectFormatterEnabled, false)) - m_session->setCustomObjectFormatterEnabled(true); -} - -void V8RuntimeAgentImpl::enable(ErrorString* errorString) { - if (m_enabled) return; - m_inspector->client()->beginEnsureAllContextsInGroup( - m_session->contextGroupId()); - m_enabled = true; - m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, true); - m_inspector->enableStackCapturingIfNeeded(); - m_session->reportAllContexts(this); - V8ConsoleMessageStorage* storage = - m_inspector->ensureConsoleMessageStorage(m_session->contextGroupId()); - for (const auto& message : storage->messages()) { - if (!reportMessage(message.get(), false)) return; - } -} - -void V8RuntimeAgentImpl::disable(ErrorString* errorString) { - if (!m_enabled) return; - m_enabled = false; - m_state->setBoolean(V8RuntimeAgentImplState::runtimeEnabled, false); - m_inspector->disableStackCapturingIfNeeded(); - m_session->discardInjectedScripts(); - reset(); - m_inspector->client()->endEnsureAllContextsInGroup( - m_session->contextGroupId()); -} - -void V8RuntimeAgentImpl::reset() { - m_compiledScripts.clear(); - if (m_enabled) { - if (const V8InspectorImpl::ContextByIdMap* contexts = - m_inspector->contextGroup(m_session->contextGroupId())) { - for (auto& idContext : *contexts) idContext.second->setReported(false); - } - m_frontend.executionContextsCleared(); - } -} - -void V8RuntimeAgentImpl::reportExecutionContextCreated( - InspectedContext* context) { - if (!m_enabled) return; - context->setReported(true); - std::unique_ptr description = - protocol::Runtime::ExecutionContextDescription::create() - .setId(context->contextId()) - .setName(context->humanReadableName()) - .setOrigin(context->origin()) - .build(); - if (!context->auxData().isEmpty()) - description->setAuxData(protocol::DictionaryValue::cast( - protocol::parseJSON(context->auxData()))); - m_frontend.executionContextCreated(std::move(description)); -} - -void V8RuntimeAgentImpl::reportExecutionContextDestroyed( - InspectedContext* context) { - if (m_enabled && context->isReported()) { - context->setReported(false); - m_frontend.executionContextDestroyed(context->contextId()); - } -} - -void V8RuntimeAgentImpl::inspect( - std::unique_ptr objectToInspect, - std::unique_ptr hints) { - if (m_enabled) - m_frontend.inspectRequested(std::move(objectToInspect), std::move(hints)); -} - -void V8RuntimeAgentImpl::messageAdded(V8ConsoleMessage* message) { - if (m_enabled) reportMessage(message, true); -} - -bool V8RuntimeAgentImpl::reportMessage(V8ConsoleMessage* message, - bool generatePreview) { - message->reportToFrontend(&m_frontend, m_session, generatePreview); - m_frontend.flush(); - return m_inspector->hasConsoleMessageStorage(m_session->contextGroupId()); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-runtime-agent-impl.h b/deps/v8_inspector/src/inspector/v8-runtime-agent-impl.h deleted file mode 100644 index edeeed47ed455c..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-runtime-agent-impl.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef V8_INSPECTOR_V8RUNTIMEAGENTIMPL_H_ -#define V8_INSPECTOR_V8RUNTIMEAGENTIMPL_H_ - -#include "src/base/macros.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Runtime.h" - -#include "include/v8.h" - -namespace v8_inspector { - -class InjectedScript; -class InspectedContext; -class RemoteObjectIdBase; -class V8ConsoleMessage; -class V8InspectorImpl; -class V8InspectorSessionImpl; - -using protocol::ErrorString; -using protocol::Maybe; - -class V8RuntimeAgentImpl : public protocol::Runtime::Backend { - public: - V8RuntimeAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, - protocol::DictionaryValue* state); - ~V8RuntimeAgentImpl() override; - void restore(); - - // Part of the protocol. - void enable(ErrorString*) override; - void disable(ErrorString*) override; - void evaluate(const String16& expression, const Maybe& objectGroup, - const Maybe& includeCommandLineAPI, - const Maybe& silent, const Maybe& executionContextId, - const Maybe& returnByValue, - const Maybe& generatePreview, - const Maybe& userGesture, const Maybe& awaitPromise, - std::unique_ptr) override; - void awaitPromise(const String16& promiseObjectId, - const Maybe& returnByValue, - const Maybe& generatePreview, - std::unique_ptr) override; - void callFunctionOn( - const String16& objectId, const String16& expression, - const Maybe>& - optionalArguments, - const Maybe& silent, const Maybe& returnByValue, - const Maybe& generatePreview, const Maybe& userGesture, - const Maybe& awaitPromise, - std::unique_ptr) override; - void releaseObject(ErrorString*, const String16& objectId) override; - void getProperties( - ErrorString*, const String16& objectId, const Maybe& ownProperties, - const Maybe& accessorPropertiesOnly, - const Maybe& generatePreview, - std::unique_ptr>* - result, - Maybe>* - internalProperties, - Maybe*) override; - void releaseObjectGroup(ErrorString*, const String16& objectGroup) override; - void runIfWaitingForDebugger(ErrorString*) override; - void setCustomObjectFormatterEnabled(ErrorString*, bool) override; - void discardConsoleEntries(ErrorString*) override; - void compileScript(ErrorString*, const String16& expression, - const String16& sourceURL, bool persistScript, - const Maybe& executionContextId, Maybe*, - Maybe*) override; - void runScript(const String16&, const Maybe& executionContextId, - const Maybe& objectGroup, const Maybe& silent, - const Maybe& includeCommandLineAPI, - const Maybe& returnByValue, - const Maybe& generatePreview, - const Maybe& awaitPromise, - std::unique_ptr) override; - - void reset(); - void reportExecutionContextCreated(InspectedContext*); - void reportExecutionContextDestroyed(InspectedContext*); - void inspect(std::unique_ptr objectToInspect, - std::unique_ptr hints); - void messageAdded(V8ConsoleMessage*); - bool enabled() const { return m_enabled; } - - private: - bool reportMessage(V8ConsoleMessage*, bool generatePreview); - - V8InspectorSessionImpl* m_session; - protocol::DictionaryValue* m_state; - protocol::Runtime::Frontend m_frontend; - V8InspectorImpl* m_inspector; - bool m_enabled; - protocol::HashMap>> - m_compiledScripts; - - DISALLOW_COPY_AND_ASSIGN(V8RuntimeAgentImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8RUNTIMEAGENTIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-schema-agent-impl.cc b/deps/v8_inspector/src/inspector/v8-schema-agent-impl.cc deleted file mode 100644 index 9eed5bdf813710..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-schema-agent-impl.cc +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-schema-agent-impl.h" - -#include "src/inspector/protocol/Protocol.h" -#include "src/inspector/v8-inspector-session-impl.h" - -namespace v8_inspector { - -V8SchemaAgentImpl::V8SchemaAgentImpl(V8InspectorSessionImpl* session, - protocol::FrontendChannel* frontendChannel, - protocol::DictionaryValue* state) - : m_session(session), m_frontend(frontendChannel) {} - -V8SchemaAgentImpl::~V8SchemaAgentImpl() {} - -void V8SchemaAgentImpl::getDomains( - ErrorString*, - std::unique_ptr>* result) { - std::vector> domains = - m_session->supportedDomainsImpl(); - *result = protocol::Array::create(); - for (size_t i = 0; i < domains.size(); ++i) - (*result)->addItem(std::move(domains[i])); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-schema-agent-impl.h b/deps/v8_inspector/src/inspector/v8-schema-agent-impl.h deleted file mode 100644 index 6150201f8bdace..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-schema-agent-impl.h +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8SCHEMAAGENTIMPL_H_ -#define V8_INSPECTOR_V8SCHEMAAGENTIMPL_H_ - -#include "src/base/macros.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Schema.h" - -namespace v8_inspector { - -class V8InspectorSessionImpl; - -using protocol::ErrorString; - -class V8SchemaAgentImpl : public protocol::Schema::Backend { - public: - V8SchemaAgentImpl(V8InspectorSessionImpl*, protocol::FrontendChannel*, - protocol::DictionaryValue* state); - ~V8SchemaAgentImpl() override; - - void getDomains( - ErrorString*, - std::unique_ptr>*) override; - - private: - V8InspectorSessionImpl* m_session; - protocol::Schema::Frontend m_frontend; - - DISALLOW_COPY_AND_ASSIGN(V8SchemaAgentImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8SCHEMAAGENTIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-stack-trace-impl.cc b/deps/v8_inspector/src/inspector/v8-stack-trace-impl.cc deleted file mode 100644 index 1a38c6dd82a002..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-stack-trace-impl.cc +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-stack-trace-impl.h" - -#include "src/inspector/string-util.h" -#include "src/inspector/v8-debugger.h" -#include "src/inspector/v8-inspector-impl.h" -#include "src/inspector/v8-profiler-agent-impl.h" - -#include "include/v8-debug.h" -#include "include/v8-profiler.h" -#include "include/v8-version.h" - -namespace v8_inspector { - -namespace { - -static const v8::StackTrace::StackTraceOptions stackTraceOptions = - static_cast( - v8::StackTrace::kLineNumber | v8::StackTrace::kColumnOffset | - v8::StackTrace::kScriptId | v8::StackTrace::kScriptNameOrSourceURL | - v8::StackTrace::kFunctionName); - -V8StackTraceImpl::Frame toFrame(v8::Local frame) { - String16 scriptId = String16::fromInteger(frame->GetScriptId()); - String16 sourceName; - v8::Local sourceNameValue(frame->GetScriptNameOrSourceURL()); - if (!sourceNameValue.IsEmpty()) - sourceName = toProtocolString(sourceNameValue); - - String16 functionName; - v8::Local functionNameValue(frame->GetFunctionName()); - if (!functionNameValue.IsEmpty()) - functionName = toProtocolString(functionNameValue); - - int sourceLineNumber = frame->GetLineNumber(); - int sourceColumn = frame->GetColumn(); - return V8StackTraceImpl::Frame(functionName, scriptId, sourceName, - sourceLineNumber, sourceColumn); -} - -void toFramesVector(v8::Local stackTrace, - std::vector& frames, - size_t maxStackSize, v8::Isolate* isolate) { - DCHECK(isolate->InContext()); - int frameCount = stackTrace->GetFrameCount(); - if (frameCount > static_cast(maxStackSize)) - frameCount = static_cast(maxStackSize); - for (int i = 0; i < frameCount; i++) { - v8::Local stackFrame = stackTrace->GetFrame(i); - frames.push_back(toFrame(stackFrame)); - } -} - -} // namespace - -V8StackTraceImpl::Frame::Frame() - : m_functionName("undefined"), - m_scriptId(""), - m_scriptName("undefined"), - m_lineNumber(0), - m_columnNumber(0) {} - -V8StackTraceImpl::Frame::Frame(const String16& functionName, - const String16& scriptId, - const String16& scriptName, int lineNumber, - int column) - : m_functionName(functionName), - m_scriptId(scriptId), - m_scriptName(scriptName), - m_lineNumber(lineNumber), - m_columnNumber(column) { - DCHECK(m_lineNumber != v8::Message::kNoLineNumberInfo); - DCHECK(m_columnNumber != v8::Message::kNoColumnInfo); -} - -V8StackTraceImpl::Frame::~Frame() {} - -// buildInspectorObject() and SourceLocation's toTracedValue() should set the -// same fields. -// If either of them is modified, the other should be also modified. -std::unique_ptr -V8StackTraceImpl::Frame::buildInspectorObject() const { - return protocol::Runtime::CallFrame::create() - .setFunctionName(m_functionName) - .setScriptId(m_scriptId) - .setUrl(m_scriptName) - .setLineNumber(m_lineNumber - 1) - .setColumnNumber(m_columnNumber - 1) - .build(); -} - -V8StackTraceImpl::Frame V8StackTraceImpl::Frame::clone() const { - return Frame(m_functionName, m_scriptId, m_scriptName, m_lineNumber, - m_columnNumber); -} - -// static -void V8StackTraceImpl::setCaptureStackTraceForUncaughtExceptions( - v8::Isolate* isolate, bool capture) { - isolate->SetCaptureStackTraceForUncaughtExceptions( - capture, V8StackTraceImpl::maxCallStackSizeToCapture, stackTraceOptions); -} - -// static -std::unique_ptr V8StackTraceImpl::create( - V8Debugger* debugger, int contextGroupId, - v8::Local stackTrace, size_t maxStackSize, - const String16& description) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::HandleScope scope(isolate); - std::vector frames; - if (!stackTrace.IsEmpty()) - toFramesVector(stackTrace, frames, maxStackSize, isolate); - - int maxAsyncCallChainDepth = 1; - V8StackTraceImpl* asyncCallChain = nullptr; - if (debugger && maxStackSize > 1) { - asyncCallChain = debugger->currentAsyncCallChain(); - maxAsyncCallChainDepth = debugger->maxAsyncCallChainDepth(); - } - // Do not accidentally append async call chain from another group. This should - // not - // happen if we have proper instrumentation, but let's double-check to be - // safe. - if (contextGroupId && asyncCallChain && asyncCallChain->m_contextGroupId && - asyncCallChain->m_contextGroupId != contextGroupId) { - asyncCallChain = nullptr; - maxAsyncCallChainDepth = 1; - } - - // Only the top stack in the chain may be empty, so ensure that second stack - // is non-empty (it's the top of appended chain). - if (asyncCallChain && asyncCallChain->isEmpty()) - asyncCallChain = asyncCallChain->m_parent.get(); - - if (stackTrace.IsEmpty() && !asyncCallChain) return nullptr; - - std::unique_ptr result(new V8StackTraceImpl( - contextGroupId, description, frames, - asyncCallChain ? asyncCallChain->cloneImpl() : nullptr)); - - // Crop to not exceed maxAsyncCallChainDepth. - V8StackTraceImpl* deepest = result.get(); - while (deepest && maxAsyncCallChainDepth) { - deepest = deepest->m_parent.get(); - maxAsyncCallChainDepth--; - } - if (deepest) deepest->m_parent.reset(); - - return result; -} - -// static -std::unique_ptr V8StackTraceImpl::capture( - V8Debugger* debugger, int contextGroupId, size_t maxStackSize, - const String16& description) { - v8::Isolate* isolate = v8::Isolate::GetCurrent(); - v8::HandleScope handleScope(isolate); - v8::Local stackTrace; - if (isolate->InContext()) { - if (debugger) { - V8InspectorImpl* inspector = debugger->inspector(); - V8ProfilerAgentImpl* profilerAgent = - inspector->enabledProfilerAgentForGroup(contextGroupId); - if (profilerAgent) profilerAgent->collectSample(); - } - stackTrace = v8::StackTrace::CurrentStackTrace( - isolate, static_cast(maxStackSize), stackTraceOptions); - } - return V8StackTraceImpl::create(debugger, contextGroupId, stackTrace, - maxStackSize, description); -} - -std::unique_ptr V8StackTraceImpl::cloneImpl() { - std::vector framesCopy(m_frames); - return wrapUnique( - new V8StackTraceImpl(m_contextGroupId, m_description, framesCopy, - m_parent ? m_parent->cloneImpl() : nullptr)); -} - -std::unique_ptr V8StackTraceImpl::clone() { - std::vector frames; - for (size_t i = 0; i < m_frames.size(); i++) - frames.push_back(m_frames.at(i).clone()); - return wrapUnique( - new V8StackTraceImpl(m_contextGroupId, m_description, frames, nullptr)); -} - -V8StackTraceImpl::V8StackTraceImpl(int contextGroupId, - const String16& description, - std::vector& frames, - std::unique_ptr parent) - : m_contextGroupId(contextGroupId), - m_description(description), - m_parent(std::move(parent)) { - m_frames.swap(frames); -} - -V8StackTraceImpl::~V8StackTraceImpl() {} - -StringView V8StackTraceImpl::topSourceURL() const { - DCHECK(m_frames.size()); - return toStringView(m_frames[0].m_scriptName); -} - -int V8StackTraceImpl::topLineNumber() const { - DCHECK(m_frames.size()); - return m_frames[0].m_lineNumber; -} - -int V8StackTraceImpl::topColumnNumber() const { - DCHECK(m_frames.size()); - return m_frames[0].m_columnNumber; -} - -StringView V8StackTraceImpl::topFunctionName() const { - DCHECK(m_frames.size()); - return toStringView(m_frames[0].m_functionName); -} - -StringView V8StackTraceImpl::topScriptId() const { - DCHECK(m_frames.size()); - return toStringView(m_frames[0].m_scriptId); -} - -std::unique_ptr -V8StackTraceImpl::buildInspectorObjectImpl() const { - std::unique_ptr> frames = - protocol::Array::create(); - for (size_t i = 0; i < m_frames.size(); i++) - frames->addItem(m_frames.at(i).buildInspectorObject()); - - std::unique_ptr stackTrace = - protocol::Runtime::StackTrace::create() - .setCallFrames(std::move(frames)) - .build(); - if (!m_description.isEmpty()) stackTrace->setDescription(m_description); - if (m_parent) stackTrace->setParent(m_parent->buildInspectorObjectImpl()); - return stackTrace; -} - -std::unique_ptr -V8StackTraceImpl::buildInspectorObjectForTail(V8Debugger* debugger) const { - v8::HandleScope handleScope(v8::Isolate::GetCurrent()); - // Next call collapses possible empty stack and ensures - // maxAsyncCallChainDepth. - std::unique_ptr fullChain = V8StackTraceImpl::create( - debugger, m_contextGroupId, v8::Local(), - V8StackTraceImpl::maxCallStackSizeToCapture); - if (!fullChain || !fullChain->m_parent) return nullptr; - return fullChain->m_parent->buildInspectorObjectImpl(); -} - -std::unique_ptr -V8StackTraceImpl::buildInspectorObject() const { - return buildInspectorObjectImpl(); -} - -std::unique_ptr V8StackTraceImpl::toString() const { - String16Builder stackTrace; - for (size_t i = 0; i < m_frames.size(); ++i) { - const Frame& frame = m_frames[i]; - stackTrace.append("\n at " + (frame.functionName().length() - ? frame.functionName() - : "(anonymous function)")); - stackTrace.append(" ("); - stackTrace.append(frame.sourceURL()); - stackTrace.append(':'); - stackTrace.append(String16::fromInteger(frame.lineNumber())); - stackTrace.append(':'); - stackTrace.append(String16::fromInteger(frame.columnNumber())); - stackTrace.append(')'); - } - String16 string = stackTrace.toString(); - return StringBufferImpl::adopt(string); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-stack-trace-impl.h b/deps/v8_inspector/src/inspector/v8-stack-trace-impl.h deleted file mode 100644 index f0a452e9390dd8..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-stack-trace-impl.h +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8STACKTRACEIMPL_H_ -#define V8_INSPECTOR_V8STACKTRACEIMPL_H_ - -#include - -#include "src/base/macros.h" -#include "src/inspector/protocol/Forward.h" -#include "src/inspector/protocol/Runtime.h" - -#include "include/v8-inspector.h" - -namespace v8_inspector { - -class TracedValue; -class V8Debugger; - -// Note: async stack trace may have empty top stack with non-empty tail to -// indicate -// that current native-only state had some async story. -// On the other hand, any non-top async stack is guaranteed to be non-empty. -class V8StackTraceImpl final : public V8StackTrace { - public: - static const size_t maxCallStackSizeToCapture = 200; - - class Frame { - public: - Frame(); - Frame(const String16& functionName, const String16& scriptId, - const String16& scriptName, int lineNumber, int column = 0); - ~Frame(); - - const String16& functionName() const { return m_functionName; } - const String16& scriptId() const { return m_scriptId; } - const String16& sourceURL() const { return m_scriptName; } - int lineNumber() const { return m_lineNumber; } - int columnNumber() const { return m_columnNumber; } - Frame clone() const; - - private: - friend class V8StackTraceImpl; - std::unique_ptr buildInspectorObject() const; - void toTracedValue(TracedValue*) const; - - String16 m_functionName; - String16 m_scriptId; - String16 m_scriptName; - int m_lineNumber; - int m_columnNumber; - }; - - static void setCaptureStackTraceForUncaughtExceptions(v8::Isolate*, - bool capture); - static std::unique_ptr create( - V8Debugger*, int contextGroupId, v8::Local, - size_t maxStackSize, const String16& description = String16()); - static std::unique_ptr capture( - V8Debugger*, int contextGroupId, size_t maxStackSize, - const String16& description = String16()); - - // This method drops the async chain. Use cloneImpl() instead. - std::unique_ptr clone() override; - std::unique_ptr cloneImpl(); - std::unique_ptr buildInspectorObjectForTail( - V8Debugger*) const; - std::unique_ptr buildInspectorObjectImpl() - const; - ~V8StackTraceImpl() override; - - // V8StackTrace implementation. - bool isEmpty() const override { return !m_frames.size(); }; - StringView topSourceURL() const override; - int topLineNumber() const override; - int topColumnNumber() const override; - StringView topScriptId() const override; - StringView topFunctionName() const override; - std::unique_ptr buildInspectorObject() - const override; - std::unique_ptr toString() const override; - - private: - V8StackTraceImpl(int contextGroupId, const String16& description, - std::vector& frames, - std::unique_ptr parent); - - int m_contextGroupId; - String16 m_description; - std::vector m_frames; - std::unique_ptr m_parent; - - DISALLOW_COPY_AND_ASSIGN(V8StackTraceImpl); -}; - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8STACKTRACEIMPL_H_ diff --git a/deps/v8_inspector/src/inspector/v8-value-copier.cc b/deps/v8_inspector/src/inspector/v8-value-copier.cc deleted file mode 100644 index 09d86b7b985016..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-value-copier.cc +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2016 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. - -#include "src/inspector/v8-value-copier.h" - -namespace v8_inspector { - -namespace { - -static int kMaxDepth = 20; -static int kMaxCalls = 1000; - -class V8ValueCopier { - public: - v8::MaybeLocal copy(v8::Local value, int depth) { - if (++m_calls > kMaxCalls || depth > kMaxDepth) - return v8::MaybeLocal(); - - if (value.IsEmpty()) return v8::MaybeLocal(); - if (value->IsNull() || value->IsUndefined() || value->IsBoolean() || - value->IsString() || value->IsNumber()) - return value; - if (!value->IsObject()) return v8::MaybeLocal(); - v8::Local object = value.As(); - if (object->CreationContext() != m_from) return value; - - if (object->IsArray()) { - v8::Local array = object.As(); - v8::Local result = v8::Array::New(m_isolate, array->Length()); - if (!result->SetPrototype(m_to, v8::Null(m_isolate)).FromMaybe(false)) - return v8::MaybeLocal(); - for (uint32_t i = 0; i < array->Length(); ++i) { - v8::Local item; - if (!array->Get(m_from, i).ToLocal(&item)) - return v8::MaybeLocal(); - v8::Local copied; - if (!copy(item, depth + 1).ToLocal(&copied)) - return v8::MaybeLocal(); - if (!createDataProperty(m_to, result, i, copied).FromMaybe(false)) - return v8::MaybeLocal(); - } - return result; - } - - v8::Local result = v8::Object::New(m_isolate); - if (!result->SetPrototype(m_to, v8::Null(m_isolate)).FromMaybe(false)) - return v8::MaybeLocal(); - v8::Local properties; - if (!object->GetOwnPropertyNames(m_from).ToLocal(&properties)) - return v8::MaybeLocal(); - for (uint32_t i = 0; i < properties->Length(); ++i) { - v8::Local name; - if (!properties->Get(m_from, i).ToLocal(&name) || !name->IsString()) - return v8::MaybeLocal(); - v8::Local property; - if (!object->Get(m_from, name).ToLocal(&property)) - return v8::MaybeLocal(); - v8::Local copied; - if (!copy(property, depth + 1).ToLocal(&copied)) - return v8::MaybeLocal(); - if (!createDataProperty(m_to, result, v8::Local::Cast(name), - copied) - .FromMaybe(false)) - return v8::MaybeLocal(); - } - return result; - } - - v8::Isolate* m_isolate; - v8::Local m_from; - v8::Local m_to; - int m_calls; -}; - -} // namespace - -v8::MaybeLocal copyValueFromDebuggerContext( - v8::Isolate* isolate, v8::Local debuggerContext, - v8::Local toContext, v8::Local value) { - V8ValueCopier copier; - copier.m_isolate = isolate; - copier.m_from = debuggerContext; - copier.m_to = toContext; - copier.m_calls = 0; - return copier.copy(value, 0); -} - -v8::Maybe createDataProperty(v8::Local context, - v8::Local object, - v8::Local key, - v8::Local value) { - v8::TryCatch tryCatch(context->GetIsolate()); - v8::Isolate::DisallowJavascriptExecutionScope throwJs( - context->GetIsolate(), - v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); - return object->CreateDataProperty(context, key, value); -} - -v8::Maybe createDataProperty(v8::Local context, - v8::Local array, int index, - v8::Local value) { - v8::TryCatch tryCatch(context->GetIsolate()); - v8::Isolate::DisallowJavascriptExecutionScope throwJs( - context->GetIsolate(), - v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE); - return array->CreateDataProperty(context, index, value); -} - -} // namespace v8_inspector diff --git a/deps/v8_inspector/src/inspector/v8-value-copier.h b/deps/v8_inspector/src/inspector/v8-value-copier.h deleted file mode 100644 index c24a5648a21642..00000000000000 --- a/deps/v8_inspector/src/inspector/v8-value-copier.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2016 the V8 project authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef V8_INSPECTOR_V8VALUECOPIER_H_ -#define V8_INSPECTOR_V8VALUECOPIER_H_ - -#include "include/v8.h" - -namespace v8_inspector { - -v8::MaybeLocal copyValueFromDebuggerContext( - v8::Isolate*, v8::Local debuggerContext, - v8::Local toContext, v8::Local); -v8::Maybe createDataProperty(v8::Local, - v8::Local, - v8::Local key, - v8::Local); -v8::Maybe createDataProperty(v8::Local, v8::Local, - int index, v8::Local); - -} // namespace v8_inspector - -#endif // V8_INSPECTOR_V8VALUECOPIER_H_ diff --git a/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/lib/BackendCallback_h.template b/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/lib/BackendCallback_h.template deleted file mode 100644 index 3c8fc15b3216e5..00000000000000 --- a/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/lib/BackendCallback_h.template +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2016 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. - -#ifndef {{"_".join(config.protocol.namespace)}}_BackendCallback_h -#define {{"_".join(config.protocol.namespace)}}_BackendCallback_h - -//#include "Forward.h" - -{% for namespace in config.protocol.namespace %} -namespace {{namespace}} { -{% endfor %} - -class {{config.lib.export_macro}} BackendCallback { -public: - virtual ~BackendCallback() { } - virtual void sendFailure(const ErrorString&) = 0; -}; - -{% for namespace in config.protocol.namespace %} -} // namespace {{namespace}} -{% endfor %} - -#endif // !defined({{"_".join(config.protocol.namespace)}}_BackendCallback_h) diff --git a/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/sample_config.json b/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/sample_config.json deleted file mode 100644 index 82d7845da3cbcd..00000000000000 --- a/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/sample_config.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "protocol": { - "path": "./relative/path/protocol/sample_protocol.json", - "package": "include/generated/files/like/this", - "output": "place/generated/files/here", - "namespace": ["sample_project", "protocol"], - "export_macro": "LIB_EXPORT", - "export_header": "lib/lib_export.h" - }, - - "exported": { - "package": "include/exported/files/like/this", - "output": "place/exported/files/here", - "string_header": "include/exported/string.h", - "string_in": "String", - "string_out": "String", - "to_string_out": "toString(%s)", - "export_macro": "LIB_EXPORT", - "export_header": "lib/lib_export.h" - }, - - "imported": { - "path": "../relative/path/imported_protocol.json", - "package": "either/include/imported/files/from/here", - "header": "or/include/them/all/together/like/this/imported_protocol.h", - "to_imported_string": "toImportedString(%s)", - "from_imported_string": "fromImportedString(%s)", - "namespace": ["imported_project", "protocol"] - }, - - "lib": { - "package": "include/lib/files/like/this", - "output": "place/generated/lib/files/here", - "string_header": "string/implementation.h", - "platform_header": "platform/implementation.h", - "export_macro": "LIB_EXPORT", - "export_header": "lib/lib_export.h" - } -} diff --git a/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/sample_expected_errors.json b/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/sample_expected_errors.json deleted file mode 100644 index 85fa2641db6029..00000000000000 --- a/deps/v8_inspector/third_party/WebKit/Source/platform/inspector_protocol/sample_expected_errors.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "errors": [ - "Domain.event: event has been removed", - "Domain.command: command has been removed", - "Domain.command.param parameter->Domain.TypeName.property: required property has been removed" - ] -} \ No newline at end of file diff --git a/deps/v8_inspector/third_party/jinja2/.gitignore b/deps/v8_inspector/third_party/jinja2/.gitignore deleted file mode 100644 index 3ae1fa70b3cd5c..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*.so -docs/_build -*.pyc -*.pyo -*.egg-info -*.egg -build -dist -.DS_Store -.tox diff --git a/deps/v8_inspector/third_party/jinja2/.travis.yml b/deps/v8_inspector/third_party/jinja2/.travis.yml deleted file mode 100644 index 9cf4d8656f35c9..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: python -python: - - "2.6" - - "2.7" - - "3.3" - - "3.4" - - "3.5" - - "pypy" - -install: - - pip install tox -script: - - tox -e \ - $(echo $TRAVIS_PYTHON_VERSION | sed 's/^\([0-9]\)\.\([0-9]\).*/py\1\2/') - -notifications: - email: false - irc: - channels: - - "chat.freenode.net#pocoo" - on_success: change - on_failure: always - use_notice: true - skip_join: true diff --git a/deps/v8_inspector/third_party/jinja2/CHANGES b/deps/v8_inspector/third_party/jinja2/CHANGES deleted file mode 100644 index 4e5df26c9934f6..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/CHANGES +++ /dev/null @@ -1,375 +0,0 @@ -Jinja2 Changelog -================ - -Version 2.8.1 -------------- - -(unreleased bugfix release) - -- Fixed the `for_qs` flag for `urlencode`. - -Version 2.8 ------------ -(codename Replacement, released on July 26th 2015) - -- Added `target` parameter to urlize function. -- Added support for `followsymlinks` to the file system loader. -- The truncate filter now counts the length. -- Added equalto filter that helps with select filters. -- Changed cache keys to use absolute file names if available - instead of load names. -- Fixed loop length calculation for some iterators. -- Changed how Jinja2 enforces strings to be native strings in - Python 2 to work when people break their default encoding. -- Added :func:`make_logging_undefined` which returns an undefined - object that logs failures into a logger. -- If unmarshalling of cached data fails the template will be - reloaded now. -- Implemented a block ``set`` tag. -- Default cache size was incrased to 400 from a low 50. -- Fixed ``is number`` test to accept long integers in all Python versions. -- Changed ``is number`` to accept Decimal as a number. -- Added a check for default arguments followed by non-default arguments. This - change makes ``{% macro m(x, y=1, z) %}...{% endmacro %}`` a syntax error. The - previous behavior for this code was broken anyway (resulting in the default - value being applied to `y`). -- Add ability to use custom subclasses of ``jinja2.compiler.CodeGenerator`` and - ``jinja2.runtime.Context`` by adding two new attributes to the environment - (`code_generator_class` and `context_class`) (pull request ``#404``). -- added support for context/environment/evalctx decorator functions on - the finalize callback of the environment. -- escape query strings for urlencode properly. Previously slashes were not - escaped in that place. -- Add 'base' parameter to 'int' filter. - -Version 2.7.3 -------------- -(bugfix release, released on June 6th 2014) - -- Security issue: Corrected the security fix for the cache folder. This - fix was provided by RedHat. - -Version 2.7.2 -------------- -(bugfix release, released on January 10th 2014) - -- Prefix loader was not forwarding the locals properly to - inner loaders. This is now fixed. -- Security issue: Changed the default folder for the filesystem cache to be - user specific and read and write protected on UNIX systems. See `Debian bug - 734747`_ for more information. - -.. _Debian bug 734747: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734747 - -Version 2.7.1 -------------- -(bugfix release, released on August 7th 2013) - -- Fixed a bug with ``call_filter`` not working properly on environment - and context filters. -- Fixed lack of Python 3 support for bytecode caches. -- Reverted support for defining blocks in included templates as this - broke existing templates for users. -- Fixed some warnings with hashing of undefineds and nodes if Python - is run with warnings for Python 3. -- Added support for properly hashing undefined objects. -- Fixed a bug with the title filter not working on already uppercase - strings. - -Version 2.7 ------------ -(codename Translation, released on May 20th 2013) - -- Choice and prefix loaders now dispatch source and template lookup - separately in order to work in combination with module loaders as - advertised. -- Fixed filesizeformat. -- Added a non-silent option for babel extraction. -- Added `urlencode` filter that automatically quotes values for - URL safe usage with utf-8 as only supported encoding. If applications - want to change this encoding they can override the filter. -- Added `keep-trailing-newline` configuration to environments and - templates to optionally preserve the final trailing newline. -- Accessing `last` on the loop context no longer causes the iterator - to be consumed into a list. -- Python requirement changed: 2.6, 2.7 or >= 3.3 are required now, - supported by same source code, using the "six" compatibility library. -- Allow `contextfunction` and other decorators to be applied to `__call__`. -- Added support for changing from newline to different signs in the `wordwrap` - filter. -- Added support for ignoring memcache errors silently. -- Added support for keeping the trailing newline in templates. -- Added finer grained support for stripping whitespace on the left side - of blocks. -- Added `map`, `select`, `reject`, `selectattr` and `rejectattr` - filters. -- Added support for `loop.depth` to figure out how deep inside a recursive - loop the code is. -- Disabled py_compile for pypy and python 3. - -Version 2.6 ------------ -(codename Convolution, released on July 24th 2011) - -- internal attributes now raise an internal attribute error now instead - of returning an undefined. This fixes problems when passing undefined - objects to Python semantics expecting APIs. -- traceback support now works properly for PyPy. (Tested with 1.4) -- implemented operator intercepting for sandboxed environments. This - allows application developers to disable builtin operators for better - security. (For instance limit the mathematical operators to actual - integers instead of longs) -- groupby filter now supports dotted notation for grouping by attributes - of attributes. -- scoped blocks now properly treat toplevel assignments and imports. - Previously an import suddenly "disappeared" in a scoped block. -- automatically detect newer Python interpreter versions before loading code - from bytecode caches to prevent segfaults on invalid opcodes. The segfault - in earlier Jinja2 versions here was not a Jinja2 bug but a limitation in - the underlying Python interpreter. If you notice Jinja2 segfaulting in - earlier versions after an upgrade of the Python interpreter you don't have - to upgrade, it's enough to flush the bytecode cache. This just no longer - makes this necessary, Jinja2 will automatically detect these cases now. -- the sum filter can now sum up values by attribute. This is a backwards - incompatible change. The argument to the filter previously was the - optional starting index which defaultes to zero. This now became the - second argument to the function because it's rarely used. -- like sum, sort now also makes it possible to order items by attribute. -- like sum and sort, join now also is able to join attributes of objects - as string. -- the internal eval context now has a reference to the environment. -- added a mapping test to see if an object is a dict or an object with - a similar interface. - -Version 2.5.5 -------------- -(re-release of 2.5.4 with built documentation removed for filesize. - Released on October 18th 2010) - -- built documentation is no longer part of release. - -Version 2.5.4 -------------- -(bugfix release, released on October 17th 2010) - -- Fixed extensions not loading properly with overlays. -- Work around a bug in cpython for the debugger that causes segfaults - on 64bit big-endian architectures. - -Version 2.5.3 -------------- -(bugfix release, released on October 17th 2010) - -- fixed an operator precedence error introduced in 2.5.2. Statements - like "-foo.bar" had their implicit parentheses applied around the - first part of the expression ("(-foo).bar") instead of the more - correct "-(foo.bar)". - -Version 2.5.2 -------------- -(bugfix release, released on August 18th 2010) - -- improved setup.py script to better work with assumptions people - might still have from it (``--with-speedups``). -- fixed a packaging error that excluded the new debug support. - -Version 2.5.1 -------------- -(bugfix release, released on August 17th 2010) - -- StopIteration exceptions raised by functions called from templates - are now intercepted and converted to undefineds. This solves a - lot of debugging grief. (StopIteration is used internally to - abort template execution) -- improved performance of macro calls slightly. -- babel extraction can now properly extract newstyle gettext calls. -- using the variable `num` in newstyle gettext for something else - than the pluralize count will no longer raise a :exc:`KeyError`. -- removed builtin markup class and switched to markupsafe. For backwards - compatibility the pure Python implementation still exists but is - pulled from markupsafe by the Jinja2 developers. The debug support - went into a separate feature called "debugsupport" and is disabled - by default because it is only relevant for Python 2.4 -- fixed an issue with unary operators having the wrong precendence. - -Version 2.5 ------------ -(codename Incoherence, relased on May 29th 2010) - -- improved the sort filter (should have worked like this for a - long time) by adding support for case insensitive searches. -- fixed a bug for getattribute constant folding. -- support for newstyle gettext translations which result in a - nicer in-template user interface and more consistent - catalogs. (:ref:`newstyle-gettext`) -- it's now possible to register extensions after an environment - was created. - -Version 2.4.1 -------------- -(bugfix release, released on April 20th 2010) - -- fixed an error reporting bug for undefineds. - -Version 2.4 ------------ -(codename Correlation, released on April 13th 2010) - -- the environment template loading functions now transparently - pass through a template object if it was passed to it. This - makes it possible to import or extend from a template object - that was passed to the template. -- added a :class:`ModuleLoader` that can load templates from - precompiled sources. The environment now features a method - to compile the templates from a configured loader into a zip - file or folder. -- the _speedups C extension now supports Python 3. -- added support for autoescaping toggling sections and support - for evaluation contexts (:ref:`eval-context`). -- extensions have a priority now. - -Version 2.3.1 -------------- -(bugfix release, released on February 19th 2010) - -- fixed an error reporting bug on all python versions -- fixed an error reporting bug on Python 2.4 - -Version 2.3 ------------ -(3000 Pythons, released on February 10th 2010) - -- fixes issue with code generator that causes unbound variables - to be generated if set was used in if-blocks and other small - identifier problems. -- include tags are now able to select between multiple templates - and take the first that exists, if a list of templates is - given. -- fixed a problem with having call blocks in outer scopes that - have an argument that is also used as local variable in an - inner frame (#360). -- greatly improved error message reporting (#339) -- implicit tuple expressions can no longer be totally empty. - This change makes ``{% if %}...{% endif %}`` a syntax error - now. (#364) -- added support for translator comments if extracted via babel. -- added with-statement extension. -- experimental Python 3 support. - -Version 2.2.1 -------------- -(bugfix release, released on September 14th 2009) - -- fixes some smaller problems for Jinja2 on Jython. - -Version 2.2 ------------ -(codename Kong, released on September 13th 2009) - -- Include statements can now be marked with ``ignore missing`` to skip - non existing templates. -- Priority of `not` raised. It's now possible to write `not foo in bar` - as an alias to `foo not in bar` like in python. Previously the grammar - required parentheses (`not (foo in bar)`) which was odd. -- Fixed a bug that caused syntax errors when defining macros or using the - `{% call %}` tag inside loops. -- Fixed a bug in the parser that made ``{{ foo[1, 2] }}`` impossible. -- Made it possible to refer to names from outer scopes in included templates - that were unused in the callers frame (#327) -- Fixed a bug that caused internal errors if names where used as iteration - variable and regular variable *after* the loop if that variable was unused - *before* the loop. (#331) -- Added support for optional `scoped` modifier to blocks. -- Added support for line-comments. -- Added the `meta` module. -- Renamed (undocumented) attribute "overlay" to "overlayed" on the - environment because it was clashing with a method of the same name. -- speedup extension is now disabled by default. - -Version 2.1.1 -------------- -(Bugfix release) - -- Fixed a translation error caused by looping over empty recursive loops. - -Version 2.1 ------------ -(codename Yasuzō, released on November 23rd 2008) - -- fixed a bug with nested loops and the special loop variable. Before the - change an inner loop overwrote the loop variable from the outer one after - iteration. - -- fixed a bug with the i18n extension that caused the explicit pluralization - block to look up the wrong variable. - -- fixed a limitation in the lexer that made ``{{ foo.0.0 }}`` impossible. - -- index based subscribing of variables with a constant value returns an - undefined object now instead of raising an index error. This was a bug - caused by eager optimizing. - -- the i18n extension looks up `foo.ugettext` now followed by `foo.gettext` - if an translations object is installed. This makes dealing with custom - translations classes easier. - -- fixed a confusing behavior with conditional extending. loops were partially - executed under some conditions even though they were not part of a visible - area. - -- added `sort` filter that works like `dictsort` but for arbitrary sequences. - -- fixed a bug with empty statements in macros. - -- implemented a bytecode cache system. (:ref:`bytecode-cache`) - -- the template context is now weakref-able - -- inclusions and imports "with context" forward all variables now, not only - the initial context. - -- added a cycle helper called `cycler`. - -- added a joining helper called `joiner`. - -- added a `compile_expression` method to the environment that allows compiling - of Jinja expressions into callable Python objects. - -- fixed an escaping bug in urlize - -Version 2.0 ------------ -(codename jinjavitus, released on July 17th 2008) - -- the subscribing of objects (looking up attributes and items) changed from - slightly. It's now possible to give attributes or items a higher priority - by either using dot-notation lookup or the bracket syntax. This also - changed the AST slightly. `Subscript` is gone and was replaced with - :class:`~jinja2.nodes.Getitem` and :class:`~jinja2.nodes.Getattr`. - - For more information see :ref:`the implementation details `. - -- added support for preprocessing and token stream filtering for extensions. - This would allow extensions to allow simplified gettext calls in template - data and something similar. - -- added :meth:`jinja2.environment.TemplateStream.dump`. - -- added missing support for implicit string literal concatenation. - ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}`` - -- `else` is optional for conditional expressions. If not given it evaluates - to `false`. - -- improved error reporting for undefined values by providing a position. - -- `filesizeformat` filter uses decimal prefixes now per default and can be - set to binary mode with the second parameter. - -- fixed bug in finalizer - -Version 2.0rc1 --------------- -(no codename, released on June 9th 2008) - -- first release of Jinja2 diff --git a/deps/v8_inspector/third_party/jinja2/MANIFEST.in b/deps/v8_inspector/third_party/jinja2/MANIFEST.in deleted file mode 100644 index 0d6db7c5edce27..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/MANIFEST.in +++ /dev/null @@ -1,12 +0,0 @@ -include MANIFEST.in Makefile CHANGES LICENSE AUTHORS run-tests.py -recursive-include docs * -recursive-include custom_fixers * -recursive-include ext * -recursive-include artwork * -recursive-include examples * -recursive-include jinja2/testsuite/res * -recursive-exclude docs/_build * -recursive-exclude jinja2 *.pyc -recursive-exclude docs *.pyc -recursive-exclude jinja2 *.pyo -recursive-exclude docs *.pyo diff --git a/deps/v8_inspector/third_party/jinja2/Makefile b/deps/v8_inspector/third_party/jinja2/Makefile deleted file mode 100644 index aadaaa94319a9e..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -test: - py.test - -develop: - pip install --editable . - -tox-test: - @tox - -release: - python scripts/make-release.py - -upload-docs: - $(MAKE) -C docs html dirhtml latex - $(MAKE) -C docs/_build/latex all-pdf - cd docs/_build/; mv html jinja-docs; zip -r jinja-docs.zip jinja-docs; mv jinja-docs html - scp -r docs/_build/dirhtml/* flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/ - scp -r docs/_build/latex/Jinja2.pdf flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/jinja-docs.pdf - scp -r docs/_build/jinja-docs.zip flow.srv.pocoo.org:/srv/websites/jinja.pocoo.org/docs/ - -.PHONY: test diff --git a/deps/v8_inspector/third_party/jinja2/README.rst b/deps/v8_inspector/third_party/jinja2/README.rst deleted file mode 100644 index 0684e8a1b22508..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Jinja2 -~~~~~~ - -Jinja2 is a template engine written in pure Python. It provides a -`Django`_ inspired non-XML syntax but supports inline expressions and -an optional `sandboxed`_ environment. - -Nutshell --------- - -Here a small example of a Jinja template:: - - {% extends 'base.html' %} - {% block title %}Memberlist{% endblock %} - {% block content %} - - {% endblock %} - -Philosophy ----------- - -Application logic is for the controller, but don't make the template designer's -life difficult by restricting functionality too much. - -For more information visit the new `Jinja2 webpage`_ and `documentation`_. - -The `Jinja2 tip`_ is installable via `easy_install` with ``easy_install -Jinja2==dev``. - -.. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security) -.. _Django: http://www.djangoproject.com/ -.. _Jinja2 webpage: http://jinja.pocoo.org/ -.. _documentation: http://jinja.pocoo.org/docs/ -.. _Jinja2 tip: http://jinja.pocoo.org/docs/intro/#as-a-python-egg-via-easy-install - -Builds ------- - -+---------------------+------------------------------------------------------------------------------+ -| ``master`` | .. image:: https://travis-ci.org/mitsuhiko/jinja2.svg?branch=master | -| | :target: https://travis-ci.org/mitsuhiko/jinja2 | -+---------------------+------------------------------------------------------------------------------+ -| ``2.7-maintenance`` | .. image:: https://travis-ci.org/mitsuhiko/jinja2.svg?branch=2.7-maintenance | -| | :target: https://travis-ci.org/mitsuhiko/jinja2 | -+---------------------+------------------------------------------------------------------------------+ diff --git a/deps/v8_inspector/third_party/jinja2/artwork/jinjalogo.svg b/deps/v8_inspector/third_party/jinja2/artwork/jinjalogo.svg deleted file mode 100644 index 0bc9ea4e8b4fd9..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/artwork/jinjalogo.svg +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - diff --git a/deps/v8_inspector/third_party/jinja2/docs/Makefile b/deps/v8_inspector/third_party/jinja2/docs/Makefile deleted file mode 100644 index 52d78d9efe6271..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/Makefile +++ /dev/null @@ -1,118 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp epub latex changes linkcheck doctest - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) _build/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask" - @echo "# ln -s _build/devhelp $$HOME/.local/share/devhelp/Flask" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ - "run these through (pdf)latex." - -latexpdf: latex - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex - @echo "Running LaTeX files through pdflatex..." - make -C _build/latex all-pdf - @echo "pdflatex finished; the PDF files are in _build/latex." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/deps/v8_inspector/third_party/jinja2/docs/_static/jinja-small.png b/deps/v8_inspector/third_party/jinja2/docs/_static/jinja-small.png deleted file mode 100644 index 455b4c3c99cb84..00000000000000 Binary files a/deps/v8_inspector/third_party/jinja2/docs/_static/jinja-small.png and /dev/null differ diff --git a/deps/v8_inspector/third_party/jinja2/docs/_templates/sidebarintro.html b/deps/v8_inspector/third_party/jinja2/docs/_templates/sidebarintro.html deleted file mode 100644 index b7fcfda412f90a..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_templates/sidebarintro.html +++ /dev/null @@ -1,20 +0,0 @@ -

About Jinja2

-

- Jinja2 is a full featured template engine for Python. It has full unicode - support, an optional integrated sandboxed execution environment, widely used - and BSD licensed. -

-

Other Formats

-

- You can download the documentation in other formats as well: -

- -

Useful Links

- diff --git a/deps/v8_inspector/third_party/jinja2/docs/_templates/sidebarlogo.html b/deps/v8_inspector/third_party/jinja2/docs/_templates/sidebarlogo.html deleted file mode 100644 index ca211c6a3e105f..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_templates/sidebarlogo.html +++ /dev/null @@ -1,3 +0,0 @@ - diff --git a/deps/v8_inspector/third_party/jinja2/docs/_themes/LICENSE b/deps/v8_inspector/third_party/jinja2/docs/_themes/LICENSE deleted file mode 100644 index 8daab7ee6efe3b..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_themes/LICENSE +++ /dev/null @@ -1,37 +0,0 @@ -Copyright (c) 2010 by Armin Ronacher. - -Some rights reserved. - -Redistribution and use in source and binary forms of the theme, with or -without modification, are permitted provided that the following conditions -are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -* The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - -We kindly ask you to only use these themes in an unmodified manner just -for Flask and Flask-related products, not for unrelated projects. If you -like the visual style and want to use it for your own projects, please -consider making some larger changes to the themes (such as changing -font faces, sizes, colors or margins). - -THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/deps/v8_inspector/third_party/jinja2/docs/_themes/README b/deps/v8_inspector/third_party/jinja2/docs/_themes/README deleted file mode 100644 index b3292bdff8ed54..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_themes/README +++ /dev/null @@ -1,31 +0,0 @@ -Flask Sphinx Styles -=================== - -This repository contains sphinx styles for Flask and Flask related -projects. To use this style in your Sphinx documentation, follow -this guide: - -1. put this folder as _themes into your docs folder. Alternatively - you can also use git submodules to check out the contents there. -2. add this to your conf.py: - - sys.path.append(os.path.abspath('_themes')) - html_theme_path = ['_themes'] - html_theme = 'flask' - -The following themes exist: - -- 'flask' - the standard flask documentation theme for large - projects -- 'flask_small' - small one-page theme. Intended to be used by - very small addon libraries for flask. - -The following options exist for the flask_small theme: - - [options] - index_logo = '' filename of a picture in _static - to be used as replacement for the - h1 in the index.rst file. - index_logo_height = 120px height of the index logo - github_fork = '' repository name on github for the - "fork me" badge diff --git a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/layout.html b/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/layout.html deleted file mode 100644 index a0c9cab04203b4..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/layout.html +++ /dev/null @@ -1,8 +0,0 @@ -{%- extends "basic/layout.html" %} -{%- block relbar2 %}{% endblock %} -{%- block footer %} - -{%- endblock %} diff --git a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/relations.html b/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/relations.html deleted file mode 100644 index 3bbcde85bb48d3..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/relations.html +++ /dev/null @@ -1,19 +0,0 @@ -

Related Topics

- diff --git a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/static/jinja.css_t b/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/static/jinja.css_t deleted file mode 100644 index 3291ba6fd18605..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/static/jinja.css_t +++ /dev/null @@ -1,396 +0,0 @@ -/* - * jinja.css_t - * ~~~~~~~~~~~ - * - * :copyright: Copyright 2011 by Armin Ronacher. - * :license: Flask Design License, see LICENSE for details. - */ - -@import url(http://fonts.googleapis.com/css?family=Crimson+Text); - -{% set page_width = '940px' %} -{% set sidebar_width = '220px' %} -{% set font_family = 'Georgia, serif' %} -{% set header_font_family = 'Crimson Text, ' ~ font_family %} - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -body { - font-family: {{ font_family }}; - font-size: 17px; - background-color: white; - color: #000; - margin: 0; - padding: 0; -} - -div.document { - width: {{ page_width }}; - margin: 30px auto 0 auto; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.bodywrapper { - margin: 0 0 0 {{ sidebar_width }}; -} - -div.sphinxsidebar { - width: {{ sidebar_width }}; -} - -hr { - border: 1px solid #B1B4B6; -} - -div.body { - background-color: #ffffff; - color: #3E4349; - padding: 0 30px 0 30px; -} - -img.floatingflask { - padding: 0 0 10px 10px; - float: right; -} - -div.footer { - width: {{ page_width }}; - margin: 20px auto 30px auto; - font-size: 14px; - color: #888; - text-align: right; -} - -div.footer a { - color: #888; -} - -div.related { - display: none; -} - -div.sphinxsidebar a { - color: #444; - text-decoration: none; - border-bottom: 1px dotted #999; -} - -div.sphinxsidebar a:hover { - border-bottom: 1px solid #999; -} - -div.sphinxsidebar { - font-size: 15px; - line-height: 1.5; -} - -div.sphinxsidebarwrapper { - padding: 18px 10px; -} - -div.sphinxsidebarwrapper p.logo { - padding: 0 0 20px 0; - margin: 0; - text-align: center; -} - -div.sphinxsidebar h3, -div.sphinxsidebar h4 { - font-family: {{ font_family }}; - color: #444; - font-size: 24px; - font-weight: normal; - margin: 0 0 5px 0; - padding: 0; -} - -div.sphinxsidebar h4 { - font-size: 20px; -} - -div.sphinxsidebar h3 a { - color: #444; -} - -div.sphinxsidebar p.logo a, -div.sphinxsidebar h3 a, -div.sphinxsidebar p.logo a:hover, -div.sphinxsidebar h3 a:hover { - border: none; -} - -div.sphinxsidebar p { - color: #555; - margin: 10px 0; -} - -div.sphinxsidebar ul { - margin: 10px 0; - padding: 0; - color: #000; -} - -div.sphinxsidebar input { - border: 1px solid #ccc; - font-family: {{ font_family }}; - font-size: 14px; -} - -div.sphinxsidebar form.search input[name="q"] { - width: 130px; -} - -/* -- body styles ----------------------------------------------------------- */ - -a { - color: #aa0000; - text-decoration: underline; -} - -a:hover { - color: #dd0000; - text-decoration: underline; -} - -div.body h1, -div.body h2, -div.body h3, -div.body h4, -div.body h5, -div.body h6 { - font-family: {{ header_font_family }}; - font-weight: normal; - margin: 30px 0px 10px 0px; - padding: 0; - color: black; -} - -div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } -div.body h2 { font-size: 180%; } -div.body h3 { font-size: 150%; } -div.body h4 { font-size: 130%; } -div.body h5 { font-size: 100%; } -div.body h6 { font-size: 100%; } - -a.headerlink { - color: #ddd; - padding: 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - color: #444; - background: #eaeaea; -} - -div.body p, div.body dd, div.body li { - line-height: 1.4em; -} - -div.admonition { - background: #fafafa; - margin: 20px -30px; - padding: 10px 30px; - border-top: 1px solid #ccc; - border-bottom: 1px solid #ccc; -} - -div.admonition tt.xref, div.admonition a tt { - border-bottom: 1px solid #fafafa; -} - -dd div.admonition { - margin-left: -60px; - padding-left: 60px; -} - -div.admonition p.admonition-title { - font-family: {{ font_family }}; - font-weight: normal; - font-size: 24px; - margin: 0 0 10px 0; - padding: 0; - line-height: 1; -} - -div.admonition p.last { - margin-bottom: 0; -} - -div.highlight { - background-color: white; -} - -dt:target, .highlight { - background: #FAF3E8; -} - -div.note { - background-color: #eee; - border: 1px solid #ccc; -} - -div.seealso { - background-color: #ffc; - border: 1px solid #ff6; -} - -div.topic { - background-color: #eee; -} - -p.admonition-title { - display: inline; -} - -p.admonition-title:after { - content: ":"; -} - -pre, tt { - font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; - font-size: 0.85em; -} - -img.screenshot { -} - -tt.descname, tt.descclassname { - font-size: 0.95em; -} - -tt.descname { - padding-right: 0.08em; -} - -img.screenshot { - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils { - border: 1px solid #888; - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils td, table.docutils th { - border: 1px solid #888; - padding: 0.25em 0.7em; -} - -table.field-list, table.footnote { - border: none; - -moz-box-shadow: none; - -webkit-box-shadow: none; - box-shadow: none; -} - -table.footnote { - margin: 15px 0; - width: 100%; - border: 1px solid #eee; - background: #fdfdfd; - font-size: 0.9em; -} - -table.footnote + table.footnote { - margin-top: -15px; - border-top: none; -} - -table.field-list th { - padding: 0 0.8em 0 0; -} - -table.field-list td { - padding: 0; -} - -table.footnote td.label { - width: 0px; - padding: 0.3em 0 0.3em 0.5em; -} - -table.footnote td { - padding: 0.3em 0.5em; -} - -dl { - margin: 0; - padding: 0; -} - -dl dd { - margin-left: 30px; -} - -blockquote { - margin: 0 0 0 30px; - padding: 0; -} - -ul, ol { - margin: 10px 0 10px 30px; - padding: 0; -} - -pre { - background: #eee; - padding: 7px 30px; - margin: 15px -30px; - line-height: 1.3em; -} - -dl pre, blockquote pre, li pre { - margin-left: -60px; - padding-left: 60px; -} - -dl dl pre { - margin-left: -90px; - padding-left: 90px; -} - -tt { - background-color: #E8EFF0; - color: #222; - /* padding: 1px 2px; */ -} - -tt.xref, a tt { - background-color: #E8EFF0; - border-bottom: 1px solid white; -} - -a.reference { - text-decoration: none; - border-bottom: 1px dotted #bb0000; -} - -a.reference:hover { - border-bottom: 1px solid #dd0000; -} - -a.footnote-reference { - text-decoration: none; - font-size: 0.7em; - vertical-align: top; - border-bottom: 1px dotted #bb0000; -} - -a.footnote-reference:hover { - border-bottom: 1px solid #dd0000; -} - -a:hover tt { - background: #EEE; -} diff --git a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/theme.conf b/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/theme.conf deleted file mode 100644 index 10c7e56e8371bb..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/_themes/jinja/theme.conf +++ /dev/null @@ -1,3 +0,0 @@ -[theme] -inherit = basic -stylesheet = jinja.css diff --git a/deps/v8_inspector/third_party/jinja2/docs/api.rst b/deps/v8_inspector/third_party/jinja2/docs/api.rst deleted file mode 100644 index 088c8673208087..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/api.rst +++ /dev/null @@ -1,808 +0,0 @@ -API -=== - -.. module:: jinja2 - :synopsis: public Jinja2 API - -This document describes the API to Jinja2 and not the template language. It -will be most useful as reference to those implementing the template interface -to the application and not those who are creating Jinja2 templates. - -Basics ------- - -Jinja2 uses a central object called the template :class:`Environment`. -Instances of this class are used to store the configuration and global objects, -and are used to load templates from the file system or other locations. -Even if you are creating templates from strings by using the constructor of -:class:`Template` class, an environment is created automatically for you, -albeit a shared one. - -Most applications will create one :class:`Environment` object on application -initialization and use that to load templates. In some cases it's however -useful to have multiple environments side by side, if different configurations -are in use. - -The simplest way to configure Jinja2 to load templates for your application -looks roughly like this:: - - from jinja2 import Environment, PackageLoader - env = Environment(loader=PackageLoader('yourapplication', 'templates')) - -This will create a template environment with the default settings and a -loader that looks up the templates in the `templates` folder inside the -`yourapplication` python package. Different loaders are available -and you can also write your own if you want to load templates from a -database or other resources. - -To load a template from this environment you just have to call the -:meth:`get_template` method which then returns the loaded :class:`Template`:: - - template = env.get_template('mytemplate.html') - -To render it with some variables, just call the :meth:`render` method:: - - print template.render(the='variables', go='here') - -Using a template loader rather than passing strings to :class:`Template` -or :meth:`Environment.from_string` has multiple advantages. Besides being -a lot easier to use it also enables template inheritance. - - -Unicode -------- - -Jinja2 is using Unicode internally which means that you have to pass Unicode -objects to the render function or bytestrings that only consist of ASCII -characters. Additionally newlines are normalized to one end of line -sequence which is per default UNIX style (``\n``). - -Python 2.x supports two ways of representing string objects. One is the -`str` type and the other is the `unicode` type, both of which extend a type -called `basestring`. Unfortunately the default is `str` which should not -be used to store text based information unless only ASCII characters are -used. With Python 2.6 it is possible to make `unicode` the default on a per -module level and with Python 3 it will be the default. - -To explicitly use a Unicode string you have to prefix the string literal -with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will -store the string as Unicode by decoding the string with the character -encoding from the current Python module. If no encoding is specified this -defaults to 'ASCII' which means that you can't use any non ASCII identifier. - -To set a better module encoding add the following comment to the first or -second line of the Python module using the Unicode literal:: - - # -*- coding: utf-8 -*- - -We recommend utf-8 as Encoding for Python modules and templates as it's -possible to represent every Unicode character in utf-8 and because it's -backwards compatible to ASCII. For Jinja2 the default encoding of templates -is assumed to be utf-8. - -It is not possible to use Jinja2 to process non-Unicode data. The reason -for this is that Jinja2 uses Unicode already on the language level. For -example Jinja2 treats the non-breaking space as valid whitespace inside -expressions which requires knowledge of the encoding or operating on an -Unicode string. - -For more details about Unicode in Python have a look at the excellent -`Unicode documentation`_. - -Another important thing is how Jinja2 is handling string literals in -templates. A naive implementation would be using Unicode strings for -all string literals but it turned out in the past that this is problematic -as some libraries are typechecking against `str` explicitly. For example -`datetime.strftime` does not accept Unicode arguments. To not break it -completely Jinja2 is returning `str` for strings that fit into ASCII and -for everything else `unicode`: - ->>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module ->>> m.a -'foo' ->>> m.b -u'f\xf6\xf6' - - -.. _Unicode documentation: http://docs.python.org/dev/howto/unicode.html - -High Level API --------------- - -The high-level API is the API you will use in the application to load and -render Jinja2 templates. The :ref:`low-level-api` on the other side is only -useful if you want to dig deeper into Jinja2 or :ref:`develop extensions -`. - -.. autoclass:: Environment([options]) - :members: from_string, get_template, select_template, - get_or_select_template, join_path, extend, compile_expression, - compile_templates, list_templates, add_extension - - .. attribute:: shared - - If a template was created by using the :class:`Template` constructor - an environment is created automatically. These environments are - created as shared environments which means that multiple templates - may have the same anonymous environment. For all shared environments - this attribute is `True`, else `False`. - - .. attribute:: sandboxed - - If the environment is sandboxed this attribute is `True`. For the - sandbox mode have a look at the documentation for the - :class:`~jinja2.sandbox.SandboxedEnvironment`. - - .. attribute:: filters - - A dict of filters for this environment. As long as no template was - loaded it's safe to add new filters or remove old. For custom filters - see :ref:`writing-filters`. For valid filter names have a look at - :ref:`identifier-naming`. - - .. attribute:: tests - - A dict of test functions for this environment. As long as no - template was loaded it's safe to modify this dict. For custom tests - see :ref:`writing-tests`. For valid test names have a look at - :ref:`identifier-naming`. - - .. attribute:: globals - - A dict of global variables. These variables are always available - in a template. As long as no template was loaded it's safe - to modify this dict. For more details see :ref:`global-namespace`. - For valid object names have a look at :ref:`identifier-naming`. - - .. attribute:: code_generator_class - - The class used for code generation. This should not be changed - in most cases, unless you need to modify the Python code a - template compiles to. - - .. attribute:: context_class - - The context used for templates. This should not be changed - in most cases, unless you need to modify internals of how - template variables are handled. For details, see - :class:`~jinja2.runtime.Context`. - - .. automethod:: overlay([options]) - - .. method:: undefined([hint, obj, name, exc]) - - Creates a new :class:`Undefined` object for `name`. This is useful - for filters or functions that may return undefined objects for - some operations. All parameters except of `hint` should be provided - as keyword parameters for better readability. The `hint` is used as - error message for the exception if provided, otherwise the error - message will be generated from `obj` and `name` automatically. The exception - provided as `exc` is raised if something with the generated undefined - object is done that the undefined object does not allow. The default - exception is :exc:`UndefinedError`. If a `hint` is provided the - `name` may be omitted. - - The most common way to create an undefined object is by providing - a name only:: - - return environment.undefined(name='some_name') - - This means that the name `some_name` is not defined. If the name - was from an attribute of an object it makes sense to tell the - undefined object the holder object to improve the error message:: - - if not hasattr(obj, 'attr'): - return environment.undefined(obj=obj, name='attr') - - For a more complex example you can provide a hint. For example - the :func:`first` filter creates an undefined object that way:: - - return environment.undefined('no first item, sequence was empty') - - If it the `name` or `obj` is known (for example because an attribute - was accessed) it should be passed to the undefined object, even if - a custom `hint` is provided. This gives undefined objects the - possibility to enhance the error message. - -.. autoclass:: Template - :members: module, make_module - - .. attribute:: globals - - The dict with the globals of that template. It's unsafe to modify - this dict as it may be shared with other templates or the environment - that loaded the template. - - .. attribute:: name - - The loading name of the template. If the template was loaded from a - string this is `None`. - - .. attribute:: filename - - The filename of the template on the file system if it was loaded from - there. Otherwise this is `None`. - - .. automethod:: render([context]) - - .. automethod:: generate([context]) - - .. automethod:: stream([context]) - - -.. autoclass:: jinja2.environment.TemplateStream() - :members: disable_buffering, enable_buffering, dump - - -Autoescaping ------------- - -.. versionadded:: 2.4 - -As of Jinja 2.4 the preferred way to do autoescaping is to enable the -:ref:`autoescape-extension` and to configure a sensible default for -autoescaping. This makes it possible to enable and disable autoescaping -on a per-template basis (HTML versus text for instance). - -Here a recommended setup that enables autoescaping for templates ending -in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default -for all other extensions:: - - def guess_autoescape(template_name): - if template_name is None or '.' not in template_name: - return False - ext = template_name.rsplit('.', 1)[1] - return ext in ('html', 'htm', 'xml') - - env = Environment(autoescape=guess_autoescape, - loader=PackageLoader('mypackage'), - extensions=['jinja2.ext.autoescape']) - -When implementing a guessing autoescape function, make sure you also -accept `None` as valid template name. This will be passed when generating -templates from strings. - -Inside the templates the behaviour can be temporarily changed by using -the `autoescape` block (see :ref:`autoescape-overrides`). - - -.. _identifier-naming: - -Notes on Identifiers --------------------- - -Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to -match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters -are currently not allowed. This limitation will probably go away as soon as -unicode identifiers are fully specified for Python 3. - -Filters and tests are looked up in separate namespaces and have slightly -modified identifier syntax. Filters and tests may contain dots to group -filters and tests by topic. For example it's perfectly valid to add a -function into the filter dict and call it `to.unicode`. The regular -expression for filter and test identifiers is -``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```. - - -Undefined Types ---------------- - -These classes can be used as undefined types. The :class:`Environment` -constructor takes an `undefined` parameter that can be one of those classes -or a custom subclass of :class:`Undefined`. Whenever the template engine is -unable to look up a name or access an attribute one of those objects is -created and returned. Some operations on undefined values are then allowed, -others fail. - -The closest to regular Python behavior is the `StrictUndefined` which -disallows all operations beside testing if it's an undefined object. - -.. autoclass:: jinja2.Undefined() - - .. attribute:: _undefined_hint - - Either `None` or an unicode string with the error message for - the undefined object. - - .. attribute:: _undefined_obj - - Either `None` or the owner object that caused the undefined object - to be created (for example because an attribute does not exist). - - .. attribute:: _undefined_name - - The name for the undefined variable / attribute or just `None` - if no such information exists. - - .. attribute:: _undefined_exception - - The exception that the undefined object wants to raise. This - is usually one of :exc:`UndefinedError` or :exc:`SecurityError`. - - .. method:: _fail_with_undefined_error(\*args, \**kwargs) - - When called with any arguments this method raises - :attr:`_undefined_exception` with an error message generated - from the undefined hints stored on the undefined object. - -.. autoclass:: jinja2.DebugUndefined() - -.. autoclass:: jinja2.StrictUndefined() - -There is also a factory function that can decorate undefined objects to -implement logging on failures: - -.. autofunction:: jinja2.make_logging_undefined - -Undefined objects are created by calling :attr:`undefined`. - -.. admonition:: Implementation - - :class:`Undefined` objects are implemented by overriding the special - `__underscore__` methods. For example the default :class:`Undefined` - class implements `__unicode__` in a way that it returns an empty - string, however `__int__` and others still fail with an exception. To - allow conversion to int by returning ``0`` you can implement your own:: - - class NullUndefined(Undefined): - def __int__(self): - return 0 - def __float__(self): - return 0.0 - - To disallow a method, just override it and raise - :attr:`~Undefined._undefined_exception`. Because this is a very common - idom in undefined objects there is the helper method - :meth:`~Undefined._fail_with_undefined_error` that does the error raising - automatically. Here a class that works like the regular :class:`Undefined` - but chokes on iteration:: - - class NonIterableUndefined(Undefined): - __iter__ = Undefined._fail_with_undefined_error - - -The Context ------------ - -.. autoclass:: jinja2.runtime.Context() - :members: resolve, get_exported, get_all - - .. attribute:: parent - - A dict of read only, global variables the template looks up. These - can either come from another :class:`Context`, from the - :attr:`Environment.globals` or :attr:`Template.globals` or points - to a dict created by combining the globals with the variables - passed to the render function. It must not be altered. - - .. attribute:: vars - - The template local variables. This list contains environment and - context functions from the :attr:`parent` scope as well as local - modifications and exported variables from the template. The template - will modify this dict during template evaluation but filters and - context functions are not allowed to modify it. - - .. attribute:: environment - - The environment that loaded the template. - - .. attribute:: exported_vars - - This set contains all the names the template exports. The values for - the names are in the :attr:`vars` dict. In order to get a copy of the - exported variables as dict, :meth:`get_exported` can be used. - - .. attribute:: name - - The load name of the template owning this context. - - .. attribute:: blocks - - A dict with the current mapping of blocks in the template. The keys - in this dict are the names of the blocks, and the values a list of - blocks registered. The last item in each list is the current active - block (latest in the inheritance chain). - - .. attribute:: eval_ctx - - The current :ref:`eval-context`. - - .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs) - - -.. admonition:: Implementation - - Context is immutable for the same reason Python's frame locals are - immutable inside functions. Both Jinja2 and Python are not using the - context / frame locals as data storage for variables but only as primary - data source. - - When a template accesses a variable the template does not define, Jinja2 - looks up the variable in the context, after that the variable is treated - as if it was defined in the template. - - -.. _loaders: - -Loaders -------- - -Loaders are responsible for loading templates from a resource such as the -file system. The environment will keep the compiled modules in memory like -Python's `sys.modules`. Unlike `sys.modules` however this cache is limited in -size by default and templates are automatically reloaded. -All loaders are subclasses of :class:`BaseLoader`. If you want to create your -own loader, subclass :class:`BaseLoader` and override `get_source`. - -.. autoclass:: jinja2.BaseLoader - :members: get_source, load - -Here a list of the builtin loaders Jinja2 provides: - -.. autoclass:: jinja2.FileSystemLoader - -.. autoclass:: jinja2.PackageLoader - -.. autoclass:: jinja2.DictLoader - -.. autoclass:: jinja2.FunctionLoader - -.. autoclass:: jinja2.PrefixLoader - -.. autoclass:: jinja2.ChoiceLoader - -.. autoclass:: jinja2.ModuleLoader - - -.. _bytecode-cache: - -Bytecode Cache --------------- - -Jinja 2.1 and higher support external bytecode caching. Bytecode caches make -it possible to store the generated bytecode on the file system or a different -location to avoid parsing the templates on first use. - -This is especially useful if you have a web application that is initialized on -the first request and Jinja compiles many templates at once which slows down -the application. - -To use a bytecode cache, instantiate it and pass it to the :class:`Environment`. - -.. autoclass:: jinja2.BytecodeCache - :members: load_bytecode, dump_bytecode, clear - -.. autoclass:: jinja2.bccache.Bucket - :members: write_bytecode, load_bytecode, bytecode_from_string, - bytecode_to_string, reset - - .. attribute:: environment - - The :class:`Environment` that created the bucket. - - .. attribute:: key - - The unique cache key for this bucket - - .. attribute:: code - - The bytecode if it's loaded, otherwise `None`. - - -Builtin bytecode caches: - -.. autoclass:: jinja2.FileSystemBytecodeCache - -.. autoclass:: jinja2.MemcachedBytecodeCache - - -Utilities ---------- - -These helper functions and classes are useful if you add custom filters or -functions to a Jinja2 environment. - -.. autofunction:: jinja2.environmentfilter - -.. autofunction:: jinja2.contextfilter - -.. autofunction:: jinja2.evalcontextfilter - -.. autofunction:: jinja2.environmentfunction - -.. autofunction:: jinja2.contextfunction - -.. autofunction:: jinja2.evalcontextfunction - -.. function:: escape(s) - - Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s` - to HTML-safe sequences. Use this if you need to display text that might - contain such characters in HTML. This function will not escaped objects - that do have an HTML representation such as already escaped data. - - The return value is a :class:`Markup` string. - -.. autofunction:: jinja2.clear_caches - -.. autofunction:: jinja2.is_undefined - -.. autoclass:: jinja2.Markup([string]) - :members: escape, unescape, striptags - -.. admonition:: Note - - The Jinja2 :class:`Markup` class is compatible with at least Pylons and - Genshi. It's expected that more template engines and framework will pick - up the `__html__` concept soon. - - -Exceptions ----------- - -.. autoexception:: jinja2.TemplateError - -.. autoexception:: jinja2.UndefinedError - -.. autoexception:: jinja2.TemplateNotFound - -.. autoexception:: jinja2.TemplatesNotFound - -.. autoexception:: jinja2.TemplateSyntaxError - - .. attribute:: message - - The error message as utf-8 bytestring. - - .. attribute:: lineno - - The line number where the error occurred - - .. attribute:: name - - The load name for the template as unicode string. - - .. attribute:: filename - - The filename that loaded the template as bytestring in the encoding - of the file system (most likely utf-8 or mbcs on Windows systems). - - The reason why the filename and error message are bytestrings and not - unicode strings is that Python 2.x is not using unicode for exceptions - and tracebacks as well as the compiler. This will change with Python 3. - -.. autoexception:: jinja2.TemplateAssertionError - - -.. _writing-filters: - -Custom Filters --------------- - -Custom filters are just regular Python functions that take the left side of -the filter as first argument and the the arguments passed to the filter as -extra arguments or keyword arguments. - -For example in the filter ``{{ 42|myfilter(23) }}`` the function would be -called with ``myfilter(42, 23)``. Here for example a simple filter that can -be applied to datetime objects to format them:: - - def datetimeformat(value, format='%H:%M / %d-%m-%Y'): - return value.strftime(format) - -You can register it on the template environment by updating the -:attr:`~Environment.filters` dict on the environment:: - - environment.filters['datetimeformat'] = datetimeformat - -Inside the template it can then be used as follows: - -.. sourcecode:: jinja - - written on: {{ article.pub_date|datetimeformat }} - publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }} - -Filters can also be passed the current template context or environment. This -is useful if a filter wants to return an undefined value or check the current -:attr:`~Environment.autoescape` setting. For this purpose three decorators -exist: :func:`environmentfilter`, :func:`contextfilter` and -:func:`evalcontextfilter`. - -Here a small example filter that breaks a text into HTML line breaks and -paragraphs and marks the return value as safe HTML string if autoescaping is -enabled:: - - import re - from jinja2 import evalcontextfilter, Markup, escape - - _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') - - @evalcontextfilter - def nl2br(eval_ctx, value): - result = u'\n\n'.join(u'

%s

' % p.replace('\n', Markup('
\n')) - for p in _paragraph_re.split(escape(value))) - if eval_ctx.autoescape: - result = Markup(result) - return result - -Context filters work the same just that the first argument is the current -active :class:`Context` rather then the environment. - - -.. _eval-context: - -Evaluation Context ------------------- - -The evaluation context (short eval context or eval ctx) is a new object -introduced in Jinja 2.4 that makes it possible to activate and deactivate -compiled features at runtime. - -Currently it is only used to enable and disable the automatic escaping but -can be used for extensions as well. - -In previous Jinja versions filters and functions were marked as -environment callables in order to check for the autoescape status from the -environment. In new versions it's encouraged to check the setting from the -evaluation context instead. - -Previous versions:: - - @environmentfilter - def filter(env, value): - result = do_something(value) - if env.autoescape: - result = Markup(result) - return result - -In new versions you can either use a :func:`contextfilter` and access the -evaluation context from the actual context, or use a -:func:`evalcontextfilter` which directly passes the evaluation context to -the function:: - - @contextfilter - def filter(context, value): - result = do_something(value) - if context.eval_ctx.autoescape: - result = Markup(result) - return result - - @evalcontextfilter - def filter(eval_ctx, value): - result = do_something(value) - if eval_ctx.autoescape: - result = Markup(result) - return result - -The evaluation context must not be modified at runtime. Modifications -must only happen with a :class:`nodes.EvalContextModifier` and -:class:`nodes.ScopedEvalContextModifier` from an extension, not on the -eval context object itself. - -.. autoclass:: jinja2.nodes.EvalContext - - .. attribute:: autoescape - - `True` or `False` depending on if autoescaping is active or not. - - .. attribute:: volatile - - `True` if the compiler cannot evaluate some expressions at compile - time. At runtime this should always be `False`. - - -.. _writing-tests: - -Custom Tests ------------- - -Tests work like filters just that there is no way for a test to get access -to the environment or context and that they can't be chained. The return -value of a test should be `True` or `False`. The purpose of a test is to -give the template designers the possibility to perform type and conformability -checks. - -Here a simple test that checks if a variable is a prime number:: - - import math - - def is_prime(n): - if n == 2: - return True - for i in xrange(2, int(math.ceil(math.sqrt(n))) + 1): - if n % i == 0: - return False - return True - - -You can register it on the template environment by updating the -:attr:`~Environment.tests` dict on the environment:: - - environment.tests['prime'] = is_prime - -A template designer can then use the test like this: - -.. sourcecode:: jinja - - {% if 42 is prime %} - 42 is a prime number - {% else %} - 42 is not a prime number - {% endif %} - - -.. _global-namespace: - -The Global Namespace --------------------- - -Variables stored in the :attr:`Environment.globals` dict are special as they -are available for imported templates too, even if they are imported without -context. This is the place where you can put variables and functions -that should be available all the time. Additionally :attr:`Template.globals` -exist that are variables available to a specific template that are available -to all :meth:`~Template.render` calls. - - -.. _low-level-api: - -Low Level API -------------- - -The low level API exposes functionality that can be useful to understand some -implementation details, debugging purposes or advanced :ref:`extension -` techniques. Unless you know exactly what you are doing we -don't recommend using any of those. - -.. automethod:: Environment.lex - -.. automethod:: Environment.parse - -.. automethod:: Environment.preprocess - -.. automethod:: Template.new_context - -.. method:: Template.root_render_func(context) - - This is the low level render function. It's passed a :class:`Context` - that has to be created by :meth:`new_context` of the same template or - a compatible template. This render function is generated by the - compiler from the template code and returns a generator that yields - unicode strings. - - If an exception in the template code happens the template engine will - not rewrite the exception but pass through the original one. As a - matter of fact this function should only be called from within a - :meth:`render` / :meth:`generate` / :meth:`stream` call. - -.. attribute:: Template.blocks - - A dict of block render functions. Each of these functions works exactly - like the :meth:`root_render_func` with the same limitations. - -.. attribute:: Template.is_up_to_date - - This attribute is `False` if there is a newer version of the template - available, otherwise `True`. - -.. admonition:: Note - - The low-level API is fragile. Future Jinja2 versions will try not to - change it in a backwards incompatible way but modifications in the Jinja2 - core may shine through. For example if Jinja2 introduces a new AST node - in later versions that may be returned by :meth:`~Environment.parse`. - -The Meta API ------------- - -.. versionadded:: 2.2 - -The meta API returns some information about abstract syntax trees that -could help applications to implement more advanced template concepts. All -the functions of the meta API operate on an abstract syntax tree as -returned by the :meth:`Environment.parse` method. - -.. autofunction:: jinja2.meta.find_undeclared_variables - -.. autofunction:: jinja2.meta.find_referenced_templates diff --git a/deps/v8_inspector/third_party/jinja2/docs/cache_extension.py b/deps/v8_inspector/third_party/jinja2/docs/cache_extension.py deleted file mode 100644 index ccdefa2ff313e6..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/cache_extension.py +++ /dev/null @@ -1,56 +0,0 @@ -from jinja2 import nodes -from jinja2.ext import Extension - - -class FragmentCacheExtension(Extension): - # a set of names that trigger the extension. - tags = set(['cache']) - - def __init__(self, environment): - super(FragmentCacheExtension, self).__init__(environment) - - # add the defaults to the environment - environment.extend( - fragment_cache_prefix='', - fragment_cache=None - ) - - def parse(self, parser): - # the first token is the token that started the tag. In our case - # we only listen to ``'cache'`` so this will be a name token with - # `cache` as value. We get the line number so that we can give - # that line number to the nodes we create by hand. - lineno = next(parser.stream).lineno - - # now we parse a single expression that is used as cache key. - args = [parser.parse_expression()] - - # if there is a comma, the user provided a timeout. If not use - # None as second parameter. - if parser.stream.skip_if('comma'): - args.append(parser.parse_expression()) - else: - args.append(nodes.Const(None)) - - # now we parse the body of the cache block up to `endcache` and - # drop the needle (which would always be `endcache` in that case) - body = parser.parse_statements(['name:endcache'], drop_needle=True) - - # now return a `CallBlock` node that calls our _cache_support - # helper method on this extension. - return nodes.CallBlock(self.call_method('_cache_support', args), - [], [], body).set_lineno(lineno) - - def _cache_support(self, name, timeout, caller): - """Helper callback.""" - key = self.environment.fragment_cache_prefix + name - - # try to load the block from the cache - # if there is no fragment in the cache, render it and store - # it in the cache. - rv = self.environment.fragment_cache.get(key) - if rv is not None: - return rv - rv = caller() - self.environment.fragment_cache.add(key, rv, timeout) - return rv diff --git a/deps/v8_inspector/third_party/jinja2/docs/changelog.rst b/deps/v8_inspector/third_party/jinja2/docs/changelog.rst deleted file mode 100644 index 9f114842654b69..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/changelog.rst +++ /dev/null @@ -1,3 +0,0 @@ -.. module:: jinja2 - -.. include:: ../CHANGES diff --git a/deps/v8_inspector/third_party/jinja2/docs/conf.py b/deps/v8_inspector/third_party/jinja2/docs/conf.py deleted file mode 100644 index 6e990be1c719ca..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/conf.py +++ /dev/null @@ -1,160 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Jinja2 documentation build configuration file, created by -# sphinx-quickstart on Sun Apr 27 21:42:41 2008. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# The contents of this file are pickled, so don't put values in the namespace -# that aren't pickleable (module imports are okay, they're removed automatically). -# -# All configuration values have a default value; values that are commented out -# serve to show the default value. - -import sys, os - -# If your extensions are in another directory, add it here. If the directory -# is relative to the documentation root, use os.path.abspath to make it -# absolute, like shown here. -sys.path.append(os.path.dirname(os.path.abspath(__file__))) - -# General configuration -# --------------------- - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'jinjaext'] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix of source filenames. -source_suffix = '.rst' - -# The master toctree document. -master_doc = 'index' - -# General substitutions. -project = 'Jinja2' -copyright = '2008, Armin Ronacher' - -# The default replacements for |version| and |release|, also used in various -# other places throughout the built documents. -# -# The short X.Y version. -import pkg_resources -try: - release = pkg_resources.get_distribution('Jinja2').version -except ImportError: - print 'To build the documentation, The distribution information of Jinja2' - print 'Has to be available. Either install the package into your' - print 'development environment or run "setup.py develop" to setup the' - print 'metadata. A virtualenv is recommended!' - sys.exit(1) -if 'dev' in release: - release = release.split('dev')[0] + 'dev' -version = '.'.join(release.split('.')[:2]) - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -today_fmt = '%B %d, %Y' - -# List of documents that shouldn't be included in the build. -#unused_docs = [] - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'jinjaext.JinjaStyle' - - -# Options for HTML output -# ----------------------- - -html_theme = 'jinja' -html_theme_path = ['_themes'] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# no modindex -html_use_modindex = False - -# If true, the reST sources are included in the HTML build as _sources/. -#html_copy_source = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. -#html_use_opensearch = False - -# Output file base name for HTML help builder. -htmlhelp_basename = 'Jinja2doc' - - -# Options for LaTeX output -# ------------------------ - -# The paper size ('letter' or 'a4'). -latex_paper_size = 'a4' - -# The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, document class [howto/manual]). -latex_documents = [ - ('latexindex', 'Jinja2.tex', 'Jinja2 Documentation', 'Armin Ronacher', - 'manual'), -] - -# Additional stuff for LaTeX -latex_elements = { - 'fontpkg': r'\usepackage{mathpazo}', - 'papersize': 'a4paper', - 'pointsize': '12pt', - 'preamble': r''' -\usepackage{jinjastyle} - -% i hate you latex -\DeclareUnicodeCharacter{14D}{o} -''' -} - -latex_use_parts = True - -latex_additional_files = ['jinjastyle.sty', 'logo.pdf'] - -# If false, no module index is generated. -latex_use_modindex = False - -html_sidebars = { - 'index': ['sidebarlogo.html', 'sidebarintro.html', 'sourcelink.html', - 'searchbox.html'], - '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html', - 'sourcelink.html', 'searchbox.html'] -} diff --git a/deps/v8_inspector/third_party/jinja2/docs/contents.rst.inc b/deps/v8_inspector/third_party/jinja2/docs/contents.rst.inc deleted file mode 100644 index 7ee68703f4a347..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/contents.rst.inc +++ /dev/null @@ -1,23 +0,0 @@ -Jinja2 Documentation --------------------- - -.. toctree:: - :maxdepth: 2 - - intro - api - sandbox - templates - extensions - integration - switching - tricks - -Additional Information ----------------------- - -.. toctree:: - :maxdepth: 2 - - faq - changelog diff --git a/deps/v8_inspector/third_party/jinja2/docs/extensions.rst b/deps/v8_inspector/third_party/jinja2/docs/extensions.rst deleted file mode 100644 index 0825fd4f9b7343..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/extensions.rst +++ /dev/null @@ -1,346 +0,0 @@ -.. _jinja-extensions: - -Extensions -========== - -Jinja2 supports extensions that can add extra filters, tests, globals or even -extend the parser. The main motivation of extensions is to move often used -code into a reusable class like adding support for internationalization. - - -Adding Extensions ------------------ - -Extensions are added to the Jinja2 environment at creation time. Once the -environment is created additional extensions cannot be added. To add an -extension pass a list of extension classes or import paths to the -`extensions` parameter of the :class:`Environment` constructor. The following -example creates a Jinja2 environment with the i18n extension loaded:: - - jinja_env = Environment(extensions=['jinja2.ext.i18n']) - - -.. _i18n-extension: - -i18n Extension --------------- - -**Import name:** `jinja2.ext.i18n` - -The i18n extension can be used in combination with `gettext`_ or `babel`_. If -the i18n extension is enabled Jinja2 provides a `trans` statement that marks -the wrapped string as translatable and calls `gettext`. - -After enabling, dummy `_` function that forwards calls to `gettext` is added -to the environment globals. An internationalized application then has to -provide a `gettext` function and optionally an `ngettext` function into the -namespace, either globally or for each rendering. - -Environment Methods -~~~~~~~~~~~~~~~~~~~ - -After enabling the extension, the environment provides the following -additional methods: - -.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False) - - Installs a translation globally for that environment. The translations - object provided must implement at least `ugettext` and `ungettext`. - The `gettext.NullTranslations` and `gettext.GNUTranslations` classes - as well as `Babel`_\s `Translations` class are supported. - - .. versionchanged:: 2.5 newstyle gettext added - -.. method:: jinja2.Environment.install_null_translations(newstyle=False) - - Install dummy gettext functions. This is useful if you want to prepare - the application for internationalization but don't want to implement the - full internationalization system yet. - - .. versionchanged:: 2.5 newstyle gettext added - -.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False) - - Installs the given `gettext` and `ngettext` callables into the - environment as globals. They are supposed to behave exactly like the - standard library's :func:`gettext.ugettext` and - :func:`gettext.ungettext` functions. - - If `newstyle` is activated, the callables are wrapped to work like - newstyle callables. See :ref:`newstyle-gettext` for more information. - - .. versionadded:: 2.5 - -.. method:: jinja2.Environment.uninstall_gettext_translations() - - Uninstall the translations again. - -.. method:: jinja2.Environment.extract_translations(source) - - Extract localizable strings from the given template node or source. - - For every string found this function yields a ``(lineno, function, - message)`` tuple, where: - - * `lineno` is the number of the line on which the string was found, - * `function` is the name of the `gettext` function used (if the - string was extracted from embedded Python code), and - * `message` is the string itself (a `unicode` object, or a tuple - of `unicode` objects for functions with multiple string arguments). - - If `Babel`_ is installed, :ref:`the babel integration ` - can be used to extract strings for babel. - -For a web application that is available in multiple languages but gives all -the users the same language (for example a multilingual forum software -installed for a French community) may load the translations once and add the -translation methods to the environment at environment generation time:: - - translations = get_gettext_translations() - env = Environment(extensions=['jinja2.ext.i18n']) - env.install_gettext_translations(translations) - -The `get_gettext_translations` function would return the translator for the -current configuration. (For example by using `gettext.find`) - -The usage of the `i18n` extension for template designers is covered as part -:ref:`of the template documentation `. - -.. _gettext: http://docs.python.org/dev/library/gettext -.. _Babel: http://babel.edgewall.org/ - -.. _newstyle-gettext: - -Newstyle Gettext -~~~~~~~~~~~~~~~~ - -.. versionadded:: 2.5 - -Starting with version 2.5 you can use newstyle gettext calls. These are -inspired by trac's internal gettext functions and are fully supported by -the babel extraction tool. They might not work as expected by other -extraction tools in case you are not using Babel's. - -What's the big difference between standard and newstyle gettext calls? In -general they are less to type and less error prone. Also if they are used -in an autoescaping environment they better support automatic escaping. -Here are some common differences between old and new calls: - -standard gettext: - -.. sourcecode:: html+jinja - - {{ gettext('Hello World!') }} - {{ gettext('Hello %(name)s!')|format(name='World') }} - {{ ngettext('%(num)d apple', '%(num)d apples', apples|count)|format( - num=apples|count - )}} - -newstyle gettext looks like this instead: - -.. sourcecode:: html+jinja - - {{ gettext('Hello World!') }} - {{ gettext('Hello %(name)s!', name='World') }} - {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }} - -The advantages of newstyle gettext are that you have less to type and that -named placeholders become mandatory. The latter sounds like a -disadvantage but solves a lot of troubles translators are often facing -when they are unable to switch the positions of two placeholder. With -newstyle gettext, all format strings look the same. - -Furthermore with newstyle gettext, string formatting is also used if no -placeholders are used which makes all strings behave exactly the same. -Last but not least are newstyle gettext calls able to properly mark -strings for autoescaping which solves lots of escaping related issues many -templates are experiencing over time when using autoescaping. - -Expression Statement --------------------- - -**Import name:** `jinja2.ext.do` - -The "do" aka expression-statement extension adds a simple `do` tag to the -template engine that works like a variable expression but ignores the -return value. - -.. _loopcontrols-extension: - -Loop Controls -------------- - -**Import name:** `jinja2.ext.loopcontrols` - -This extension adds support for `break` and `continue` in loops. After -enabling, Jinja2 provides those two keywords which work exactly like in -Python. - -.. _with-extension: - -With Statement --------------- - -**Import name:** `jinja2.ext.with_` - -.. versionadded:: 2.3 - -This extension adds support for the with keyword. Using this keyword it -is possible to enforce a nested scope in a template. Variables can be -declared directly in the opening block of the with statement or using a -standard `set` statement directly within. - -.. _autoescape-extension: - -Autoescape Extension --------------------- - -**Import name:** `jinja2.ext.autoescape` - -.. versionadded:: 2.4 - -The autoescape extension allows you to toggle the autoescape feature from -within the template. If the environment's :attr:`~Environment.autoescape` -setting is set to `False` it can be activated, if it's `True` it can be -deactivated. The setting overriding is scoped. - - -.. _writing-extensions: - -Writing Extensions ------------------- - -.. module:: jinja2.ext - -By writing extensions you can add custom tags to Jinja2. This is a non-trivial -task and usually not needed as the default tags and expressions cover all -common use cases. The i18n extension is a good example of why extensions are -useful. Another one would be fragment caching. - -When writing extensions you have to keep in mind that you are working with the -Jinja2 template compiler which does not validate the node tree you are passing -to it. If the AST is malformed you will get all kinds of compiler or runtime -errors that are horrible to debug. Always make sure you are using the nodes -you create correctly. The API documentation below shows which nodes exist and -how to use them. - -Example Extension -~~~~~~~~~~~~~~~~~ - -The following example implements a `cache` tag for Jinja2 by using the -`Werkzeug`_ caching contrib module: - -.. literalinclude:: cache_extension.py - :language: python - -And here is how you use it in an environment:: - - from jinja2 import Environment - from werkzeug.contrib.cache import SimpleCache - - env = Environment(extensions=[FragmentCacheExtension]) - env.fragment_cache = SimpleCache() - -Inside the template it's then possible to mark blocks as cacheable. The -following example caches a sidebar for 300 seconds: - -.. sourcecode:: html+jinja - - {% cache 'sidebar', 300 %} - - {% endcache %} - -.. _Werkzeug: http://werkzeug.pocoo.org/ - -Extension API -~~~~~~~~~~~~~ - -Extensions always have to extend the :class:`jinja2.ext.Extension` class: - -.. autoclass:: Extension - :members: preprocess, filter_stream, parse, attr, call_method - - .. attribute:: identifier - - The identifier of the extension. This is always the true import name - of the extension class and must not be changed. - - .. attribute:: tags - - If the extension implements custom tags this is a set of tag names - the extension is listening for. - -Parser API -~~~~~~~~~~ - -The parser passed to :meth:`Extension.parse` provides ways to parse -expressions of different types. The following methods may be used by -extensions: - -.. autoclass:: jinja2.parser.Parser - :members: parse_expression, parse_tuple, parse_assign_target, - parse_statements, free_identifier, fail - - .. attribute:: filename - - The filename of the template the parser processes. This is **not** - the load name of the template. For the load name see :attr:`name`. - For templates that were not loaded form the file system this is - `None`. - - .. attribute:: name - - The load name of the template. - - .. attribute:: stream - - The current :class:`~jinja2.lexer.TokenStream` - -.. autoclass:: jinja2.lexer.TokenStream - :members: push, look, eos, skip, next, next_if, skip_if, expect - - .. attribute:: current - - The current :class:`~jinja2.lexer.Token`. - -.. autoclass:: jinja2.lexer.Token - :members: test, test_any - - .. attribute:: lineno - - The line number of the token - - .. attribute:: type - - The type of the token. This string is interned so you may compare - it with arbitrary strings using the `is` operator. - - .. attribute:: value - - The value of the token. - -There is also a utility function in the lexer module that can count newline -characters in strings: - -.. autofunction:: jinja2.lexer.count_newlines - -AST -~~~ - -The AST (Abstract Syntax Tree) is used to represent a template after parsing. -It's build of nodes that the compiler then converts into executable Python -code objects. Extensions that provide custom statements can return nodes to -execute custom Python code. - -The list below describes all nodes that are currently available. The AST may -change between Jinja2 versions but will stay backwards compatible. - -For more information have a look at the repr of :meth:`jinja2.Environment.parse`. - -.. module:: jinja2.nodes - -.. jinjanodes:: - -.. autoexception:: Impossible diff --git a/deps/v8_inspector/third_party/jinja2/docs/faq.rst b/deps/v8_inspector/third_party/jinja2/docs/faq.rst deleted file mode 100644 index 0b0375e190863d..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/faq.rst +++ /dev/null @@ -1,191 +0,0 @@ -Frequently Asked Questions -========================== - -This page answers some of the often asked questions about Jinja. - -.. highlight:: html+jinja - -Why is it called Jinja? ------------------------ - -The name Jinja was chosen because it's the name of a Japanese temple and -temple and template share a similar pronunciation. It is not named after -the city in Uganda. - -How fast is it? ---------------- - -We really hate benchmarks especially since they don't reflect much. The -performance of a template depends on many factors and you would have to -benchmark different engines in different situations. The benchmarks from the -testsuite show that Jinja2 has a similar performance to `Mako`_ and is between -10 and 20 times faster than Django's template engine or Genshi. These numbers -should be taken with tons of salt as the benchmarks that took these numbers -only test a few performance related situations such as looping. Generally -speaking the performance of a template engine doesn't matter much as the -usual bottleneck in a web application is either the database or the application -code. - -.. _Mako: http://www.makotemplates.org/ - -How Compatible is Jinja2 with Django? -------------------------------------- - -The default syntax of Jinja2 matches Django syntax in many ways. However -this similarity doesn't mean that you can use a Django template unmodified -in Jinja2. For example filter arguments use a function call syntax rather -than a colon to separate filter name and arguments. Additionally the -extension interface in Jinja is fundamentally different from the Django one -which means that your custom tags won't work any longer. - -Generally speaking you will use much less custom extensions as the Jinja -template system allows you to use a certain subset of Python expressions -which can replace most Django extensions. For example instead of using -something like this:: - - {% load comments %} - {% get_latest_comments 10 as latest_comments %} - {% for comment in latest_comments %} - ... - {% endfor %} - -You will most likely provide an object with attributes to retrieve -comments from the database:: - - {% for comment in models.comments.latest(10) %} - ... - {% endfor %} - -Or directly provide the model for quick testing:: - - {% for comment in Comment.objects.order_by('-pub_date')[:10] %} - ... - {% endfor %} - -Please keep in mind that even though you may put such things into templates -it still isn't a good idea. Queries should go into the view code and not -the template! - -Isn't it a terrible idea to put Logic into Templates? ------------------------------------------------------ - -Without a doubt you should try to remove as much logic from templates as -possible. But templates without any logic mean that you have to do all -the processing in the code which is boring and stupid. A template engine -that does that is shipped with Python and called `string.Template`. Comes -without loops and if conditions and is by far the fastest template engine -you can get for Python. - -So some amount of logic is required in templates to keep everyone happy. -And Jinja leaves it pretty much to you how much logic you want to put into -templates. There are some restrictions in what you can do and what not. - -Jinja2 neither allows you to put arbitrary Python code into templates nor -does it allow all Python expressions. The operators are limited to the -most common ones and more advanced expressions such as list comprehensions -and generator expressions are not supported. This keeps the template engine -easier to maintain and templates more readable. - -Why is Autoescaping not the Default? ------------------------------------- - -There are multiple reasons why automatic escaping is not the default mode -and also not the recommended one. While automatic escaping of variables -means that you will less likely have an XSS problem it also causes a huge -amount of extra processing in the template engine which can cause serious -performance problems. As Python doesn't provide a way to mark strings as -unsafe Jinja has to hack around that limitation by providing a custom -string class (the :class:`Markup` string) that safely interacts with safe -and unsafe strings. - -With explicit escaping however the template engine doesn't have to perform -any safety checks on variables. Also a human knows not to escape integers -or strings that may never contain characters one has to escape or already -HTML markup. For example when iterating over a list over a table of -integers and floats for a table of statistics the template designer can -omit the escaping because he knows that integers or floats don't contain -any unsafe parameters. - -Additionally Jinja2 is a general purpose template engine and not only used -for HTML/XML generation. For example you may generate LaTeX, emails, -CSS, JavaScript, or configuration files. - -Why is the Context immutable? ------------------------------ - -When writing a :func:`contextfunction` or something similar you may have -noticed that the context tries to stop you from modifying it. If you have -managed to modify the context by using an internal context API you may -have noticed that changes in the context don't seem to be visible in the -template. The reason for this is that Jinja uses the context only as -primary data source for template variables for performance reasons. - -If you want to modify the context write a function that returns a variable -instead that one can assign to a variable by using set:: - - {% set comments = get_latest_comments() %} - -My tracebacks look weird. What's happening? --------------------------------------------- - -If the debugsupport module is not compiled and you are using a Python -installation without ctypes (Python 2.4 without ctypes, Jython or Google's -AppEngine) Jinja2 is unable to provide correct debugging information and -the traceback may be incomplete. There is currently no good workaround -for Jython or the AppEngine as ctypes is unavailable there and it's not -possible to use the debugsupport extension. - -If you are working in the Google AppEngine development server you can -whitelist the ctypes module to restore the tracebacks. This however won't -work in production environments:: - - import os - if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'): - from google.appengine.tools.dev_appserver import HardenedModulesHook - HardenedModulesHook._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt'] - -Credit for this snippet goes to `Thomas Johansson -`_ - -Why is there no Python 2.3/2.4/2.5/3.1/3.2 support? ---------------------------------------------------- - -Python 2.3 is missing a lot of features that are used heavily in Jinja2. This -decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes -harder to maintain the code for older Python versions. If you really need -Python 2.3 support you either have to use `Jinja 1`_ or other templating -engines that still support 2.3. - -Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting -Python 2 and 3 by the same sourcecode (without using 2to3). It was required to -drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode -literals in a way compatible to each other version. If you really need support -for older Python 2 (or 3) versions, you can just use Jinja2 2.6. - -My Macros are overridden by something -------------------------------------- - -In some situations the Jinja scoping appears arbitrary: - -layout.tmpl: - -.. sourcecode:: jinja - - {% macro foo() %}LAYOUT{% endmacro %} - {% block body %}{% endblock %} - -child.tmpl: - -.. sourcecode:: jinja - - {% extends 'layout.tmpl' %} - {% macro foo() %}CHILD{% endmacro %} - {% block body %}{{ foo() }}{% endblock %} - -This will print ``LAYOUT`` in Jinja2. This is a side effect of having -the parent template evaluated after the child one. This allows child -templates passing information to the parent template. To avoid this -issue rename the macro or variable in the parent template to have an -uncommon prefix. - -.. _Jinja 1: http://jinja.pocoo.org/1/ diff --git a/deps/v8_inspector/third_party/jinja2/docs/index.rst b/deps/v8_inspector/third_party/jinja2/docs/index.rst deleted file mode 100644 index a08d6281df47eb..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/index.rst +++ /dev/null @@ -1,34 +0,0 @@ -Welcome to Jinja2 -================= - -Jinja2 is a modern and designer-friendly templating language for Python, -modelled after Django's templates. It is fast, widely used and secure -with the optional sandboxed template execution environment: - -.. sourcecode:: html+jinja - - {% block title %}{% endblock %} - - -**Features:** - -- sandboxed execution -- powerful automatic HTML escaping system for XSS prevention -- template inheritance -- compiles down to the optimal python code just in time -- optional ahead-of-time template compilation -- easy to debug. Line numbers of exceptions directly point to - the correct line in the template. -- configurable syntax - -.. include:: contents.rst.inc - -If you can't find the information you're looking for, have a look at the -index or try to find it using the search function: - -* :ref:`genindex` -* :ref:`search` diff --git a/deps/v8_inspector/third_party/jinja2/docs/integration.rst b/deps/v8_inspector/third_party/jinja2/docs/integration.rst deleted file mode 100644 index 92a3b14794b39f..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/integration.rst +++ /dev/null @@ -1,101 +0,0 @@ -Integration -=========== - -Jinja2 provides some code for integration into other tools such as frameworks, -the `Babel`_ library or your favourite editor for fancy code highlighting. -This is a brief description of whats included. - -Files to help integration are available -`here. `_ - -.. _babel-integration: - -Babel Integration ------------------ - -Jinja provides support for extracting gettext messages from templates via a -`Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel -support is implemented as part of the :ref:`i18n-extension` extension. - -Gettext messages extracted from both `trans` tags and code expressions. - -To extract gettext messages from templates, the project needs a Jinja2 section -in its Babel extraction method `mapping file`_: - -.. sourcecode:: ini - - [jinja2: **/templates/**.html] - encoding = utf-8 - -The syntax related options of the :class:`Environment` are also available as -configuration values in the mapping file. For example to tell the extraction -that templates use ``%`` as `line_statement_prefix` you can use this code: - -.. sourcecode:: ini - - [jinja2: **/templates/**.html] - encoding = utf-8 - line_statement_prefix = % - -:ref:`jinja-extensions` may also be defined by passing a comma separated list -of import paths as `extensions` value. The i18n extension is added -automatically. - -.. versionchanged:: 2.7 - - Until 2.7 template syntax errors were always ignored. This was done - since many people are dropping non template html files into the - templates folder and it would randomly fail. The assumption was that - testsuites will catch syntax errors in templates anyways. If you don't - want that behavior you can add ``silent=false`` to the settings and - exceptions are propagated. - -.. _mapping file: http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-method-mapping-and-configuration - -Pylons ------- - -With `Pylons`_ 0.9.7 onwards it's incredible easy to integrate Jinja into a -Pylons powered application. - -The template engine is configured in `config/environment.py`. The configuration -for Jinja2 looks something like that:: - - from jinja2 import Environment, PackageLoader - config['pylons.app_globals'].jinja_env = Environment( - loader=PackageLoader('yourapplication', 'templates') - ) - -After that you can render Jinja templates by using the `render_jinja` function -from the `pylons.templating` module. - -Additionally it's a good idea to set the Pylons' `c` object into strict mode. -Per default any attribute to not existing attributes on the `c` object return -an empty string and not an undefined object. To change this just use this -snippet and add it into your `config/environment.py`:: - - config['pylons.strict_c'] = True - -.. _Pylons: http://www.pylonshq.com/ - -TextMate --------- - -There is a bundle for TextMate that supports syntax highlighting for Jinja1 and Jinja2 for text based -templates as well as HTML. It also contains a few often used snippets. - -.. _TextMate Bundle: https://github.com/mitsuhiko/jinja2-tmbundle - -Vim ---- - -A syntax plugin for `Vim`_ exists in the Vim-scripts directory as well as the -`ext` folder at the root of the Jinja2 project. `The script -`_ supports Jinja1 and -Jinja2. Once installed two file types are available `jinja` and `htmljinja`. -The first one for text based templates, the latter for HTML templates. - -Copy the files into your `syntax` folder. - -.. _Babel: http://babel.edgewall.org/ -.. _Vim: http://www.vim.org/ diff --git a/deps/v8_inspector/third_party/jinja2/docs/intro.rst b/deps/v8_inspector/third_party/jinja2/docs/intro.rst deleted file mode 100644 index 99c3582728f773..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/intro.rst +++ /dev/null @@ -1,123 +0,0 @@ -Introduction -============ - -This is the documentation for the Jinja2 general purpose templating language. -Jinja2 is a library for Python that is designed to be flexible, fast and secure. - -If you have any exposure to other text-based template languages, such as Smarty or -Django, you should feel right at home with Jinja2. It's both designer and -developer friendly by sticking to Python's principles and adding functionality -useful for templating environments. - -Prerequisites -------------- - -Jinja2 works with Python 2.6.x, 2.7.x and >= 3.3. If you are using Python -3.2 you can use an older release of Jinja2 (2.6) as support for Python 3.2 -was dropped in Jinja2 version 2.7. - -If you wish to use the :class:`~jinja2.PackageLoader` class, you will also -need `setuptools`_ or `distribute`_ installed at runtime. - -Installation ------------- - -You have multiple ways to install Jinja2. If you are unsure what to do, go -with the Python egg or tarball. - -As a Python egg (via `easy_install`) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can install the most recent Jinja2 version using `easy_install`_ or `pip`_:: - - easy_install Jinja2 - pip install Jinja2 - -This will install a Jinja2 egg in your Python installation's site-packages -directory. - -(If you are installing from the Windows command line omit the `sudo` and make -sure to run the command as user with administrator rights) - -From the tarball release -~~~~~~~~~~~~~~~~~~~~~~~~~ - -1. Download the most recent tarball from the `download page`_ -2. Unpack the tarball -3. ``sudo python setup.py install`` - -Note that you either have to have `setuptools` or `distribute` installed; -the latter is preferred. - -This will install Jinja2 into your Python installation's site-packages directory. - -Installing the development version -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -1. Install `git`_ -2. ``git clone git://github.com/mitsuhiko/jinja2.git`` -3. ``cd jinja2`` -4. ``ln -s jinja2 /usr/lib/python2.X/site-packages`` - -As an alternative to steps 4 you can also do ``python setup.py develop`` -which will install the package via `distribute` in development mode. This also -has the advantage that the C extensions are compiled. - -.. _download page: http://pypi.python.org/pypi/Jinja2 -.. _distribute: http://pypi.python.org/pypi/distribute -.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools -.. _easy_install: http://peak.telecommunity.com/DevCenter/EasyInstall -.. _pip: http://pypi.python.org/pypi/pip -.. _git: http://git-scm.org/ - - -MarkupSafe Dependency -~~~~~~~~~~~~~~~~~~~~~ - -As of version 2.7 Jinja2 depends on the `MarkupSafe`_ module. If you -install Jinja2 via `pip` or `easy_install` it will be installed -automatically for you. - -.. _MarkupSafe: http://pypi.python.org/pypi/MarkupSafe - -Basic API Usage ---------------- - -This section gives you a brief introduction to the Python API for Jinja2 -templates. - -The most basic way to create a template and render it is through -:class:`~jinja2.Template`. This however is not the recommended way to -work with it if your templates are not loaded from strings but the file -system or another data source: - ->>> from jinja2 import Template ->>> template = Template('Hello {{ name }}!') ->>> template.render(name='John Doe') -u'Hello John Doe!' - -By creating an instance of :class:`~jinja2.Template` you get back a new template -object that provides a method called :meth:`~jinja2.Template.render` which when -called with a dict or keyword arguments expands the template. The dict -or keywords arguments passed to the template are the so-called "context" -of the template. - -What you can see here is that Jinja2 is using unicode internally and the -return value is an unicode string. So make sure that your application is -indeed using unicode internally. - - -Experimental Python 3 Support ------------------------------ - -Jinja 2.7 brings experimental support for Python >=3.3. It means that all -unittests pass on the new version, but there might still be small bugs in -there and behavior might be inconsistent. If you notice any bugs, please -provide feedback in the `Jinja bug tracker`_. - -Also please keep in mind that the documentation is written with Python 2 -in mind, so you will have to adapt the shown code examples to Python 3 syntax -for yourself. - - -.. _Jinja bug tracker: http://github.com/mitsuhiko/jinja2/issues diff --git a/deps/v8_inspector/third_party/jinja2/docs/jinjaext.py b/deps/v8_inspector/third_party/jinja2/docs/jinjaext.py deleted file mode 100644 index cdacba9d9cf62f..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/jinjaext.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Jinja Documentation Extensions - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Support for automatically documenting filters and tests. - - :copyright: Copyright 2008 by Armin Ronacher. - :license: BSD. -""" -import collections -import os -import re -import inspect -import jinja2 -from itertools import islice -from types import BuiltinFunctionType -from docutils import nodes -from docutils.statemachine import ViewList -from sphinx.ext.autodoc import prepare_docstring -from sphinx.application import TemplateBridge -from pygments.style import Style -from pygments.token import Keyword, Name, Comment, String, Error, \ - Number, Operator, Generic -from jinja2 import Environment, FileSystemLoader - - -def parse_rst(state, content_offset, doc): - node = nodes.section() - # hack around title style bookkeeping - surrounding_title_styles = state.memo.title_styles - surrounding_section_level = state.memo.section_level - state.memo.title_styles = [] - state.memo.section_level = 0 - state.nested_parse(doc, content_offset, node, match_titles=1) - state.memo.title_styles = surrounding_title_styles - state.memo.section_level = surrounding_section_level - return node.children - - -class JinjaStyle(Style): - title = 'Jinja Style' - default_style = "" - styles = { - Comment: 'italic #aaaaaa', - Comment.Preproc: 'noitalic #B11414', - Comment.Special: 'italic #505050', - - Keyword: 'bold #B80000', - Keyword.Type: '#808080', - - Operator.Word: 'bold #B80000', - - Name.Builtin: '#333333', - Name.Function: '#333333', - Name.Class: 'bold #333333', - Name.Namespace: 'bold #333333', - Name.Entity: 'bold #363636', - Name.Attribute: '#686868', - Name.Tag: 'bold #686868', - Name.Decorator: '#686868', - - String: '#AA891C', - Number: '#444444', - - Generic.Heading: 'bold #000080', - Generic.Subheading: 'bold #800080', - Generic.Deleted: '#aa0000', - Generic.Inserted: '#00aa00', - Generic.Error: '#aa0000', - Generic.Emph: 'italic', - Generic.Strong: 'bold', - Generic.Prompt: '#555555', - Generic.Output: '#888888', - Generic.Traceback: '#aa0000', - - Error: '#F00 bg:#FAA' - } - - -_sig_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*(\(.*?\))') - - -def format_function(name, aliases, func): - lines = inspect.getdoc(func).splitlines() - signature = '()' - if isinstance(func, BuiltinFunctionType): - match = _sig_re.match(lines[0]) - if match is not None: - del lines[:1 + bool(lines and not lines[0])] - signature = match.group(1) - else: - try: - argspec = inspect.getargspec(func) - if getattr(func, 'environmentfilter', False) or \ - getattr(func, 'contextfilter', False) or \ - getattr(func, 'evalcontextfilter', False): - del argspec[0][0] - signature = inspect.formatargspec(*argspec) - except: - pass - result = ['.. function:: %s%s' % (name, signature), ''] - result.extend(' ' + line for line in lines) - if aliases: - result.extend(('', ' :aliases: %s' % ', '.join( - '``%s``' % x for x in sorted(aliases)))) - return result - - -def dump_functions(mapping): - def directive(dirname, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - reverse_mapping = {} - for name, func in mapping.items(): - reverse_mapping.setdefault(func, []).append(name) - filters = [] - for func, names in reverse_mapping.items(): - aliases = sorted(names, key=lambda x: len(x)) - name = aliases.pop() - filters.append((name, aliases, func)) - filters.sort() - - result = ViewList() - for name, aliases, func in filters: - for item in format_function(name, aliases, func): - result.append(item, '') - - node = nodes.paragraph() - state.nested_parse(result, content_offset, node) - return node.children - return directive - - -from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS -jinja_filters = dump_functions(DEFAULT_FILTERS) -jinja_tests = dump_functions(DEFAULT_TESTS) - - -def jinja_nodes(dirname, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - from jinja2.nodes import Node - doc = ViewList() - def walk(node, indent): - p = ' ' * indent - sig = ', '.join(node.fields) - doc.append(p + '.. autoclass:: %s(%s)' % (node.__name__, sig), '') - if node.abstract: - members = [] - for key, name in node.__dict__.items(): - if not key.startswith('_') and \ - not hasattr(node.__base__, key) and isinstance(name, collections.Callable): - members.append(key) - if members: - members.sort() - doc.append('%s :members: %s' % (p, ', '.join(members)), '') - if node.__base__ != object: - doc.append('', '') - doc.append('%s :Node type: :class:`%s`' % - (p, node.__base__.__name__), '') - doc.append('', '') - children = node.__subclasses__() - children.sort(key=lambda x: x.__name__.lower()) - for child in children: - walk(child, indent) - walk(Node, 0) - return parse_rst(state, content_offset, doc) - - -def inject_toc(app, doctree, docname): - titleiter = iter(doctree.traverse(nodes.title)) - try: - # skip first title, we are not interested in that one - next(titleiter) - title = next(titleiter) - # and check if there is at least another title - next(titleiter) - except StopIteration: - return - tocnode = nodes.section('') - tocnode['classes'].append('toc') - toctitle = nodes.section('') - toctitle['classes'].append('toctitle') - toctitle.append(nodes.title(text='Table Of Contents')) - tocnode.append(toctitle) - tocnode += doctree.document.settings.env.get_toc_for(docname)[0][1] - title.parent.insert(title.parent.children.index(title), tocnode) - - -def setup(app): - app.add_directive('jinjafilters', jinja_filters, 0, (0, 0, 0)) - app.add_directive('jinjatests', jinja_tests, 0, (0, 0, 0)) - app.add_directive('jinjanodes', jinja_nodes, 0, (0, 0, 0)) - # uncomment for inline toc. links are broken unfortunately - ##app.connect('doctree-resolved', inject_toc) diff --git a/deps/v8_inspector/third_party/jinja2/docs/jinjastyle.sty b/deps/v8_inspector/third_party/jinja2/docs/jinjastyle.sty deleted file mode 100644 index da811ce376bd12..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/jinjastyle.sty +++ /dev/null @@ -1,119 +0,0 @@ -\definecolor{TitleColor}{rgb}{0,0,0} -\definecolor{InnerLinkColor}{rgb}{0,0,0} -\definecolor{OuterLinkColor}{rgb}{0.8,0,0} - -\renewcommand{\maketitle}{% - \begin{titlepage}% - \let\footnotesize\small - \let\footnoterule\relax - \ifsphinxpdfoutput - \begingroup - % This \def is required to deal with multi-line authors; it - % changes \\ to ', ' (comma-space), making it pass muster for - % generating document info in the PDF file. - \def\\{, } - \pdfinfo{ - /Author (\@author) - /Title (\@title) - } - \endgroup - \fi - \begin{flushright}% - %\sphinxlogo% - {\center - \vspace*{3cm} - \includegraphics{logo.pdf} - \vspace{3cm} - \par - {\rm\Huge \@title \par}% - {\em\LARGE \py@release\releaseinfo \par} - {\large - \@date \par - \py@authoraddress \par - }}% - \end{flushright}%\par - \@thanks - \end{titlepage}% - \cleardoublepage% - \setcounter{footnote}{0}% - \let\thanks\relax\let\maketitle\relax - %\gdef\@thanks{}\gdef\@author{}\gdef\@title{} -} - -\fancypagestyle{normal}{ - \fancyhf{} - \fancyfoot[LE,RO]{{\thepage}} - \fancyfoot[LO]{{\nouppercase{\rightmark}}} - \fancyfoot[RE]{{\nouppercase{\leftmark}}} - \fancyhead[LE,RO]{{ \@title, \py@release}} - \renewcommand{\headrulewidth}{0.4pt} - \renewcommand{\footrulewidth}{0.4pt} -} - -\fancypagestyle{plain}{ - \fancyhf{} - \fancyfoot[LE,RO]{{\thepage}} - \renewcommand{\headrulewidth}{0pt} - \renewcommand{\footrulewidth}{0.4pt} -} - -\titleformat{\section}{\Large}% - {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\subsection}{\large}% - {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\subsubsection}{}% - {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor} -\titleformat{\paragraph}{\large}% - {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor} - -\ChNameVar{\raggedleft\normalsize} -\ChNumVar{\raggedleft \bfseries\Large} -\ChTitleVar{\raggedleft \rm\Huge} - -\renewcommand\thepart{\@Roman\c@part} -\renewcommand\part{% - \pagestyle{plain} - \if@noskipsec \leavevmode \fi - \cleardoublepage - \vspace*{6cm}% - \@afterindentfalse - \secdef\@part\@spart} - -\def\@part[#1]#2{% - \ifnum \c@secnumdepth >\m@ne - \refstepcounter{part}% - \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}% - \else - \addcontentsline{toc}{part}{#1}% - \fi - {\parindent \z@ %\center - \interlinepenalty \@M - \normalfont - \ifnum \c@secnumdepth >\m@ne - \rm\Large \partname~\thepart - \par\nobreak - \fi - \MakeUppercase{\rm\Huge #2}% - \markboth{}{}\par}% - \nobreak - \vskip 8ex - \@afterheading} -\def\@spart#1{% - {\parindent \z@ %\center - \interlinepenalty \@M - \normalfont - \huge \bfseries #1\par}% - \nobreak - \vskip 3ex - \@afterheading} - -% use inconsolata font -\usepackage{inconsolata} - -% fix single quotes, for inconsolata. (does not work) -%%\usepackage{textcomp} -%%\begingroup -%% \catcode`'=\active -%% \g@addto@macro\@noligs{\let'\textsinglequote} -%% \endgroup -%%\endinput diff --git a/deps/v8_inspector/third_party/jinja2/docs/latexindex.rst b/deps/v8_inspector/third_party/jinja2/docs/latexindex.rst deleted file mode 100644 index 300e60d10f2a76..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/latexindex.rst +++ /dev/null @@ -1,6 +0,0 @@ -:orphan: - -Jinja2 Documentation -==================== - -.. include:: contents.rst.inc diff --git a/deps/v8_inspector/third_party/jinja2/docs/logo.pdf b/deps/v8_inspector/third_party/jinja2/docs/logo.pdf deleted file mode 100644 index 3e8a9cf480ccbe..00000000000000 Binary files a/deps/v8_inspector/third_party/jinja2/docs/logo.pdf and /dev/null differ diff --git a/deps/v8_inspector/third_party/jinja2/docs/sandbox.rst b/deps/v8_inspector/third_party/jinja2/docs/sandbox.rst deleted file mode 100644 index 71ccc0d6deff3b..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/sandbox.rst +++ /dev/null @@ -1,94 +0,0 @@ -Sandbox -======= - -The Jinja2 sandbox can be used to evaluate untrusted code. Access to unsafe -attributes and methods is prohibited. - -Assuming `env` is a :class:`SandboxedEnvironment` in the default configuration -the following piece of code shows how it works: - ->>> env.from_string("{{ func.func_code }}").render(func=lambda:None) -u'' ->>> env.from_string("{{ func.func_code.do_something }}").render(func=lambda:None) -Traceback (most recent call last): - ... -SecurityError: access to attribute 'func_code' of 'function' object is unsafe. - -API ---- - -.. module:: jinja2.sandbox - -.. autoclass:: SandboxedEnvironment([options]) - :members: is_safe_attribute, is_safe_callable, default_binop_table, - default_unop_table, intercepted_binops, intercepted_unops, - call_binop, call_unop - -.. autoclass:: ImmutableSandboxedEnvironment([options]) - -.. autoexception:: SecurityError - -.. autofunction:: unsafe - -.. autofunction:: is_internal_attribute - -.. autofunction:: modifies_known_mutable - -.. admonition:: Note - - The Jinja2 sandbox alone is no solution for perfect security. Especially - for web applications you have to keep in mind that users may create - templates with arbitrary HTML in so it's crucial to ensure that (if you - are running multiple users on the same server) they can't harm each other - via JavaScript insertions and much more. - - Also the sandbox is only as good as the configuration. We strongly - recommend only passing non-shared resources to the template and use - some sort of whitelisting for attributes. - - Also keep in mind that templates may raise runtime or compile time errors, - so make sure to catch them. - -Operator Intercepting ---------------------- - -.. versionadded:: 2.6 - -For maximum performance Jinja2 will let operators call directly the type -specific callback methods. This means that it's not possible to have this -intercepted by overriding :meth:`Environment.call`. Furthermore a -conversion from operator to special method is not always directly possible -due to how operators work. For instance for divisions more than one -special method exist. - -With Jinja 2.6 there is now support for explicit operator intercepting. -This can be used to customize specific operators as necessary. In order -to intercept an operator one has to override the -:attr:`SandboxedEnvironment.intercepted_binops` attribute. Once the -operator that needs to be intercepted is added to that set Jinja2 will -generate bytecode that calls the :meth:`SandboxedEnvironment.call_binop` -function. For unary operators the `unary` attributes and methods have to -be used instead. - -The default implementation of :attr:`SandboxedEnvironment.call_binop` -will use the :attr:`SandboxedEnvironment.binop_table` to translate -operator symbols into callbacks performing the default operator behavior. - -This example shows how the power (``**``) operator can be disabled in -Jinja2:: - - from jinja2.sandbox import SandboxedEnvironment - - - class MyEnvironment(SandboxedEnvironment): - intercepted_binops = frozenset(['**']) - - def call_binop(self, context, operator, left, right): - if operator == '**': - return self.undefined('the power operator is unavailable') - return SandboxedEnvironment.call_binop(self, context, - operator, left, right) - -Make sure to always call into the super method, even if you are not -intercepting the call. Jinja2 might internally call the method to -evaluate expressions. diff --git a/deps/v8_inspector/third_party/jinja2/docs/switching.rst b/deps/v8_inspector/third_party/jinja2/docs/switching.rst deleted file mode 100644 index 01a7d0d787bec2..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/switching.rst +++ /dev/null @@ -1,226 +0,0 @@ -Switching from other Template Engines -===================================== - -.. highlight:: html+jinja - -If you have used a different template engine in the past and want to switch -to Jinja2 here is a small guide that shows the basic syntactic and semantic -changes between some common, similar text template engines for Python. - -Jinja1 ------- - -Jinja2 is mostly compatible with Jinja1 in terms of API usage and template -syntax. The differences between Jinja1 and 2 are explained in the following -list. - -API -~~~ - -Loaders - Jinja2 uses a different loader API. Because the internal representation - of templates changed there is no longer support for external caching - systems such as memcached. The memory consumed by templates is comparable - with regular Python modules now and external caching doesn't give any - advantage. If you have used a custom loader in the past have a look at - the new :ref:`loader API `. - -Loading templates from strings - In the past it was possible to generate templates from a string with the - default environment configuration by using `jinja.from_string`. Jinja2 - provides a :class:`Template` class that can be used to do the same, but - with optional additional configuration. - -Automatic unicode conversion - Jinja1 performed automatic conversion of bytestrings in a given encoding - into unicode objects. This conversion is no longer implemented as it - was inconsistent as most libraries are using the regular Python ASCII - bytestring to Unicode conversion. An application powered by Jinja2 - *has to* use unicode internally everywhere or make sure that Jinja2 only - gets unicode strings passed. - -i18n - Jinja1 used custom translators for internationalization. i18n is now - available as Jinja2 extension and uses a simpler, more gettext friendly - interface and has support for babel. For more details see - :ref:`i18n-extension`. - -Internal methods - Jinja1 exposed a few internal methods on the environment object such - as `call_function`, `get_attribute` and others. While they were marked - as being an internal method it was possible to override them. Jinja2 - doesn't have equivalent methods. - -Sandbox - Jinja1 was running sandbox mode by default. Few applications actually - used that feature so it became optional in Jinja2. For more details - about the sandboxed execution see :class:`SandboxedEnvironment`. - -Context - Jinja1 had a stacked context as storage for variables passed to the - environment. In Jinja2 a similar object exists but it doesn't allow - modifications nor is it a singleton. As inheritance is dynamic now - multiple context objects may exist during template evaluation. - -Filters and Tests - Filters and tests are regular functions now. It's no longer necessary - and allowed to use factory functions. - - -Templates -~~~~~~~~~ - -Jinja2 has mostly the same syntax as Jinja1. What's different is that -macros require parentheses around the argument list now. - -Additionally Jinja2 allows dynamic inheritance now and dynamic includes. -The old helper function `rendertemplate` is gone now, `include` can be used -instead. Includes no longer import macros and variable assignments, for -that the new `import` tag is used. This concept is explained in the -:ref:`import` documentation. - -Another small change happened in the `for`-tag. The special loop variable -doesn't have a `parent` attribute, instead you have to alias the loop -yourself. See :ref:`accessing-the-parent-loop` for more details. - - -Django ------- - -If you have previously worked with Django templates, you should find -Jinja2 very familiar. In fact, most of the syntax elements look and -work the same. - -However, Jinja2 provides some more syntax elements covered in the -documentation and some work a bit different. - -This section covers the template changes. As the API is fundamentally -different we won't cover it here. - -Method Calls -~~~~~~~~~~~~ - -In Django method calls work implicitly, while Jinja requires the explicit -Python syntax. Thus this Django code:: - - {% for page in user.get_created_pages %} - ... - {% endfor %} - -...looks like this in Jinja:: - - {% for page in user.get_created_pages() %} - ... - {% endfor %} - -This allows you to pass variables to the method, which is not possible in -Django. This syntax is also used for macros. - -Filter Arguments -~~~~~~~~~~~~~~~~ - -Jinja2 provides more than one argument for filters. Also the syntax for -argument passing is different. A template that looks like this in Django:: - - {{ items|join:", " }} - -looks like this in Jinja2:: - - {{ items|join(', ') }} - -It is a bit more verbose, but it allows different types of arguments - -including variables - and more than one of them. - -Tests -~~~~~ - -In addition to filters there also are tests you can perform using the is -operator. Here are some examples:: - - {% if user.user_id is odd %} - {{ user.username|e }} is odd - {% else %} - hmm. {{ user.username|e }} looks pretty normal - {% endif %} - -Loops -~~~~~ - -For loops work very similarly to Django, but notably the Jinja2 special -variable for the loop context is called `loop`, not `forloop` as in Django. - -In addition, the Django `empty` argument is called `else` in Jinja2. For -example, the Django template:: - - {% for item in items %} - {{ item }} - {% empty %} - No items! - {% endfor %} - -...looks like this in Jinja2:: - - {% for item in items %} - {{ item }} - {% else %} - No items! - {% endfor %} - -Cycle -~~~~~ - -The ``{% cycle %}`` tag does not exist in Jinja2; however, you can achieve the -same output by using the `cycle` method on the loop context special variable. - -The following Django template:: - - {% for user in users %} -
  • {{ user }}
  • - {% endfor %} - -...looks like this in Jinja2:: - - {% for user in users %} -
  • {{ user }}
  • - {% endfor %} - -There is no equivalent of ``{% cycle ... as variable %}``. - - -Mako ----- - -.. highlight:: html+mako - -If you have used Mako so far and want to switch to Jinja2 you can configure -Jinja2 to look more like Mako: - -.. sourcecode:: python - - env = Environment('<%', '%>', '${', '}', '<%doc>', '', '%', '##') - -With an environment configured like that, Jinja2 should be able to interpret -a small subset of Mako templates. Jinja2 does not support embedded Python -code, so you would have to move that out of the template. The syntax for defs -(which are called macros in Jinja2) and template inheritance is different too. -The following Mako template:: - - <%inherit file="layout.html" /> - <%def name="title()">Page Title -
      - % for item in list: -
    • ${item}
    • - % endfor -
    - -Looks like this in Jinja2 with the above configuration:: - - <% extends "layout.html" %> - <% block title %>Page Title<% endblock %> - <% block body %> -
      - % for item in list: -
    • ${item}
    • - % endfor -
    - <% endblock %> diff --git a/deps/v8_inspector/third_party/jinja2/docs/templates.rst b/deps/v8_inspector/third_party/jinja2/docs/templates.rst deleted file mode 100644 index d9102ecc1b636b..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/templates.rst +++ /dev/null @@ -1,1509 +0,0 @@ -Template Designer Documentation -=============================== - -.. highlight:: html+jinja - -This document describes the syntax and semantics of the template engine and -will be most useful as reference to those creating Jinja templates. As the -template engine is very flexible, the configuration from the application can -be slightly different from the code presented here in terms of delimiters and -behavior of undefined values. - - -Synopsis --------- - -A Jinja template is simply a text file. Jinja can generate any text-based -format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a -specific extension: ``.html``, ``.xml``, or any other extension is just fine. - -A template contains **variables** and/or **expressions**, which get replaced -with values when a template is *rendered*; and **tags**, which control the -logic of the template. The template syntax is heavily inspired by Django and -Python. - -Below is a minimal template that illustrates a few basics using the default -Jinja configuration. We will cover the details later in this document:: - - - - - My Webpage - - - - -

    My Webpage

    - {{ a_variable }} - - {# a comment #} - - - -The following example shows the default configuration settings. An application -developer can change the syntax configuration from ``{% foo %}`` to ``<% foo -%>``, or something similar. - -There are a few kinds of delimiters. The default Jinja delimiters are -configured as follows: - -* ``{% ... %}`` for :ref:`Statements ` -* ``{{ ... }}`` for :ref:`Expressions` to print to the template output -* ``{# ... #}`` for :ref:`Comments` not included in the template output -* ``# ... ##`` for :ref:`Line Statements ` - - -.. _variables: - -Variables ---------- - -Template variables are defined by the context dictionary passed to the -template. - -You can mess around with the variables in templates provided they are passed in -by the application. Variables may have attributes or elements on them you can -access too. What attributes a variable has depends heavily on the application -providing that variable. - -You can use a dot (``.``) to access attributes of a variable in addition -to the standard Python ``__getitem__`` "subscript" syntax (``[]``). - -The following lines do the same thing:: - - {{ foo.bar }} - {{ foo['bar'] }} - -It's important to know that the outer double-curly braces are *not* part of the -variable, but the print statement. If you access variables inside tags don't -put the braces around them. - -If a variable or attribute does not exist, you will get back an undefined -value. What you can do with that kind of value depends on the application -configuration: the default behavior is to evaluate to an empty string if -printed or iterated over, and to fail for every other operation. - -.. _notes-on-subscriptions: - -.. admonition:: Implementation - - For the sake of convenience, ``foo.bar`` in Jinja2 does the following - things on the Python layer: - - - check for an attribute called `bar` on `foo` - (``getattr(foo, 'bar')``) - - if there is not, check for an item ``'bar'`` in `foo` - (``foo.__getitem__('bar')``) - - if there is not, return an undefined object. - - ``foo['bar']`` works mostly the same with a small difference in sequence: - - - check for an item ``'bar'`` in `foo`. - (``foo.__getitem__('bar')``) - - if there is not, check for an attribute called `bar` on `foo`. - (``getattr(foo, 'bar')``) - - if there is not, return an undefined object. - - This is important if an object has an item and attribute with the same - name. Additionally, the :func:`attr` filter only looks up attributes. - -.. _filters: - -Filters -------- - -Variables can be modified by **filters**. Filters are separated from the -variable by a pipe symbol (``|``) and may have optional arguments in -parentheses. Multiple filters can be chained. The output of one filter is -applied to the next. - -For example, ``{{ name|striptags|title }}`` will remove all HTML Tags from -variable `name` and title-case the output (``title(striptags(name))``). - -Filters that accept arguments have parentheses around the arguments, just like -a function call. For example: ``{{ listx|join(', ') }}`` will join a list with -commas (``str.join(', ', listx)``). - -The :ref:`builtin-filters` below describes all the builtin filters. - -.. _tests: - -Tests ------ - -Beside filters, there are also so-called "tests" available. Tests can be used -to test a variable against a common expression. To test a variable or -expression, you add `is` plus the name of the test after the variable. For -example, to find out if a variable is defined, you can do ``name is defined``, -which will then return true or false depending on whether `name` is defined -in the current template context. - -Tests can accept arguments, too. If the test only takes one argument, you can -leave out the parentheses. For example, the following two -expressions do the same thing:: - - {% if loop.index is divisibleby 3 %} - {% if loop.index is divisibleby(3) %} - -The :ref:`builtin-tests` below describes all the builtin tests. - - -.. _comments: - -Comments --------- - -To comment-out part of a line in a template, use the comment syntax which is -by default set to ``{# ... #}``. This is useful to comment out parts of the -template for debugging or to add information for other template designers or -yourself:: - - {# note: commented-out template because we no longer use this - {% for user in users %} - ... - {% endfor %} - #} - - -Whitespace Control ------------------- - -In the default configuration: - -* a single trailing newline is stripped if present -* other whitespace (spaces, tabs, newlines etc.) is returned unchanged - -If an application configures Jinja to `trim_blocks`, the first newline after a -template tag is removed automatically (like in PHP). The `lstrip_blocks` -option can also be set to strip tabs and spaces from the beginning of a -line to the start of a block. (Nothing will be stripped if there are -other characters before the start of the block.) - -With both `trim_blocks` and `lstrip_blocks` enabled, you can put block tags -on their own lines, and the entire block line will be removed when -rendered, preserving the whitespace of the contents. For example, -without the `trim_blocks` and `lstrip_blocks` options, this template:: - -
    - {% if True %} - yay - {% endif %} -
    - -gets rendered with blank lines inside the div:: - -
    - - yay - -
    - -But with both `trim_blocks` and `lstrip_blocks` enabled, the template block -lines are removed and other whitespace is preserved:: - -
    - yay -
    - -You can manually disable the `lstrip_blocks` behavior by putting a -plus sign (``+``) at the start of a block:: - -
    - {%+ if something %}yay{% endif %} -
    - -You can also strip whitespace in templates by hand. If you add a minus -sign (``-``) to the start or end of a block (e.g. a :ref:`for-loop` tag), a -comment, or a variable expression, the whitespaces before or after -that block will be removed:: - - {% for item in seq -%} - {{ item }} - {%- endfor %} - -This will yield all elements without whitespace between them. If `seq` was -a list of numbers from ``1`` to ``9``, the output would be ``123456789``. - -If :ref:`line-statements` are enabled, they strip leading whitespace -automatically up to the beginning of the line. - -By default, Jinja2 also removes trailing newlines. To keep single -trailing newlines, configure Jinja to `keep_trailing_newline`. - -.. admonition:: Note - - You must not add whitespace between the tag and the minus sign. - - **valid**:: - - {%- if foo -%}...{% endif %} - - **invalid**:: - - {% - if foo - %}...{% endif %} - - -Escaping --------- - -It is sometimes desirable -- even necessary -- to have Jinja ignore parts -it would otherwise handle as variables or blocks. For example, if, with -the default syntax, you want to use ``{{`` as a raw string in a template and -not start a variable, you have to use a trick. - -The easiest way to output a literal variable delimiter (``{{``) is by using a -variable expression:: - - {{ '{{' }} - -For bigger sections, it makes sense to mark a block `raw`. For example, to -include example Jinja syntax in a template, you can use this snippet:: - - {% raw %} -
      - {% for item in seq %} -
    • {{ item }}
    • - {% endfor %} -
    - {% endraw %} - - -.. _line-statements: - -Line Statements ---------------- - -If line statements are enabled by the application, it's possible to mark a -line as a statement. For example, if the line statement prefix is configured -to ``#``, the following two examples are equivalent:: - -
      - # for item in seq -
    • {{ item }}
    • - # endfor -
    - -
      - {% for item in seq %} -
    • {{ item }}
    • - {% endfor %} -
    - -The line statement prefix can appear anywhere on the line as long as no text -precedes it. For better readability, statements that start a block (such as -`for`, `if`, `elif` etc.) may end with a colon:: - - # for item in seq: - ... - # endfor - - -.. admonition:: Note - - Line statements can span multiple lines if there are open parentheses, - braces or brackets:: - -
      - # for href, caption in [('index.html', 'Index'), - ('about.html', 'About')]: -
    • {{ caption }}
    • - # endfor -
    - -Since Jinja 2.2, line-based comments are available as well. For example, if -the line-comment prefix is configured to be ``##``, everything from ``##`` to -the end of the line is ignored (excluding the newline sign):: - - # for item in seq: -
  • {{ item }}
  • ## this comment is ignored - # endfor - - -.. _template-inheritance: - -Template Inheritance --------------------- - -The most powerful part of Jinja is template inheritance. Template inheritance -allows you to build a base "skeleton" template that contains all the common -elements of your site and defines **blocks** that child templates can override. - -Sounds complicated but is very basic. It's easiest to understand it by starting -with an example. - - -Base Template -~~~~~~~~~~~~~ - -This template, which we'll call ``base.html``, defines a simple HTML skeleton -document that you might use for a simple two-column page. It's the job of -"child" templates to fill the empty blocks with content:: - - - - - {% block head %} - - {% block title %}{% endblock %} - My Webpage - {% endblock %} - - -
    {% block content %}{% endblock %}
    - - - - -In this example, the ``{% block %}`` tags define four blocks that child templates -can fill in. All the `block` tag does is tell the template engine that a -child template may override those placeholders in the template. - -Child Template -~~~~~~~~~~~~~~ - -A child template might look like this:: - - {% extends "base.html" %} - {% block title %}Index{% endblock %} - {% block head %} - {{ super() }} - - {% endblock %} - {% block content %} -

    Index

    -

    - Welcome to my awesome homepage. -

    - {% endblock %} - -The ``{% extends %}`` tag is the key here. It tells the template engine that -this template "extends" another template. When the template system evaluates -this template, it first locates the parent. The extends tag should be the -first tag in the template. Everything before it is printed out normally and -may cause confusion. For details about this behavior and how to take -advantage of it, see :ref:`null-master-fallback`. - -The filename of the template depends on the template loader. For example, the -:class:`FileSystemLoader` allows you to access other templates by giving the -filename. You can access templates in subdirectories with a slash:: - - {% extends "layout/default.html" %} - -But this behavior can depend on the application embedding Jinja. Note that -since the child template doesn't define the ``footer`` block, the value from -the parent template is used instead. - -You can't define multiple ``{% block %}`` tags with the same name in the -same template. This limitation exists because a block tag works in "both" -directions. That is, a block tag doesn't just provide a placeholder to fill -- it also defines the content that fills the placeholder in the *parent*. -If there were two similarly-named ``{% block %}`` tags in a template, -that template's parent wouldn't know which one of the blocks' content to use. - -If you want to print a block multiple times, you can, however, use the special -`self` variable and call the block with that name:: - - {% block title %}{% endblock %} -

    {{ self.title() }}

    - {% block body %}{% endblock %} - - -Super Blocks -~~~~~~~~~~~~ - -It's possible to render the contents of the parent block by calling `super`. -This gives back the results of the parent block:: - - {% block sidebar %} -

    Table Of Contents

    - ... - {{ super() }} - {% endblock %} - - -Named Block End-Tags -~~~~~~~~~~~~~~~~~~~~ - -Jinja2 allows you to put the name of the block after the end tag for better -readability:: - - {% block sidebar %} - {% block inner_sidebar %} - ... - {% endblock inner_sidebar %} - {% endblock sidebar %} - -However, the name after the `endblock` word must match the block name. - - -Block Nesting and Scope -~~~~~~~~~~~~~~~~~~~~~~~ - -Blocks can be nested for more complex layouts. However, per default blocks -may not access variables from outer scopes:: - - {% for item in seq %} -
  • {% block loop_item %}{{ item }}{% endblock %}
  • - {% endfor %} - -This example would output empty ``
  • `` items because `item` is unavailable -inside the block. The reason for this is that if the block is replaced by -a child template, a variable would appear that was not defined in the block or -passed to the context. - -Starting with Jinja 2.2, you can explicitly specify that variables are -available in a block by setting the block to "scoped" by adding the `scoped` -modifier to a block declaration:: - - {% for item in seq %} -
  • {% block loop_item scoped %}{{ item }}{% endblock %}
  • - {% endfor %} - -When overriding a block, the `scoped` modifier does not have to be provided. - - -Template Objects -~~~~~~~~~~~~~~~~ - -.. versionchanged:: 2.4 - -If a template object was passed in the template context, you can -extend from that object as well. Assuming the calling code passes -a layout template as `layout_template` to the environment, this -code works:: - - {% extends layout_template %} - -Previously, the `layout_template` variable had to be a string with -the layout template's filename for this to work. - - -HTML Escaping -------------- - -When generating HTML from templates, there's always a risk that a variable will -include characters that affect the resulting HTML. There are two approaches: - -a. manually escaping each variable; or -b. automatically escaping everything by default. - -Jinja supports both. What is used depends on the application configuration. -The default configuration is no automatic escaping; for various reasons: - -- Escaping everything except for safe values will also mean that Jinja is - escaping variables known to not include HTML (e.g. numbers, booleans) - which can be a huge performance hit. - -- The information about the safety of a variable is very fragile. It could - happen that by coercing safe and unsafe values, the return value is - double-escaped HTML. - -Working with Manual Escaping -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If manual escaping is enabled, it's **your** responsibility to escape -variables if needed. What to escape? If you have a variable that *may* -include any of the following chars (``>``, ``<``, ``&``, or ``"``) you -**SHOULD** escape it unless the variable contains well-formed and trusted -HTML. Escaping works by piping the variable through the ``|e`` filter:: - - {{ user.username|e }} - -Working with Automatic Escaping -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When automatic escaping is enabled, everything is escaped by default except -for values explicitly marked as safe. Variables and expressions -can be marked as safe either in: - -a. the context dictionary by the application with `MarkupSafe.Markup`, or -b. the template, with the `|safe` filter - -The main problem with this approach is that Python itself doesn't have the -concept of tainted values; so whether a value is safe or unsafe can get lost. - -If a value is not marked safe, auto-escaping will take place; which means that -you could end up with double-escaped contents. Double-escaping is easy to -avoid, however: just rely on the tools Jinja2 provides and *don't use builtin -Python constructs such as str.format or the string modulo operator (%)*. - -Jinja2 functions (macros, `super`, `self.BLOCKNAME`) always return template -data that is marked as safe. - -String literals in templates with automatic escaping are considered unsafe -because native Python strings (``str``, ``unicode``, ``basestring``) are not -`MarkupSafe.Markup` strings with an ``__html__`` attribute. - -.. _list-of-control-structures: - -List of Control Structures --------------------------- - -A control structure refers to all those things that control the flow of a -program - conditionals (i.e. if/elif/else), for-loops, as well as things like -macros and blocks. With the default syntax, control structures appear inside -``{% ... %}`` blocks. - -.. _for-loop: - -For -~~~ - -Loop over each item in a sequence. For example, to display a list of users -provided in a variable called `users`:: - -

    Members

    -
      - {% for user in users %} -
    • {{ user.username|e }}
    • - {% endfor %} -
    - -As variables in templates retain their object properties, it is possible to -iterate over containers like `dict`:: - -
    - {% for key, value in my_dict.iteritems() %} -
    {{ key|e }}
    -
    {{ value|e }}
    - {% endfor %} -
    - -Note, however, that **Python dicts are not ordered**; so you might want to -either pass a sorted ``list`` of ``tuple`` s -- or a -``collections.OrderedDict`` -- to the template, or use the `dictsort` filter. - -Inside of a for-loop block, you can access some special variables: - -+-----------------------+---------------------------------------------------+ -| Variable | Description | -+=======================+===================================================+ -| `loop.index` | The current iteration of the loop. (1 indexed) | -+-----------------------+---------------------------------------------------+ -| `loop.index0` | The current iteration of the loop. (0 indexed) | -+-----------------------+---------------------------------------------------+ -| `loop.revindex` | The number of iterations from the end of the loop | -| | (1 indexed) | -+-----------------------+---------------------------------------------------+ -| `loop.revindex0` | The number of iterations from the end of the loop | -| | (0 indexed) | -+-----------------------+---------------------------------------------------+ -| `loop.first` | True if first iteration. | -+-----------------------+---------------------------------------------------+ -| `loop.last` | True if last iteration. | -+-----------------------+---------------------------------------------------+ -| `loop.length` | The number of items in the sequence. | -+-----------------------+---------------------------------------------------+ -| `loop.cycle` | A helper function to cycle between a list of | -| | sequences. See the explanation below. | -+-----------------------+---------------------------------------------------+ -| `loop.depth` | Indicates how deep in deep in a recursive loop | -| | the rendering currently is. Starts at level 1 | -+-----------------------+---------------------------------------------------+ -| `loop.depth0` | Indicates how deep in deep in a recursive loop | -| | the rendering currently is. Starts at level 0 | -+-----------------------+---------------------------------------------------+ - -Within a for-loop, it's possible to cycle among a list of strings/variables -each time through the loop by using the special `loop.cycle` helper:: - - {% for row in rows %} -
  • {{ row }}
  • - {% endfor %} - -Since Jinja 2.1, an extra `cycle` helper exists that allows loop-unbound -cycling. For more information, have a look at the :ref:`builtin-globals`. - -.. _loop-filtering: - -Unlike in Python, it's not possible to `break` or `continue` in a loop. You -can, however, filter the sequence during iteration, which allows you to skip -items. The following example skips all the users which are hidden:: - - {% for user in users if not user.hidden %} -
  • {{ user.username|e }}
  • - {% endfor %} - -The advantage is that the special `loop` variable will count correctly; thus -not counting the users not iterated over. - -If no iteration took place because the sequence was empty or the filtering -removed all the items from the sequence, you can render a default block -by using `else`:: - -
      - {% for user in users %} -
    • {{ user.username|e }}
    • - {% else %} -
    • no users found
    • - {% endfor %} -
    - -Note that, in Python, `else` blocks are executed whenever the corresponding -loop **did not** `break`. Since Jinja loops cannot `break` anyway, -a slightly different behavior of the `else` keyword was chosen. - -It is also possible to use loops recursively. This is useful if you are -dealing with recursive data such as sitemaps or RDFa. -To use loops recursively, you basically have to add the `recursive` modifier -to the loop definition and call the `loop` variable with the new iterable -where you want to recurse. - -The following example implements a sitemap with recursive loops:: - -
      - {%- for item in sitemap recursive %} -
    • {{ item.title }} - {%- if item.children -%} - - {%- endif %}
    • - {%- endfor %} -
    - -The `loop` variable always refers to the closest (innermost) loop. If we -have more than one level of loops, we can rebind the variable `loop` by -writing `{% set outer_loop = loop %}` after the loop that we want to -use recursively. Then, we can call it using `{{ outer_loop(...) }}` - -.. _if: - -If -~~ - -The `if` statement in Jinja is comparable with the Python if statement. -In the simplest form, you can use it to test if a variable is defined, not -empty or not false:: - - {% if users %} -
      - {% for user in users %} -
    • {{ user.username|e }}
    • - {% endfor %} -
    - {% endif %} - -For multiple branches, `elif` and `else` can be used like in Python. You can -use more complex :ref:`expressions` there, too:: - - {% if kenny.sick %} - Kenny is sick. - {% elif kenny.dead %} - You killed Kenny! You bastard!!! - {% else %} - Kenny looks okay --- so far - {% endif %} - -If can also be used as an :ref:`inline expression ` and for -:ref:`loop filtering `. - -.. _macros: - -Macros -~~~~~~ - -Macros are comparable with functions in regular programming languages. They -are useful to put often used idioms into reusable functions to not repeat -yourself ("DRY"). - -Here's a small example of a macro that renders a form element:: - - {% macro input(name, value='', type='text', size=20) -%} - - {%- endmacro %} - -The macro can then be called like a function in the namespace:: - -

    {{ input('username') }}

    -

    {{ input('password', type='password') }}

    - -If the macro was defined in a different template, you have to -:ref:`import ` it first. - -Inside macros, you have access to three special variables: - -`varargs` - If more positional arguments are passed to the macro than accepted by the - macro, they end up in the special `varargs` variable as a list of values. - -`kwargs` - Like `varargs` but for keyword arguments. All unconsumed keyword - arguments are stored in this special variable. - -`caller` - If the macro was called from a :ref:`call` tag, the caller is stored - in this variable as a callable macro. - -Macros also expose some of their internal details. The following attributes -are available on a macro object: - -`name` - The name of the macro. ``{{ input.name }}`` will print ``input``. - -`arguments` - A tuple of the names of arguments the macro accepts. - -`defaults` - A tuple of default values. - -`catch_kwargs` - This is `true` if the macro accepts extra keyword arguments (i.e.: accesses - the special `kwargs` variable). - -`catch_varargs` - This is `true` if the macro accepts extra positional arguments (i.e.: - accesses the special `varargs` variable). - -`caller` - This is `true` if the macro accesses the special `caller` variable and may - be called from a :ref:`call` tag. - -If a macro name starts with an underscore, it's not exported and can't -be imported. - - -.. _call: - -Call -~~~~ - -In some cases it can be useful to pass a macro to another macro. For this -purpose, you can use the special `call` block. The following example shows -a macro that takes advantage of the call functionality and how it can be -used:: - - {% macro render_dialog(title, class='dialog') -%} -
    -

    {{ title }}

    -
    - {{ caller() }} -
    -
    - {%- endmacro %} - - {% call render_dialog('Hello World') %} - This is a simple dialog rendered by using a macro and - a call block. - {% endcall %} - -It's also possible to pass arguments back to the call block. This makes it -useful as a replacement for loops. Generally speaking, a call block works -exactly like a macro without a name. - -Here's an example of how a call block can be used with arguments:: - - {% macro dump_users(users) -%} -
      - {%- for user in users %} -
    • {{ user.username|e }}

      {{ caller(user) }}
    • - {%- endfor %} -
    - {%- endmacro %} - - {% call(user) dump_users(list_of_user) %} -
    -
    Realname
    -
    {{ user.realname|e }}
    -
    Description
    -
    {{ user.description }}
    -
    - {% endcall %} - - -Filters -~~~~~~~ - -Filter sections allow you to apply regular Jinja2 filters on a block of -template data. Just wrap the code in the special `filter` section:: - - {% filter upper %} - This text becomes uppercase - {% endfilter %} - - -.. _assignments: - -Assignments -~~~~~~~~~~~ - -Inside code blocks, you can also assign values to variables. Assignments at -top level (outside of blocks, macros or loops) are exported from the template -like top level macros and can be imported by other templates. - -Assignments use the `set` tag and can have multiple targets:: - - {% set navigation = [('index.html', 'Index'), ('about.html', 'About')] %} - {% set key, value = call_something() %} - - -Block Assignments -~~~~~~~~~~~~~~~~~ - -.. versionadded:: 2.8 - -Starting with Jinja 2.8, it's possible to also use block assignments to -capture the contents of a block into a variable name. This can be useful -in some situations as an alternative for macros. In that case, instead of -using an equals sign and a value, you just write the variable name and then -everything until ``{% endset %}`` is captured. - -Example:: - - {% set navigation %} -
  • Index -
  • Downloads - {% endset %} - -The `navigation` variable then contains the navigation HTML source. - - -.. _extends: - -Extends -~~~~~~~ - -The `extends` tag can be used to extend one template from another. You can -have multiple `extends` tags in a file, but only one of them may be executed at -a time. - -See the section about :ref:`template-inheritance` above. - - -.. _blocks: - -Blocks -~~~~~~ - -Blocks are used for inheritance and act as both placeholders and replacements -at the same time. They are documented in detail in the -:ref:`template-inheritance` section. - - -Include -~~~~~~~ - -The `include` statement is useful to include a template and return the -rendered contents of that file into the current namespace:: - - {% include 'header.html' %} - Body - {% include 'footer.html' %} - -Included templates have access to the variables of the active context by -default. For more details about context behavior of imports and includes, -see :ref:`import-visibility`. - -From Jinja 2.2 onwards, you can mark an include with ``ignore missing``; in -which case Jinja will ignore the statement if the template to be included -does not exist. When combined with ``with`` or ``without context``, it must -be placed *before* the context visibility statement. Here are some valid -examples:: - - {% include "sidebar.html" ignore missing %} - {% include "sidebar.html" ignore missing with context %} - {% include "sidebar.html" ignore missing without context %} - -.. versionadded:: 2.2 - -You can also provide a list of templates that are checked for existence -before inclusion. The first template that exists will be included. If -`ignore missing` is given, it will fall back to rendering nothing if -none of the templates exist, otherwise it will raise an exception. - -Example:: - - {% include ['page_detailed.html', 'page.html'] %} - {% include ['special_sidebar.html', 'sidebar.html'] ignore missing %} - -.. versionchanged:: 2.4 - If a template object was passed to the template context, you can - include that object using `include`. - -.. _import: - -Import -~~~~~~ - -Jinja2 supports putting often used code into macros. These macros can go into -different templates and get imported from there. This works similarly to the -import statements in Python. It's important to know that imports are cached -and imported templates don't have access to the current template variables, -just the globals by default. For more details about context behavior of -imports and includes, see :ref:`import-visibility`. - -There are two ways to import templates. You can import a complete template -into a variable or request specific macros / exported variables from it. - -Imagine we have a helper module that renders forms (called `forms.html`):: - - {% macro input(name, value='', type='text') -%} - - {%- endmacro %} - - {%- macro textarea(name, value='', rows=10, cols=40) -%} - - {%- endmacro %} - -The easiest and most flexible way to access a template's variables -and macros is to import the whole template module into a variable. -That way, you can access the attributes:: - - {% import 'forms.html' as forms %} -
    -
    Username
    -
    {{ forms.input('username') }}
    -
    Password
    -
    {{ forms.input('password', type='password') }}
    -
    -

    {{ forms.textarea('comment') }}

    - - -Alternatively, you can import specific names from a template into the current -namespace:: - - {% from 'forms.html' import input as input_field, textarea %} -
    -
    Username
    -
    {{ input_field('username') }}
    -
    Password
    -
    {{ input_field('password', type='password') }}
    -
    -

    {{ textarea('comment') }}

    - -Macros and variables starting with one or more underscores are private and -cannot be imported. - -.. versionchanged:: 2.4 - If a template object was passed to the template context, you can - import from that object. - - -.. _import-visibility: - -Import Context Behavior ------------------------ - -By default, included templates are passed the current context and imported -templates are not. The reason for this is that imports, unlike includes, -are cached; as imports are often used just as a module that holds macros. - -This behavior can be changed explicitly: by adding `with context` -or `without context` to the import/include directive, the current context -can be passed to the template and caching is disabled automatically. - -Here are two examples:: - - {% from 'forms.html' import input with context %} - {% include 'header.html' without context %} - -.. admonition:: Note - - In Jinja 2.0, the context that was passed to the included template - did not include variables defined in the template. As a matter of - fact, this did not work:: - - {% for box in boxes %} - {% include "render_box.html" %} - {% endfor %} - - The included template ``render_box.html`` is *not* able to access - `box` in Jinja 2.0. As of Jinja 2.1, ``render_box.html`` *is* able - to do so. - - -.. _expressions: - -Expressions ------------ - -Jinja allows basic expressions everywhere. These work very similarly to -regular Python; even if you're not working with Python -you should feel comfortable with it. - -Literals -~~~~~~~~ - -The simplest form of expressions are literals. Literals are representations -for Python objects such as strings and numbers. The following literals exist: - -"Hello World": - Everything between two double or single quotes is a string. They are - useful whenever you need a string in the template (e.g. as - arguments to function calls and filters, or just to extend or include a - template). - -42 / 42.23: - Integers and floating point numbers are created by just writing the - number down. If a dot is present, the number is a float, otherwise an - integer. Keep in mind that, in Python, ``42`` and ``42.0`` - are different (``int`` and ``float``, respectively). - -['list', 'of', 'objects']: - Everything between two brackets is a list. Lists are useful for storing - sequential data to be iterated over. For example, you can easily - create a list of links using lists and tuples for (and with) a for loop:: - -
      - {% for href, caption in [('index.html', 'Index'), ('about.html', 'About'), - ('downloads.html', 'Downloads')] %} -
    • {{ caption }}
    • - {% endfor %} -
    - -('tuple', 'of', 'values'): - Tuples are like lists that cannot be modified ("immutable"). If a tuple - only has one item, it must be followed by a comma (``('1-tuple',)``). - Tuples are usually used to represent items of two or more elements. - See the list example above for more details. - -{'dict': 'of', 'key': 'and', 'value': 'pairs'}: - A dict in Python is a structure that combines keys and values. Keys must - be unique and always have exactly one value. Dicts are rarely used in - templates; they are useful in some rare cases such as the :func:`xmlattr` - filter. - -true / false: - true is always true and false is always false. - -.. admonition:: Note - - The special constants `true`, `false`, and `none` are indeed lowercase. - Because that caused confusion in the past, (`True` used to expand - to an undefined variable that was considered false), - all three can now also be written in title case - (`True`, `False`, and `None`). - However, for consistency, (all Jinja identifiers are lowercase) - you should use the lowercase versions. - -Math -~~~~ - -Jinja allows you to calculate with values. This is rarely useful in templates -but exists for completeness' sake. The following operators are supported: - -\+ - Adds two objects together. Usually the objects are numbers, but if both are - strings or lists, you can concatenate them this way. This, however, is not - the preferred way to concatenate strings! For string concatenation, have - a look-see at the ``~`` operator. ``{{ 1 + 1 }}`` is ``2``. - -\- - Subtract the second number from the first one. ``{{ 3 - 2 }}`` is ``1``. - -/ - Divide two numbers. The return value will be a floating point number. - ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. - (Just like ``from __future__ import division``.) - -// - Divide two numbers and return the truncated integer result. - ``{{ 20 // 7 }}`` is ``2``. - -% - Calculate the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``. - -\* - Multiply the left operand with the right one. ``{{ 2 * 2 }}`` would - return ``4``. This can also be used to repeat a string multiple times. - ``{{ '=' * 80 }}`` would print a bar of 80 equal signs. - -\** - Raise the left operand to the power of the right operand. ``{{ 2**3 }}`` - would return ``8``. - -Comparisons -~~~~~~~~~~~ - -== - Compares two objects for equality. - -!= - Compares two objects for inequality. - -> - `true` if the left hand side is greater than the right hand side. - ->= - `true` if the left hand side is greater or equal to the right hand side. - -< - `true` if the left hand side is lower than the right hand side. - -<= - `true` if the left hand side is lower or equal to the right hand side. - -Logic -~~~~~ - -For `if` statements, `for` filtering, and `if` expressions, it can be useful to -combine multiple expressions: - -and - Return true if the left and the right operand are true. - -or - Return true if the left or the right operand are true. - -not - negate a statement (see below). - -(expr) - group an expression. - -.. admonition:: Note - - The ``is`` and ``in`` operators support negation using an infix notation, - too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar`` - and ``not foo in bar``. All other expressions require a prefix notation: - ``not (foo and bar).`` - - -Other Operators -~~~~~~~~~~~~~~~ - -The following operators are very useful but don't fit into any of the other -two categories: - -in - Perform a sequence / mapping containment test. Returns true if the left - operand is contained in the right. ``{{ 1 in [1, 2, 3] }}`` would, for - example, return true. - -is - Performs a :ref:`test `. - -\| - Applies a :ref:`filter `. - -~ - Converts all operands into strings and concatenates them. - - ``{{ "Hello " ~ name ~ "!" }}`` would return (assuming `name` is set - to ``'John'``) ``Hello John!``. - -() - Call a callable: ``{{ post.render() }}``. Inside of the parentheses you - can use positional arguments and keyword arguments like in Python: - - ``{{ post.render(user, full=true) }}``. - -. / [] - Get an attribute of an object. (See :ref:`variables`) - - -.. _if-expression: - -If Expression -~~~~~~~~~~~~~ - -It is also possible to use inline `if` expressions. These are useful in some -situations. For example, you can use this to extend from one template if a -variable is defined, otherwise from the default layout template:: - - {% extends layout_template if layout_template is defined else 'master.html' %} - -The general syntax is `` if else ``. - -The `else` part is optional. If not provided, the else block implicitly -evaluates into an undefined object:: - - {{ '[%s]' % page.title if page.title }} - - -.. _builtin-filters: - -List of Builtin Filters ------------------------ - -.. jinjafilters:: - - -.. _builtin-tests: - -List of Builtin Tests ---------------------- - -.. jinjatests:: - -.. _builtin-globals: - -List of Global Functions ------------------------- - -The following functions are available in the global scope by default: - -.. function:: range([start,] stop[, step]) - - Return a list containing an arithmetic progression of integers. - ``range(i, j)`` returns ``[i, i+1, i+2, ..., j-1]``; - start (!) defaults to ``0``. - When step is given, it specifies the increment (or decrement). - For example, ``range(4)`` and ``range(0, 4, 1)`` return ``[0, 1, 2, 3]``. - The end point is omitted! - These are exactly the valid indices for a list of 4 elements. - - This is useful to repeat a template block multiple times, e.g. - to fill a list. Imagine you have 7 users in the list but you want to - render three empty items to enforce a height with CSS:: - -
      - {% for user in users %} -
    • {{ user.username }}
    • - {% endfor %} - {% for number in range(10 - users|count) %} -
    • ...
    • - {% endfor %} -
    - -.. function:: lipsum(n=5, html=True, min=20, max=100) - - Generates some lorem ipsum for the template. By default, five paragraphs - of HTML are generated with each paragraph between 20 and 100 words. - If html is False, regular text is returned. This is useful to generate simple - contents for layout testing. - -.. function:: dict(\**items) - - A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same - as ``dict(foo='bar')``. - -.. class:: cycler(\*items) - - The cycler allows you to cycle among values similar to how `loop.cycle` - works. Unlike `loop.cycle`, you can use this cycler outside of - loops or over multiple loops. - - This can be very useful if you want to show a list of folders and - files with the folders on top but both in the same list with alternating - row colors. - - The following example shows how `cycler` can be used:: - - {% set row_class = cycler('odd', 'even') %} -
      - {% for folder in folders %} -
    • {{ folder|e }}
    • - {% endfor %} - {% for filename in files %} -
    • {{ filename|e }}
    • - {% endfor %} -
    - - A cycler has the following attributes and methods: - - .. method:: reset() - - Resets the cycle to the first item. - - .. method:: next() - - Goes one item ahead and returns the then-current item. - - .. attribute:: current - - Returns the current item. - - **new in Jinja 2.1** - -.. class:: joiner(sep=', ') - - A tiny helper that can be used to "join" multiple sections. A joiner is - passed a string and will return that string every time it's called, except - the first time (in which case it returns an empty string). You can - use this to join things:: - - {% set pipe = joiner("|") %} - {% if categories %} {{ pipe() }} - Categories: {{ categories|join(", ") }} - {% endif %} - {% if author %} {{ pipe() }} - Author: {{ author() }} - {% endif %} - {% if can_edit %} {{ pipe() }} - Edit - {% endif %} - - **new in Jinja 2.1** - - -Extensions ----------- - -The following sections cover the built-in Jinja2 extensions that may be -enabled by an application. An application could also provide further -extensions not covered by this documentation; in which case there should -be a separate document explaining said :ref:`extensions -`. - -.. _i18n-in-templates: - -i18n -~~~~ - -If the i18n extension is enabled, it's possible to mark parts in the template -as translatable. To mark a section as translatable, you can use `trans`:: - -

    {% trans %}Hello {{ user }}!{% endtrans %}

    - -To translate a template expression --- say, using template filters, or by just -accessing an attribute of an object --- you need to bind the expression to a -name for use within the translation block:: - -

    {% trans user=user.username %}Hello {{ user }}!{% endtrans %}

    - -If you need to bind more than one expression inside a `trans` tag, separate -the pieces with a comma (``,``):: - - {% trans book_title=book.title, author=author.name %} - This is {{ book_title }} by {{ author }} - {% endtrans %} - -Inside trans tags no statements are allowed, only variable tags are. - -To pluralize, specify both the singular and plural forms with the `pluralize` -tag, which appears between `trans` and `endtrans`:: - - {% trans count=list|length %} - There is {{ count }} {{ name }} object. - {% pluralize %} - There are {{ count }} {{ name }} objects. - {% endtrans %} - -By default, the first variable in a block is used to determine the correct -singular or plural form. If that doesn't work out, you can specify the name -which should be used for pluralizing by adding it as parameter to `pluralize`:: - - {% trans ..., user_count=users|length %}... - {% pluralize user_count %}...{% endtrans %} - -It's also possible to translate strings in expressions. For that purpose, -three functions exist: - -- `gettext`: translate a single string -- `ngettext`: translate a pluralizable string -- `_`: alias for `gettext` - -For example, you can easily print a translated string like this:: - - {{ _('Hello World!') }} - -To use placeholders, use the `format` filter:: - - {{ _('Hello %(user)s!')|format(user=user.username) }} - -For multiple placeholders, always use keyword arguments to `format`, -as other languages may not use the words in the same order. - -.. versionchanged:: 2.5 - -If newstyle gettext calls are activated (:ref:`newstyle-gettext`), using -placeholders is a lot easier: - -.. sourcecode:: html+jinja - - {{ gettext('Hello World!') }} - {{ gettext('Hello %(name)s!', name='World') }} - {{ ngettext('%(num)d apple', '%(num)d apples', apples|count) }} - -Note that the `ngettext` function's format string automatically receives -the count as a `num` parameter in addition to the regular parameters. - - -Expression Statement -~~~~~~~~~~~~~~~~~~~~ - -If the expression-statement extension is loaded, a tag called `do` is available -that works exactly like the regular variable expression (``{{ ... }}``); except -it doesn't print anything. This can be used to modify lists:: - - {% do navigation.append('a string') %} - - -Loop Controls -~~~~~~~~~~~~~ - -If the application enables the :ref:`loopcontrols-extension`, it's possible to -use `break` and `continue` in loops. When `break` is reached, the loop is -terminated; if `continue` is reached, the processing is stopped and continues -with the next iteration. - -Here's a loop that skips every second item:: - - {% for user in users %} - {%- if loop.index is even %}{% continue %}{% endif %} - ... - {% endfor %} - -Likewise, a loop that stops processing after the 10th iteration:: - - {% for user in users %} - {%- if loop.index >= 10 %}{% break %}{% endif %} - {%- endfor %} - -Note that ``loop.index`` starts with 1, and ``loop.index0`` starts with 0 -(See: :ref:`for-loop`). - - -With Statement -~~~~~~~~~~~~~~ - -.. versionadded:: 2.3 - -If the application enables the :ref:`with-extension`, it is possible to -use the `with` keyword in templates. This makes it possible to create -a new inner scope. Variables set within this scope are not visible -outside of the scope. - -With in a nutshell:: - - {% with %} - {% set foo = 42 %} - {{ foo }} foo is 42 here - {% endwith %} - foo is not visible here any longer - -Because it is common to set variables at the beginning of the scope, -you can do that within the `with` statement. The following two examples -are equivalent:: - - {% with foo = 42 %} - {{ foo }} - {% endwith %} - - {% with %} - {% set foo = 42 %} - {{ foo }} - {% endwith %} - -.. _autoescape-overrides: - -Autoescape Extension --------------------- - -.. versionadded:: 2.4 - -If the application enables the :ref:`autoescape-extension`, one can -activate and deactivate the autoescaping from within the templates. - -Example:: - - {% autoescape true %} - Autoescaping is active within this block - {% endautoescape %} - - {% autoescape false %} - Autoescaping is inactive within this block - {% endautoescape %} - -After an `endautoescape` the behavior is reverted to what it was before. diff --git a/deps/v8_inspector/third_party/jinja2/docs/tricks.rst b/deps/v8_inspector/third_party/jinja2/docs/tricks.rst deleted file mode 100644 index 4d33e220706e42..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/docs/tricks.rst +++ /dev/null @@ -1,100 +0,0 @@ -Tips and Tricks -=============== - -.. highlight:: html+jinja - -This part of the documentation shows some tips and tricks for Jinja2 -templates. - - -.. _null-master-fallback: - -Null-Master Fallback --------------------- - -Jinja2 supports dynamic inheritance and does not distinguish between parent -and child template as long as no `extends` tag is visited. While this leads -to the surprising behavior that everything before the first `extends` tag -including whitespace is printed out instead of being ignored, it can be used -for a neat trick. - -Usually child templates extend from one template that adds a basic HTML -skeleton. However it's possible to put the `extends` tag into an `if` tag to -only extend from the layout template if the `standalone` variable evaluates -to false which it does per default if it's not defined. Additionally a very -basic skeleton is added to the file so that if it's indeed rendered with -`standalone` set to `True` a very basic HTML skeleton is added:: - - {% if not standalone %}{% extends 'master.html' %}{% endif -%} - - {% block title %}The Page Title{% endblock %} - - {% block body %} -

    This is the page body.

    - {% endblock %} - - -Alternating Rows ----------------- - -If you want to have different styles for each row of a table or -list you can use the `cycle` method on the `loop` object:: - -
      - {% for row in rows %} -
    • {{ row }}
    • - {% endfor %} -
    - -`cycle` can take an unlimited amount of strings. Each time this -tag is encountered the next item from the list is rendered. - - -Highlighting Active Menu Items ------------------------------- - -Often you want to have a navigation bar with an active navigation -item. This is really simple to achieve. Because assignments outside -of `block`\s in child templates are global and executed before the layout -template is evaluated it's possible to define the active menu item in the -child template:: - - {% extends "layout.html" %} - {% set active_page = "index" %} - -The layout template can then access `active_page`. Additionally it makes -sense to define a default for that variable:: - - {% set navigation_bar = [ - ('/', 'index', 'Index'), - ('/downloads/', 'downloads', 'Downloads'), - ('/about/', 'about', 'About') - ] -%} - {% set active_page = active_page|default('index') -%} - ... - - ... - -.. _accessing-the-parent-loop: - -Accessing the parent Loop -------------------------- - -The special `loop` variable always points to the innermost loop. If it's -desired to have access to an outer loop it's possible to alias it:: - - - {% for row in table %} - - {% set rowloop = loop %} - {% for cell in row %} - - {% endfor %} - - {% endfor %} -
    {{ cell }}
    diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/cycle.py b/deps/v8_inspector/third_party/jinja2/examples/basic/cycle.py deleted file mode 100644 index 73dd6325eb8064..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/cycle.py +++ /dev/null @@ -1,13 +0,0 @@ -from jinja2 import Environment - - -env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}") - - -print env.from_string("""\ -
      -# for item in range(10) -
    • ${item}
    • -# endfor -
    \ -""").render() diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/debugger.py b/deps/v8_inspector/third_party/jinja2/examples/basic/debugger.py deleted file mode 100644 index 4291ff7ac4a9ff..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/debugger.py +++ /dev/null @@ -1,7 +0,0 @@ -from jinja2 import Environment -from jinja2.loaders import FileSystemLoader - -env = Environment(loader=FileSystemLoader('templates')) - -tmpl = env.get_template('broken.html') -print tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1]) diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/inheritance.py b/deps/v8_inspector/third_party/jinja2/examples/basic/inheritance.py deleted file mode 100644 index aa687c898a1378..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/inheritance.py +++ /dev/null @@ -1,12 +0,0 @@ -from jinja2 import Environment -from jinja2.loaders import DictLoader - - -env = Environment(loader=DictLoader({ -'a': '''[A[{% block body %}{% endblock %}]]''', -'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''', -'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}''' -})) - - -print env.get_template('c').render() diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/templates/broken.html b/deps/v8_inspector/third_party/jinja2/examples/basic/templates/broken.html deleted file mode 100644 index 294d5c99894d9f..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/templates/broken.html +++ /dev/null @@ -1,6 +0,0 @@ -{% from 'subbroken.html' import may_break %} -
      -{% for item in seq %} -
    • {{ may_break(item) }}
    • -{% endfor %} -
    diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/templates/subbroken.html b/deps/v8_inspector/third_party/jinja2/examples/basic/templates/subbroken.html deleted file mode 100644 index 245eb7e6e6f7f6..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/templates/subbroken.html +++ /dev/null @@ -1,3 +0,0 @@ -{% macro may_break(item) -%} - [{{ item / 0 }}] -{%- endmacro %} diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/test.py b/deps/v8_inspector/third_party/jinja2/examples/basic/test.py deleted file mode 100644 index 8f7dde79221057..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/test.py +++ /dev/null @@ -1,27 +0,0 @@ -from jinja2 import Environment -from jinja2.loaders import DictLoader - -env = Environment(loader=DictLoader({ -'child.html': u'''\ -{% extends master_layout or 'master.html' %} -{% include helpers = 'helpers.html' %} -{% macro get_the_answer() %}42{% endmacro %} -{% title = 'Hello World' %} -{% block body %} - {{ get_the_answer() }} - {{ helpers.conspirate() }} -{% endblock %} -''', -'master.html': u'''\ - -{{ title }} -{% block body %}{% endblock %} -''', -'helpers.html': u'''\ -{% macro conspirate() %}23{% endmacro %} -''' -})) - - -tmpl = env.get_template("child.html") -print(tmpl.render()) diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/test_filter_and_linestatements.py b/deps/v8_inspector/third_party/jinja2/examples/basic/test_filter_and_linestatements.py deleted file mode 100644 index 79e0a4b371a5d0..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/test_filter_and_linestatements.py +++ /dev/null @@ -1,25 +0,0 @@ -from jinja2 import Environment - - -env = Environment(line_statement_prefix='%', variable_start_string="${", variable_end_string="}") -tmpl = env.from_string("""\ -% macro foo() - ${caller(42)} -% endmacro -
      -% for item in seq -
    • ${item}
    • -% endfor -
    -% call(var) foo() - [${var}] -% endcall -% filter escape - - % for item in [1, 2, 3] - - ${item} - % endfor -% endfilter -""") - -print(tmpl.render(seq=range(10))) diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/test_loop_filter.py b/deps/v8_inspector/third_party/jinja2/examples/basic/test_loop_filter.py deleted file mode 100644 index 0469d04e432af8..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/test_loop_filter.py +++ /dev/null @@ -1,12 +0,0 @@ -from jinja2 import Environment - -tmpl = Environment().from_string("""\ -
      -{%- for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %} -
    • {{ loop.index }} / {{ loop.length }}: {{ item }}
    • -{%- endfor %} -
    -if condition: {{ 1 if foo else 0 }} -""") - -print(tmpl.render(foo=True)) diff --git a/deps/v8_inspector/third_party/jinja2/examples/basic/translate.py b/deps/v8_inspector/third_party/jinja2/examples/basic/translate.py deleted file mode 100644 index 1fb8ee63bf284b..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/basic/translate.py +++ /dev/null @@ -1,14 +0,0 @@ -from jinja2 import Environment - -env = Environment(extensions=['jinja2.ext.i18n']) -env.globals['gettext'] = { - 'Hello %(user)s!': 'Hallo %(user)s!' -}.__getitem__ -env.globals['ngettext'] = lambda s, p, n: { - '%(count)s user': '%(count)d Benutzer', - '%(count)s users': '%(count)d Benutzer' -}[n == 1 and s or p] -print env.from_string("""\ -{% trans %}Hello {{ user }}!{% endtrans %} -{% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %} -""").render(user="someone", users=[1, 2, 3]) diff --git a/deps/v8_inspector/third_party/jinja2/examples/bench.py b/deps/v8_inspector/third_party/jinja2/examples/bench.py deleted file mode 100644 index c648dc69b02865..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/bench.py +++ /dev/null @@ -1,433 +0,0 @@ -"""\ - This benchmark compares some python templating engines with Jinja 2 so - that we get a picture of how fast Jinja 2 is for a semi real world - template. If a template engine is not installed the test is skipped.\ -""" -import sys -import cgi -from timeit import Timer -from jinja2 import Environment as JinjaEnvironment - -context = { - 'page_title': 'mitsuhiko\'s benchmark', - 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] -} - -jinja_template = JinjaEnvironment( - line_statement_prefix='%', - variable_start_string="${", - variable_end_string="}" -).from_string("""\ - - - - ${page_title|e} - - -
    -

    ${page_title|e}

    -
    - -
    - - % for row in table - - % for cell in row - - % endfor - - % endfor -
    ${cell}
    -
    - -\ -""") - -def test_jinja(): - jinja_template.render(context) - -try: - from tornado.template import Template -except ImportError: - test_tornado = None -else: - tornado_template = Template("""\ - - - - {{ page_title }} - - -
    -

    {{ page_title }}

    -
    - -
    - - {% for row in table %} - - {% for cell in row %} - - {% end %} - - {% end %} -
    {{ cell }}
    -
    - -\ -""") - - def test_tornado(): - tornado_template.generate(**context) - -try: - from django.conf import settings - settings.configure() - from django.template import Template as DjangoTemplate, Context as DjangoContext -except ImportError: - test_django = None -else: - django_template = DjangoTemplate("""\ - - - - {{ page_title }} - - -
    -

    {{ page_title }}

    -
    - -
    - - {% for row in table %} - - {% for cell in row %} - - {% endfor %} - - {% endfor %} -
    {{ cell }}
    -
    - -\ -""") - - def test_django(): - c = DjangoContext(context) - c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'), - ('products.html', 'Products')] - django_template.render(c) - -try: - from mako.template import Template as MakoTemplate -except ImportError: - test_mako = None -else: - mako_template = MakoTemplate("""\ - - - - ${page_title|h} - - -
    -

    ${page_title|h}

    -
    - -
    - - % for row in table: - - % for cell in row: - - % endfor - - % endfor -
    ${cell}
    -
    - -\ -""") - - def test_mako(): - mako_template.render(**context) - -try: - from genshi.template import MarkupTemplate as GenshiTemplate -except ImportError: - test_genshi = None -else: - genshi_template = GenshiTemplate("""\ - - - ${page_title} - - -
    -

    ${page_title}

    -
    - -
    - - - - -
    ${cell}
    -
    - -\ -""") - - def test_genshi(): - genshi_template.generate(**context).render('html', strip_whitespace=False) - -try: - from Cheetah.Template import Template as CheetahTemplate -except ImportError: - test_cheetah = None -else: - cheetah_template = CheetahTemplate("""\ -#import cgi - - - - $cgi.escape($page_title) - - -
    -

    $cgi.escape($page_title)

    -
    - -
    - - #for $row in $table: - - #for $cell in $row: - - #end for - - #end for -
    $cell
    -
    - -\ -""", searchList=[dict(context)]) - - def test_cheetah(): - unicode(cheetah_template) - -try: - import tenjin -except ImportError: - test_tenjin = None -else: - tenjin_template = tenjin.Template() - tenjin_template.convert("""\ - - - - ${page_title} - - -
    -

    ${page_title}

    -
    - -
    - - - - - - - - -
    #{cell}
    -
    - -\ -""") - - def test_tenjin(): - from tenjin.helpers import escape, to_str - tenjin_template.render(context, locals()) - -try: - from spitfire.compiler import util as SpitfireTemplate - from spitfire.compiler.analyzer import o2_options as spitfire_optimizer -except ImportError: - test_spitfire = None -else: - spitfire_template = SpitfireTemplate.load_template("""\ - - - - $cgi.escape($page_title) - - -
    -

    $cgi.escape($page_title)

    -
    - -
    - - #for $row in $table - - #for $cell in $row - - #end for - - #end for -
    $cell
    -
    - -\ -""", 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False}) - spitfire_context = dict(context, **{'cgi': cgi}) - - def test_spitfire(): - spitfire_template(search_list=[spitfire_context]).main() - - -try: - from chameleon.zpt.template import PageTemplate -except ImportError: - test_chameleon = None -else: - chameleon_template = PageTemplate("""\ - - - Page Title - - -
    -

    Page Title

    -
    - -
    - - - - -
    cell
    -
    - -\ -""") - chameleon_context = dict(context) - chameleon_context['sections'] = [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') - ] - def test_chameleon(): - chameleon_template.render(**chameleon_context) - -try: - from chameleon.zpt.template import PageTemplate - from chameleon.genshi import language -except ImportError: - test_chameleon_genshi = None -else: - chameleon_genshi_template = PageTemplate("""\ - - - ${page_title} - - -
    -

    ${page_title}

    -
    - -
    - - - - -
    ${row[cell]}
    -
    - -\ -""", parser=language.Parser()) - chameleon_genshi_context = dict(context) - chameleon_genshi_context['sections'] = [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') - ] - def test_chameleon_genshi(): - chameleon_genshi_template.render(**chameleon_genshi_context) - - -sys.stdout.write('\r' + '\n'.join(( - '=' * 80, - 'Template Engine BigTable Benchmark'.center(80), - '=' * 80, - __doc__, - '-' * 80 -)) + '\n') - - -for test in 'jinja', 'mako', 'tornado', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah', 'chameleon', 'chameleon_genshi': - if locals()['test_' + test] is None: - sys.stdout.write(' %-20s*not installed*\n' % test) - continue - t = Timer(setup='from __main__ import test_%s as bench' % test, - stmt='bench()') - sys.stdout.write(' >> %-20s' % test) - sys.stdout.flush() - sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50)) -sys.stdout.write('-' * 80 + '\n') -sys.stdout.write('''\ - WARNING: The results of this benchmark are useless to compare the - performance of template engines and should not be taken seriously in any - way. It's testing the performance of simple loops and has no real-world - usefulnes. It only used to check if changes on the Jinja code affect - performance in a good or bad way and how it roughly compares to others. -''' + '=' * 80 + '\n') diff --git a/deps/v8_inspector/third_party/jinja2/examples/profile.py b/deps/v8_inspector/third_party/jinja2/examples/profile.py deleted file mode 100644 index 0c907ae3f12a64..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/profile.py +++ /dev/null @@ -1,52 +0,0 @@ -try: - from cProfile import Profile -except ImportError: - from profile import Profile -from pstats import Stats -from jinja2 import Environment as JinjaEnvironment - -context = { - 'page_title': 'mitsuhiko\'s benchmark', - 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] -} - -source = """\ -% macro testmacro(x) - ${x} -% endmacro - - - - ${page_title|e} - - -
    -

    ${page_title|e}

    -
    -
    - - % for row in table - - % for cell in row - - % endfor - - % endfor -
    ${testmacro(cell)}
    -
    - -\ -""" -jinja_template = JinjaEnvironment( - line_statement_prefix='%', - variable_start_string="${", - variable_end_string="}" -).from_string(source) -print jinja_template.environment.compile(source, raw=True) - - -p = Profile() -p.runcall(lambda: jinja_template.render(context)) -stats = Stats(p) -stats.sort_stats('time', 'calls') -stats.print_stats() diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_form.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_form.html deleted file mode 100644 index 9c4f710eacc405..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_form.html +++ /dev/null @@ -1 +0,0 @@ -
    {{ body }}
    diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_input_field.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_input_field.html deleted file mode 100644 index 290fdbd446ed26..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_input_field.html +++ /dev/null @@ -1 +0,0 @@ - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_textarea.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_textarea.html deleted file mode 100644 index 7f104240559c96..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/_textarea.html +++ /dev/null @@ -1 +0,0 @@ - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/index.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/index.html deleted file mode 100644 index 6f620bb2c04f55..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/index.html +++ /dev/null @@ -1,29 +0,0 @@ -{% extends "layout.html" %} -{% block page_title %}Index Page{% endblock %} -{% block body %} - {% for article in articles %} - {% if article.published %} -
    -

    {{ article.title }}

    -

    written by {{ article.user.username }} on {{ article.pub_date|dateformat }}

    -
    {{ article.body|safe }}
    -
    - {% endif %} - {% endfor %} - {% form %} -
    -
    Name
    -
    {% input_field 'name' %}
    -
    E-Mail
    -
    {% input_field 'email' %}
    -
    URL
    -
    {% input_field 'url' %}
    -
    Comment
    -
    {% textarea 'comment' %}
    -
    Captcha
    -
    {% input_field 'captcha' %}
    -
    - {% input_field '' 'submit' 'Submit' %} - {% input_field 'cancel' 'submit' 'Cancel' %} - {% endform %} -{% endblock %} diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/layout.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/layout.html deleted file mode 100644 index 60039cebad1f69..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/django/layout.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - {% block page_title %}{% endblock %} | RealWorld Benchmark - - - -
    -
    -

    RealWorld Benchmark

    -

    - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. -

    -
    - -
    - {% block body %}{% endblock %} -
    - -
    - - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/djangoext.py b/deps/v8_inspector/third_party/jinja2/examples/rwbench/djangoext.py deleted file mode 100644 index 9e9fa6cf0d7095..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/djangoext.py +++ /dev/null @@ -1,135 +0,0 @@ -# -*- coding: utf-8 -*- -from rwbench import ROOT -from os.path import join -from django.conf import settings -settings.configure( - TEMPLATE_DIRS=(join(ROOT, 'django'),), - TEMPLATE_LOADERS=( - ('django.template.loaders.cached.Loader', ( - 'django.template.loaders.filesystem.Loader', - )), - ) -) -from django.template import loader as django_loader, Context as DjangoContext, \ - Node, NodeList, Variable, TokenParser -from django import template as django_template_module -from django.template import Library - - -# for django extensions. We monkey patch our extensions in so that -# we don't have to initialize a more complex django setup. -django_extensions = django_template_module.Library() -django_template_module.builtins.append(django_extensions) - - -from rwbench import dateformat -django_extensions.filter(dateformat) - - -def var_or_none(x): - if x is not None: - return Variable(x) - - -# and more django extensions -@django_extensions.tag -def input_field(parser, token): - p = TokenParser(token.contents) - args = [p.value()] - while p.more(): - args.append(p.value()) - return InputFieldNode(*args) - - -@django_extensions.tag -def textarea(parser, token): - p = TokenParser(token.contents) - args = [p.value()] - while p.more(): - args.append(p.value()) - return TextareaNode(*args) - - -@django_extensions.tag -def form(parser, token): - p = TokenParser(token.contents) - args = [] - while p.more(): - args.append(p.value()) - body = parser.parse(('endform',)) - parser.delete_first_token() - return FormNode(body, *args) - - -class InputFieldNode(Node): - - def __init__(self, name, type=None, value=None): - self.name = var_or_none(name) - self.type = var_or_none(type) - self.value = var_or_none(value) - - def render(self, context): - name = self.name.resolve(context) - type = 'text' - value = '' - if self.type is not None: - type = self.type.resolve(context) - if self.value is not None: - value = self.value.resolve(context) - tmpl = django_loader.get_template('_input_field.html') - return tmpl.render(DjangoContext({ - 'name': name, - 'type': type, - 'value': value - })) - - -class TextareaNode(Node): - - def __init__(self, name, rows=None, cols=None, value=None): - self.name = var_or_none(name) - self.rows = var_or_none(rows) - self.cols = var_or_none(cols) - self.value = var_or_none(value) - - def render(self, context): - name = self.name.resolve(context) - rows = 10 - cols = 40 - value = '' - if self.rows is not None: - rows = int(self.rows.resolve(context)) - if self.cols is not None: - cols = int(self.cols.resolve(context)) - if self.value is not None: - value = self.value.resolve(context) - tmpl = django_loader.get_template('_textarea.html') - return tmpl.render(DjangoContext({ - 'name': name, - 'rows': rows, - 'cols': cols, - 'value': value - })) - - -class FormNode(Node): - - def __init__(self, body, action=None, method=None): - self.body = body - self.action = action - self.method = method - - def render(self, context): - body = self.body.render(context) - action = '' - method = 'post' - if self.action is not None: - action = self.action.resolve(context) - if self.method is not None: - method = self.method.resolve(context) - tmpl = django_loader.get_template('_form.html') - return tmpl.render(DjangoContext({ - 'body': body, - 'action': action, - 'method': method - })) diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/helpers.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/helpers.html deleted file mode 100644 index ecc6dc4d9ca897..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/helpers.html +++ /dev/null @@ -1,12 +0,0 @@ -
    - - - - - - - - - -
    diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/index.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/index.html deleted file mode 100644 index 70f697d5765651..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/index.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - Index Page - -
    - -

    ${article.title}

    -

    written by ${article.user.username} on ${dateformat(article.pub_date)}

    -
    ${Markup(article.body)}
    -
    -
    - -
    -
    -
    Name
    -
    ${input_field('name')}
    -
    E-Mail
    -
    ${input_field('email')}
    -
    URL
    -
    ${input_field('url')}
    -
    Comment
    -
    ${textarea('comment')}
    -
    Captcha
    -
    ${input_field('captcha')}
    -
    - ${input_field(type='submit', value='Submit')} - ${input_field(name='cancel', type='submit', value='Cancel')} -
    - - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/layout.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/layout.html deleted file mode 100644 index b12aec48d88327..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/genshi/layout.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - ${select('title/text()')} | RealWorld Benchmark - - - - - -
    -
    -

    RealWorld Benchmark

    -

    - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. -

    -
    - -
    - ${select('*|text()')} -
    - -
    - -
    - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/helpers.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/helpers.html deleted file mode 100644 index 89976aa05f1404..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/helpers.html +++ /dev/null @@ -1,12 +0,0 @@ -{% macro input_field(name, value='', type='text') -%} - -{%- endmacro %} - -{% macro textarea(name, value='', rows=10, cols=40) -%} - -{%- endmacro %} - -{% macro form(action='', method='post') -%} -
    {{ caller() }}
    -{%- endmacro %} diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/index.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/index.html deleted file mode 100644 index b006d0565e1a04..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/index.html +++ /dev/null @@ -1,29 +0,0 @@ -{% extends "layout.html" %} -{% from "helpers.html" import input_field, textarea, form %} -{% block page_title %}Index Page{% endblock %} -{% block body %} - {%- for article in articles if article.published %} -
    -

    {{ article.title|e }}

    -

    written by {{ article.user.username|e }} on {{ article.pub_date|dateformat }}

    -
    {{ article.body }}
    -
    - {%- endfor %} - {%- call form() %} -
    -
    Name
    -
    {{ input_field('name') }}
    -
    E-Mail
    -
    {{ input_field('email') }}
    -
    URL
    -
    {{ input_field('url') }}
    -
    Comment
    -
    {{ textarea('comment') }}
    -
    Captcha
    -
    {{ input_field('captcha') }}
    -
    - {{ input_field(type='submit', value='Submit') }} - {{ input_field('cancel', type='submit', value='Cancel') }} - {%- endcall %} -{% endblock %} diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/layout.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/layout.html deleted file mode 100644 index 755789e24877fb..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/jinja/layout.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - {% block page_title %}{% endblock %} | RealWorld Benchmark - - - -
    -
    -

    RealWorld Benchmark

    -

    - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. -

    -
    - -
    - {% block body %}{% endblock %} -
    - -
    - - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/helpers.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/helpers.html deleted file mode 100644 index a0290ebb2e9fae..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/helpers.html +++ /dev/null @@ -1,11 +0,0 @@ -<%def name="input_field(name='', value='', type='text')"> - - - -<%def name="textarea(name, value='', rows=10, cols=40)"> - - - -<%def name="form(action='', method='post')"> -
    ${caller.body()}
    - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/index.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/index.html deleted file mode 100644 index c4c6303246e364..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/index.html +++ /dev/null @@ -1,31 +0,0 @@ -<%! - from rwbench import dateformat -%> -<%inherit file="layout.html" /> -<%namespace file="helpers.html" import="input_field, textarea, form" /> -<%def name="page_title()">Index Page -% for article in articles: - <% if not article.published: continue %> -
    -

    ${article.title|h}

    -

    written by ${article.user.username|h} on ${dateformat(article.pub_date)}

    -
    ${article.body}
    -
    -% endfor -<%call expr="form()"> -
    -
    Name
    -
    ${input_field('name')}
    -
    E-Mail
    -
    ${input_field('email')}
    -
    URL
    -
    ${input_field('url')}
    -
    Comment
    -
    ${textarea('comment')}
    -
    Captcha
    -
    ${input_field('captcha')}
    -
    - ${input_field(type='submit', value='Submit')} - ${input_field(name='cancel', type='submit', value='Cancel')} - diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/layout.html b/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/layout.html deleted file mode 100644 index a9c353e1c65a5d..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/mako/layout.html +++ /dev/null @@ -1,30 +0,0 @@ - - - - ${self.page_title()} | RealWorld Benchmark - - - -
    -
    -

    RealWorld Benchmark

    -

    - A less stupid benchmark for Mako and Jinja2 to get an impression how - code changes affect runtime performance. -

    -
    - -
    - ${self.body()} -
    - -
    - - -<%def name="page_title()"> diff --git a/deps/v8_inspector/third_party/jinja2/examples/rwbench/rwbench.py b/deps/v8_inspector/third_party/jinja2/examples/rwbench/rwbench.py deleted file mode 100644 index 813dd56cf71431..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/examples/rwbench/rwbench.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -""" - RealWorldish Benchmark - ~~~~~~~~~~~~~~~~~~~~~~ - - A more real-world benchmark of Jinja2. Like the other benchmark in the - Jinja2 repository this has no real-world usefulnes (despite the name). - Just go away and ignore it. NOW! - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -import sys -from os.path import join, dirname, abspath -try: - from cProfile import Profile -except ImportError: - from profile import Profile -from pstats import Stats -ROOT = abspath(dirname(__file__)) - -from random import choice, randrange -from datetime import datetime -from timeit import Timer -from jinja2 import Environment, FileSystemLoader -from jinja2.utils import generate_lorem_ipsum -from mako.lookup import TemplateLookup -from genshi.template import TemplateLoader as GenshiTemplateLoader - - -def dateformat(x): - return x.strftime('%Y-%m-%d') - - -jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja'))) -jinja_env.filters['dateformat'] = dateformat -mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')]) -genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')]) - -class Article(object): - - def __init__(self, id): - self.id = id - self.href = '/article/%d' % self.id - self.title = generate_lorem_ipsum(1, False, 5, 10) - self.user = choice(users) - self.body = generate_lorem_ipsum() - self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9)) - self.published = True - - -class User(object): - - def __init__(self, username): - self.href = '/user/%s' % username - self.username = username - - -users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat']) -articles = map(Article, range(20)) -navigation = [ - ('index', 'Index'), - ('about', 'About'), - ('foo?bar=1', 'Foo with Bar'), - ('foo?bar=2&s=x', 'Foo with X'), - ('blah', 'Blub Blah'), - ('hehe', 'Haha'), -] * 5 - -context = dict(users=users, articles=articles, page_navigation=navigation) - - -jinja_template = jinja_env.get_template('index.html') -mako_template = mako_lookup.get_template('index.html') -genshi_template = genshi_loader.load('index.html') - - -def test_jinja(): - jinja_template.render(context) - -def test_mako(): - mako_template.render_unicode(**context) - - -from djangoext import django_loader, DjangoContext -def test_django(): - # not cached because django is not thread safe and does - # not cache by itself so it would be unfair to cache it here. - django_template = django_loader.get_template('index.html') - django_template.render(DjangoContext(context)) - - -def test_genshi(): - genshi_template.generate(**context).render('html', doctype='html') - - -if __name__ == '__main__': - sys.stdout.write('Realworldish Benchmark:\n') - for test in 'jinja', 'mako', 'django', 'genshi': - t = Timer(setup='from __main__ import test_%s as bench' % test, - stmt='bench()') - sys.stdout.write(' >> %-20s' % test) - sys.stdout.flush() - sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200)) - - if '-p' in sys.argv: - print 'Jinja profile' - p = Profile() - p.runcall(test_jinja) - stats = Stats(p) - stats.sort_stats('time', 'calls') - stats.print_stats() diff --git a/deps/v8_inspector/third_party/jinja2/ext/Vim/jinja.vim b/deps/v8_inspector/third_party/jinja2/ext/Vim/jinja.vim deleted file mode 100644 index ac72efe796e476..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/Vim/jinja.vim +++ /dev/null @@ -1,135 +0,0 @@ -" Vim syntax file -" Language: Jinja template -" Maintainer: Armin Ronacher -" Last Change: 2008 May 9 -" Version: 1.1 -" -" Known Bugs: -" because of odd limitations dicts and the modulo operator -" appear wrong in the template. -" -" Changes: -" -" 2008 May 9: Added support for Jinja2 changes (new keyword rules) - -" .vimrc variable to disable html highlighting -if !exists('g:jinja_syntax_html') - let g:jinja_syntax_html=1 -endif - -" For version 5.x: Clear all syntax items -" For version 6.x: Quit when a syntax file was already loaded -if !exists("main_syntax") - if version < 600 - syntax clear - elseif exists("b:current_syntax") - finish -endif - let main_syntax = 'jinja' -endif - -" Pull in the HTML syntax. -if g:jinja_syntax_html - if version < 600 - so :p:h/html.vim - else - runtime! syntax/html.vim - unlet b:current_syntax - endif -endif - -syntax case match - -" Jinja template built-in tags and parameters (without filter, macro, is and raw, they -" have special threatment) -syn keyword jinjaStatement containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained and if else in not or recursive as import - -syn keyword jinjaStatement containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained is filter skipwhite nextgroup=jinjaFilter -syn keyword jinjaStatement containedin=jinjaTagBlock contained macro skipwhite nextgroup=jinjaFunction -syn keyword jinjaStatement containedin=jinjaTagBlock contained block skipwhite nextgroup=jinjaBlockName - -" Variable Names -syn match jinjaVariable containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[a-zA-Z_][a-zA-Z0-9_]*/ -syn keyword jinjaSpecial containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained false true none False True None loop super caller varargs kwargs - -" Filters -syn match jinjaOperator "|" containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained skipwhite nextgroup=jinjaFilter -syn match jinjaFilter contained /[a-zA-Z_][a-zA-Z0-9_]*/ -syn match jinjaFunction contained /[a-zA-Z_][a-zA-Z0-9_]*/ -syn match jinjaBlockName contained /[a-zA-Z_][a-zA-Z0-9_]*/ - -" Jinja template constants -syn region jinjaString containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained start=/"/ skip=/\(\\\)\@\)*\\"/ end=/"/ -syn region jinjaString containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained start=/'/ skip=/\(\\\)\@\)*\\'/ end=/'/ -syn match jinjaNumber containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[0-9]\+\(\.[0-9]\+\)\?/ - -" Operators -syn match jinjaOperator containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[+\-*\/<>=!,:]/ -syn match jinjaPunctuation containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /[()\[\]]/ -syn match jinjaOperator containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained /\./ nextgroup=jinjaAttribute -syn match jinjaAttribute contained /[a-zA-Z_][a-zA-Z0-9_]*/ - -" Jinja template tag and variable blocks -syn region jinjaNested matchgroup=jinjaOperator start="(" end=")" transparent display containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained -syn region jinjaNested matchgroup=jinjaOperator start="\[" end="\]" transparent display containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained -syn region jinjaNested matchgroup=jinjaOperator start="{" end="}" transparent display containedin=jinjaVarBlock,jinjaTagBlock,jinjaNested contained -syn region jinjaTagBlock matchgroup=jinjaTagDelim start=/{%-\?/ end=/-\?%}/ containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaRaw,jinjaString,jinjaNested,jinjaComment - -syn region jinjaVarBlock matchgroup=jinjaVarDelim start=/{{-\?/ end=/-\?}}/ containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaRaw,jinjaString,jinjaNested,jinjaComment - -" Jinja template 'raw' tag -syn region jinjaRaw matchgroup=jinjaRawDelim start="{%\s*raw\s*%}" end="{%\s*endraw\s*%}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString,jinjaComment - -" Jinja comments -syn region jinjaComment matchgroup=jinjaCommentDelim start="{#" end="#}" containedin=ALLBUT,jinjaTagBlock,jinjaVarBlock,jinjaString - -" Block start keywords. A bit tricker. We only highlight at the start of a -" tag block and only if the name is not followed by a comma or equals sign -" which usually means that we have to deal with an assignment. -syn match jinjaStatement containedin=jinjaTagBlock contained /\({%-\?\s*\)\@<=\<[a-zA-Z_][a-zA-Z0-9_]*\>\(\s*[,=]\)\@!/ - -" and context modifiers -syn match jinjaStatement containedin=jinjaTagBlock contained /\/ - - -" Define the default highlighting. -" For version 5.7 and earlier: only when not done already -" For version 5.8 and later: only when an item doesn't have highlighting yet -if version >= 508 || !exists("did_jinja_syn_inits") - if version < 508 - let did_jinja_syn_inits = 1 - command -nargs=+ HiLink hi link - else - command -nargs=+ HiLink hi def link - endif - - HiLink jinjaPunctuation jinjaOperator - HiLink jinjaAttribute jinjaVariable - HiLink jinjaFunction jinjaFilter - - HiLink jinjaTagDelim jinjaTagBlock - HiLink jinjaVarDelim jinjaVarBlock - HiLink jinjaCommentDelim jinjaComment - HiLink jinjaRawDelim jinja - - HiLink jinjaSpecial Special - HiLink jinjaOperator Normal - HiLink jinjaRaw Normal - HiLink jinjaTagBlock PreProc - HiLink jinjaVarBlock PreProc - HiLink jinjaStatement Statement - HiLink jinjaFilter Function - HiLink jinjaBlockName Function - HiLink jinjaVariable Identifier - HiLink jinjaString Constant - HiLink jinjaNumber Constant - HiLink jinjaComment Comment - - delcommand HiLink -endif - -let b:current_syntax = "jinja" - -if main_syntax == 'jinja' - unlet main_syntax -endif diff --git a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/django2jinja.py b/deps/v8_inspector/third_party/jinja2/ext/django2jinja/django2jinja.py deleted file mode 100644 index ad9627ffbc3791..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/django2jinja.py +++ /dev/null @@ -1,768 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Django to Jinja - ~~~~~~~~~~~~~~~ - - Helper module that can convert django templates into Jinja2 templates. - - This file is not intended to be used as stand alone application but to - be used as library. To convert templates you basically create your own - writer, add extra conversion logic for your custom template tags, - configure your django environment and run the `convert_templates` - function. - - Here a simple example:: - - # configure django (or use settings.configure) - import os - os.environ['DJANGO_SETTINGS_MODULE'] = 'yourapplication.settings' - from yourapplication.foo.templatetags.bar import MyNode - - from django2jinja import Writer, convert_templates - - def write_my_node(writer, node): - writer.start_variable() - writer.write('myfunc(') - for idx, arg in enumerate(node.args): - if idx: - writer.write(', ') - writer.node(arg) - writer.write(')') - writer.end_variable() - - writer = Writer() - writer.node_handlers[MyNode] = write_my_node - convert_templates('/path/to/output/folder', writer=writer) - - Here is an example hos to automatically translate your django - variables to jinja2:: - - import re - # List of tuple (Match pattern, Replace pattern, Exclusion pattern) - - var_re = ((re.compile(r"(u|user)\.is_authenticated"), r"\1.is_authenticated()", None), - (re.compile(r"\.non_field_errors"), r".non_field_errors()", None), - (re.compile(r"\.label_tag"), r".label_tag()", None), - (re.compile(r"\.as_dl"), r".as_dl()", None), - (re.compile(r"\.as_table"), r".as_table()", None), - (re.compile(r"\.as_widget"), r".as_widget()", None), - (re.compile(r"\.as_hidden"), r".as_hidden()", None), - - (re.compile(r"\.get_([0-9_\w]+)_url"), r".get_\1_url()", None), - (re.compile(r"\.url"), r".url()", re.compile(r"(form|calendar).url")), - (re.compile(r"\.get_([0-9_\w]+)_display"), r".get_\1_display()", None), - (re.compile(r"loop\.counter"), r"loop.index", None), - (re.compile(r"loop\.revcounter"), r"loop.revindex", None), - (re.compile(r"request\.GET\.([0-9_\w]+)"), r"request.GET.get('\1', '')", None), - (re.compile(r"request\.get_host"), r"request.get_host()", None), - - (re.compile(r"\.all(?!_)"), r".all()", None), - (re.compile(r"\.all\.0"), r".all()[0]", None), - (re.compile(r"\.([0-9])($|\s+)"), r"[\1]\2", None), - (re.compile(r"\.items"), r".items()", None), - ) - writer = Writer(var_re=var_re) - - For details about the writing process have a look at the module code. - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -import re -import os -import sys -from jinja2.defaults import * -from django.conf import settings -from django.template import defaulttags as core_tags, loader, TextNode, \ - FilterExpression, libraries, Variable, loader_tags, TOKEN_TEXT, \ - TOKEN_VAR -from django.template.debug import DebugVariableNode as VariableNode -from django.templatetags import i18n as i18n_tags -from StringIO import StringIO - - -_node_handlers = {} -_resolved_filters = {} -_newline_re = re.compile(r'(?:\r\n|\r|\n)') - - -# Django stores an itertools object on the cycle node. Not only is this -# thread unsafe but also a problem for the converter which needs the raw -# string values passed to the constructor to create a jinja loop.cycle() -# call from it. -_old_cycle_init = core_tags.CycleNode.__init__ -def _fixed_cycle_init(self, cyclevars, variable_name=None): - self.raw_cycle_vars = map(Variable, cyclevars) - _old_cycle_init(self, cyclevars, variable_name) -core_tags.CycleNode.__init__ = _fixed_cycle_init - - -def node(cls): - def proxy(f): - _node_handlers[cls] = f - return f - return proxy - - -def convert_templates(output_dir, extensions=('.html', '.txt'), writer=None, - callback=None): - """Iterates over all templates in the template dirs configured and - translates them and writes the new templates into the output directory. - """ - if writer is None: - writer = Writer() - - def filter_templates(files): - for filename in files: - ifilename = filename.lower() - for extension in extensions: - if ifilename.endswith(extension): - yield filename - - def translate(f, loadname): - template = loader.get_template(loadname) - original = writer.stream - writer.stream = f - writer.body(template.nodelist) - writer.stream = original - - if callback is None: - def callback(template): - print template - - for directory in settings.TEMPLATE_DIRS: - for dirname, _, files in os.walk(directory): - dirname = dirname[len(directory) + 1:] - for filename in filter_templates(files): - source = os.path.normpath(os.path.join(dirname, filename)) - target = os.path.join(output_dir, dirname, filename) - basetarget = os.path.dirname(target) - if not os.path.exists(basetarget): - os.makedirs(basetarget) - callback(source) - f = file(target, 'w') - try: - translate(f, source) - finally: - f.close() - - -class Writer(object): - """The core writer class.""" - - def __init__(self, stream=None, error_stream=None, - block_start_string=BLOCK_START_STRING, - block_end_string=BLOCK_END_STRING, - variable_start_string=VARIABLE_START_STRING, - variable_end_string=VARIABLE_END_STRING, - comment_start_string=COMMENT_START_STRING, - comment_end_string=COMMENT_END_STRING, - initial_autoescape=True, - use_jinja_autoescape=False, - custom_node_handlers=None, - var_re=[], - env=None): - if stream is None: - stream = sys.stdout - if error_stream is None: - error_stream = sys.stderr - self.stream = stream - self.error_stream = error_stream - self.block_start_string = block_start_string - self.block_end_string = block_end_string - self.variable_start_string = variable_start_string - self.variable_end_string = variable_end_string - self.comment_start_string = comment_start_string - self.comment_end_string = comment_end_string - self.autoescape = initial_autoescape - self.spaceless = False - self.use_jinja_autoescape = use_jinja_autoescape - self.node_handlers = dict(_node_handlers, - **(custom_node_handlers or {})) - self._loop_depth = 0 - self._filters_warned = set() - self.var_re = var_re - self.env = env - - def enter_loop(self): - """Increments the loop depth so that write functions know if they - are in a loop. - """ - self._loop_depth += 1 - - def leave_loop(self): - """Reverse of enter_loop.""" - self._loop_depth -= 1 - - @property - def in_loop(self): - """True if we are in a loop.""" - return self._loop_depth > 0 - - def write(self, s): - """Writes stuff to the stream.""" - self.stream.write(s.encode(settings.FILE_CHARSET)) - - def print_expr(self, expr): - """Open a variable tag, write to the string to the stream and close.""" - self.start_variable() - self.write(expr) - self.end_variable() - - def _post_open(self): - if self.spaceless: - self.write('- ') - else: - self.write(' ') - - def _pre_close(self): - if self.spaceless: - self.write(' -') - else: - self.write(' ') - - def start_variable(self): - """Start a variable.""" - self.write(self.variable_start_string) - self._post_open() - - def end_variable(self, always_safe=False): - """End a variable.""" - if not always_safe and self.autoescape and \ - not self.use_jinja_autoescape: - self.write('|e') - self._pre_close() - self.write(self.variable_end_string) - - def start_block(self): - """Starts a block.""" - self.write(self.block_start_string) - self._post_open() - - def end_block(self): - """Ends a block.""" - self._pre_close() - self.write(self.block_end_string) - - def tag(self, name): - """Like `print_expr` just for blocks.""" - self.start_block() - self.write(name) - self.end_block() - - def variable(self, name): - """Prints a variable. This performs variable name transformation.""" - self.write(self.translate_variable_name(name)) - - def literal(self, value): - """Writes a value as literal.""" - value = repr(value) - if value[:2] in ('u"', "u'"): - value = value[1:] - self.write(value) - - def filters(self, filters, is_block=False): - """Dumps a list of filters.""" - want_pipe = not is_block - for filter, args in filters: - name = self.get_filter_name(filter) - if name is None: - self.warn('Could not find filter %s' % name) - continue - if name not in DEFAULT_FILTERS and \ - name not in self._filters_warned: - self._filters_warned.add(name) - self.warn('Filter %s probably doesn\'t exist in Jinja' % - name) - if not want_pipe: - want_pipe = True - else: - self.write('|') - self.write(name) - if args: - self.write('(') - for idx, (is_var, value) in enumerate(args): - if idx: - self.write(', ') - if is_var: - self.node(value) - else: - self.literal(value) - self.write(')') - - def get_location(self, origin, position): - """Returns the location for an origin and position tuple as name - and lineno. - """ - if hasattr(origin, 'source'): - source = origin.source - name = '' - else: - source = origin.loader(origin.loadname, origin.dirs)[0] - name = origin.loadname - lineno = len(_newline_re.findall(source[:position[0]])) + 1 - return name, lineno - - def warn(self, message, node=None): - """Prints a warning to the error stream.""" - if node is not None and hasattr(node, 'source'): - filename, lineno = self.get_location(*node.source) - message = '[%s:%d] %s' % (filename, lineno, message) - print >> self.error_stream, message - - def translate_variable_name(self, var): - """Performs variable name translation.""" - if self.in_loop and var == 'forloop' or var.startswith('forloop.'): - var = var[3:] - - for reg, rep, unless in self.var_re: - no_unless = unless and unless.search(var) or True - if reg.search(var) and no_unless: - var = reg.sub(rep, var) - break - return var - - def get_filter_name(self, filter): - """Returns the filter name for a filter function or `None` if there - is no such filter. - """ - if filter not in _resolved_filters: - for library in libraries.values(): - for key, value in library.filters.iteritems(): - _resolved_filters[value] = key - return _resolved_filters.get(filter, None) - - def node(self, node): - """Invokes the node handler for a node.""" - for cls, handler in self.node_handlers.iteritems(): - if type(node) is cls or type(node).__name__ == cls: - handler(self, node) - break - else: - self.warn('Untranslatable node %s.%s found' % ( - node.__module__, - node.__class__.__name__ - ), node) - - def body(self, nodes): - """Calls node() for every node in the iterable passed.""" - for node in nodes: - self.node(node) - - -@node(TextNode) -def text_node(writer, node): - writer.write(node.s) - - -@node(Variable) -def variable(writer, node): - if node.translate: - writer.warn('i18n system used, make sure to install translations', node) - writer.write('_(') - if node.literal is not None: - writer.literal(node.literal) - else: - writer.variable(node.var) - if node.translate: - writer.write(')') - - -@node(VariableNode) -def variable_node(writer, node): - writer.start_variable() - if node.filter_expression.var.var == 'block.super' \ - and not node.filter_expression.filters: - writer.write('super()') - else: - writer.node(node.filter_expression) - writer.end_variable() - - -@node(FilterExpression) -def filter_expression(writer, node): - writer.node(node.var) - writer.filters(node.filters) - - -@node(core_tags.CommentNode) -def comment_tag(writer, node): - pass - - -@node(core_tags.DebugNode) -def comment_tag(writer, node): - writer.warn('Debug tag detected. Make sure to add a global function ' - 'called debug to the namespace.', node=node) - writer.print_expr('debug()') - - -@node(core_tags.ForNode) -def for_loop(writer, node): - writer.start_block() - writer.write('for ') - for idx, var in enumerate(node.loopvars): - if idx: - writer.write(', ') - writer.variable(var) - writer.write(' in ') - if node.is_reversed: - writer.write('(') - writer.node(node.sequence) - if node.is_reversed: - writer.write(')|reverse') - writer.end_block() - writer.enter_loop() - writer.body(node.nodelist_loop) - writer.leave_loop() - writer.tag('endfor') - - -@node(core_tags.IfNode) -def if_condition(writer, node): - writer.start_block() - writer.write('if ') - join_with = 'and' - if node.link_type == core_tags.IfNode.LinkTypes.or_: - join_with = 'or' - - for idx, (ifnot, expr) in enumerate(node.bool_exprs): - if idx: - writer.write(' %s ' % join_with) - if ifnot: - writer.write('not ') - writer.node(expr) - writer.end_block() - writer.body(node.nodelist_true) - if node.nodelist_false: - writer.tag('else') - writer.body(node.nodelist_false) - writer.tag('endif') - - -@node(core_tags.IfEqualNode) -def if_equal(writer, node): - writer.start_block() - writer.write('if ') - writer.node(node.var1) - if node.negate: - writer.write(' != ') - else: - writer.write(' == ') - writer.node(node.var2) - writer.end_block() - writer.body(node.nodelist_true) - if node.nodelist_false: - writer.tag('else') - writer.body(node.nodelist_false) - writer.tag('endif') - - -@node(loader_tags.BlockNode) -def block(writer, node): - writer.tag('block ' + node.name.replace('-', '_').rstrip('_')) - node = node - while node.parent is not None: - node = node.parent - writer.body(node.nodelist) - writer.tag('endblock') - - -@node(loader_tags.ExtendsNode) -def extends(writer, node): - writer.start_block() - writer.write('extends ') - if node.parent_name_expr: - writer.node(node.parent_name_expr) - else: - writer.literal(node.parent_name) - writer.end_block() - writer.body(node.nodelist) - - -@node(loader_tags.ConstantIncludeNode) -@node(loader_tags.IncludeNode) -def include(writer, node): - writer.start_block() - writer.write('include ') - if hasattr(node, 'template'): - writer.literal(node.template.name) - else: - writer.node(node.template_name) - writer.end_block() - - -@node(core_tags.CycleNode) -def cycle(writer, node): - if not writer.in_loop: - writer.warn('Untranslatable free cycle (cycle outside loop)', node=node) - return - if node.variable_name is not None: - writer.start_block() - writer.write('set %s = ' % node.variable_name) - else: - writer.start_variable() - writer.write('loop.cycle(') - for idx, var in enumerate(node.raw_cycle_vars): - if idx: - writer.write(', ') - writer.node(var) - writer.write(')') - if node.variable_name is not None: - writer.end_block() - else: - writer.end_variable() - - -@node(core_tags.FilterNode) -def filter(writer, node): - writer.start_block() - writer.write('filter ') - writer.filters(node.filter_expr.filters, True) - writer.end_block() - writer.body(node.nodelist) - writer.tag('endfilter') - - -@node(core_tags.AutoEscapeControlNode) -def autoescape_control(writer, node): - original = writer.autoescape - writer.autoescape = node.setting - writer.body(node.nodelist) - writer.autoescape = original - - -@node(core_tags.SpacelessNode) -def spaceless(writer, node): - original = writer.spaceless - writer.spaceless = True - writer.warn('entering spaceless mode with different semantics', node) - # do the initial stripping - nodelist = list(node.nodelist) - if nodelist: - if isinstance(nodelist[0], TextNode): - nodelist[0] = TextNode(nodelist[0].s.lstrip()) - if isinstance(nodelist[-1], TextNode): - nodelist[-1] = TextNode(nodelist[-1].s.rstrip()) - writer.body(nodelist) - writer.spaceless = original - - -@node(core_tags.TemplateTagNode) -def template_tag(writer, node): - tag = { - 'openblock': writer.block_start_string, - 'closeblock': writer.block_end_string, - 'openvariable': writer.variable_start_string, - 'closevariable': writer.variable_end_string, - 'opencomment': writer.comment_start_string, - 'closecomment': writer.comment_end_string, - 'openbrace': '{', - 'closebrace': '}' - }.get(node.tagtype) - if tag: - writer.start_variable() - writer.literal(tag) - writer.end_variable() - - -@node(core_tags.URLNode) -def url_tag(writer, node): - writer.warn('url node used. make sure to provide a proper url() ' - 'function', node) - if node.asvar: - writer.start_block() - writer.write('set %s = ' % node.asvar) - else: - writer.start_variable() - autoescape = writer.autoescape - writer.write('url(') - writer.literal(node.view_name) - for arg in node.args: - writer.write(', ') - writer.node(arg) - for key, arg in node.kwargs.items(): - writer.write(', %s=' % key) - writer.node(arg) - writer.write(')') - if node.asvar: - writer.end_block() - else: - writer.end_variable() - - -@node(core_tags.WidthRatioNode) -def width_ratio(writer, node): - writer.warn('widthratio expanded into formula. You may want to provide ' - 'a helper function for this calculation', node) - writer.start_variable() - writer.write('(') - writer.node(node.val_expr) - writer.write(' / ') - writer.node(node.max_expr) - writer.write(' * ') - writer.write(str(int(node.max_width))) - writer.write(')|round|int') - writer.end_variable(always_safe=True) - - -@node(core_tags.WithNode) -def with_block(writer, node): - writer.warn('with block expanded into set statement. This could cause ' - 'variables following that block to be overridden.', node) - writer.start_block() - writer.write('set %s = ' % node.name) - writer.node(node.var) - writer.end_block() - writer.body(node.nodelist) - - -@node(core_tags.RegroupNode) -def regroup(writer, node): - if node.expression.var.literal: - writer.warn('literal in groupby filter used. Behavior in that ' - 'situation is undefined and translation is skipped.', node) - return - elif node.expression.filters: - writer.warn('filters in groupby filter used. Behavior in that ' - 'situation is undefined which is most likely a bug ' - 'in your code. Filters were ignored.', node) - writer.start_block() - writer.write('set %s = ' % node.var_name) - writer.node(node.target) - writer.write('|groupby(') - writer.literal(node.expression.var.var) - writer.write(')') - writer.end_block() - - -@node(core_tags.LoadNode) -def warn_load(writer, node): - writer.warn('load statement used which was ignored on conversion', node) - - -@node(i18n_tags.GetAvailableLanguagesNode) -def get_available_languages(writer, node): - writer.warn('make sure to provide a get_available_languages function', node) - writer.tag('set %s = get_available_languages()' % - writer.translate_variable_name(node.variable)) - - -@node(i18n_tags.GetCurrentLanguageNode) -def get_current_language(writer, node): - writer.warn('make sure to provide a get_current_language function', node) - writer.tag('set %s = get_current_language()' % - writer.translate_variable_name(node.variable)) - - -@node(i18n_tags.GetCurrentLanguageBidiNode) -def get_current_language_bidi(writer, node): - writer.warn('make sure to provide a get_current_language_bidi function', node) - writer.tag('set %s = get_current_language_bidi()' % - writer.translate_variable_name(node.variable)) - - -@node(i18n_tags.TranslateNode) -def simple_gettext(writer, node): - writer.warn('i18n system used, make sure to install translations', node) - writer.start_variable() - writer.write('_(') - writer.node(node.value) - writer.write(')') - writer.end_variable() - - -@node(i18n_tags.BlockTranslateNode) -def translate_block(writer, node): - first_var = [] - variables = set() - - def touch_var(name): - variables.add(name) - if not first_var: - first_var.append(name) - - def dump_token_list(tokens): - for token in tokens: - if token.token_type == TOKEN_TEXT: - writer.write(token.contents) - elif token.token_type == TOKEN_VAR: - writer.print_expr(token.contents) - touch_var(token.contents) - - writer.warn('i18n system used, make sure to install translations', node) - writer.start_block() - writer.write('trans') - idx = -1 - for idx, (key, var) in enumerate(node.extra_context.items()): - if idx: - writer.write(',') - writer.write(' %s=' % key) - touch_var(key) - writer.node(var.filter_expression) - - have_plural = False - plural_var = None - if node.plural and node.countervar and node.counter: - have_plural = True - plural_var = node.countervar - if plural_var not in variables: - if idx > -1: - writer.write(',') - touch_var(plural_var) - writer.write(' %s=' % plural_var) - writer.node(node.counter) - - writer.end_block() - dump_token_list(node.singular) - if node.plural and node.countervar and node.counter: - writer.start_block() - writer.write('pluralize') - if node.countervar != first_var[0]: - writer.write(' ' + node.countervar) - writer.end_block() - dump_token_list(node.plural) - writer.tag('endtrans') - -@node("SimpleNode") -def simple_tag(writer, node): - """Check if the simple tag exist as a filter in """ - name = node.tag_name - if writer.env and \ - name not in writer.env.filters and \ - name not in writer._filters_warned: - writer._filters_warned.add(name) - writer.warn('Filter %s probably doesn\'t exist in Jinja' % - name) - - if not node.vars_to_resolve: - # No argument, pass the request - writer.start_variable() - writer.write('request|') - writer.write(name) - writer.end_variable() - return - - first_var = node.vars_to_resolve[0] - args = node.vars_to_resolve[1:] - writer.start_variable() - - # Copied from Writer.filters() - writer.node(first_var) - - writer.write('|') - writer.write(name) - if args: - writer.write('(') - for idx, var in enumerate(args): - if idx: - writer.write(', ') - if var.var: - writer.node(var) - else: - writer.literal(var.literal) - writer.write(')') - writer.end_variable() - -# get rid of node now, it shouldn't be used normally -del node diff --git a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/example.py b/deps/v8_inspector/third_party/jinja2/ext/django2jinja/example.py deleted file mode 100644 index 2d4ab9add849a8..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/example.py +++ /dev/null @@ -1,7 +0,0 @@ -from django.conf import settings -settings.configure(TEMPLATE_DIRS=['templates'], TEMPLATE_DEBUG=True) - -from django2jinja import convert_templates, Writer - -writer = Writer(use_jinja_autoescape=True) -convert_templates('converted', writer=writer) diff --git a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/index.html b/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/index.html deleted file mode 100644 index d0fbe3854d4bb6..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/index.html +++ /dev/null @@ -1,58 +0,0 @@ -{% extends "layout.html" %} -{% load i18n %} -{% block title %}Foo{% endblock %} -{% block page-body %} - {{ block.super }} - Hello {{ name|cut:"d" }}! - - {% for item in seq reversed %} - {% if forloop.index|divisibleby:2 %} -
  • {{ item }}
  • - {% endif %} - {% endfor %} - {% ifequal foo bar %} - haha - {% else %} - hmm - {% endifequal %} - {% filter upper %} - {% include "subtemplate.html" %} - {% include foo %} - {% endfilter %} - {% spaceless %} - Hello World - {{ foo }} - Hmm - {% endspaceless %} - {% templatetag opencomment %}...{% templatetag closecomment %} - {% url foo a, b, c=d %} - {% url foo a, b, c=d as hmm %} - - {% with object.value as value %} - - {% endwith %} - -
    {% debug %}
    - - {% blocktrans with book|title as book_t and author|title as author_t %} - This is {{ book_t }} by {{ author_t }} - {% endblocktrans %} - - {% blocktrans count list|length as counter %} - There is only one {{ name }} object. - {% plural %} - There are {{ counter }} {{ name }} objects. - {% endblocktrans %} - - {% blocktrans with name|escape as name count list|length as counter %} - There is only one {{ name }} object. - {% plural %} - There are {{ counter }} {{ name }} objects. - {% endblocktrans %} - - {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %} - -

    {% trans "This is the title." %}

    - - {% regroup people by gender as grouped %} -{% endblock %} diff --git a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/layout.html b/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/layout.html deleted file mode 100644 index 3f21a122df85e4..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/layout.html +++ /dev/null @@ -1,4 +0,0 @@ -{% block title %}{% endblock %} -
    - {% block page-body %}{% endblock %} -
    diff --git a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/subtemplate.html b/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/subtemplate.html deleted file mode 100644 index 980a0d5f19a64b..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/django2jinja/templates/subtemplate.html +++ /dev/null @@ -1 +0,0 @@ -Hello World! diff --git a/deps/v8_inspector/third_party/jinja2/ext/djangojinja2.py b/deps/v8_inspector/third_party/jinja2/ext/djangojinja2.py deleted file mode 100644 index c7b4884d725a36..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/djangojinja2.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -""" - djangojinja2 - ~~~~~~~~~~~~ - - Adds support for Jinja2 to Django. - - Configuration variables: - - ======================= ============================================= - Key Description - ======================= ============================================= - `JINJA2_TEMPLATE_DIRS` List of template folders - `JINJA2_EXTENSIONS` List of Jinja2 extensions to use - `JINJA2_CACHE_SIZE` The size of the Jinja2 template cache. - ======================= ============================================= - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -from itertools import chain -from django.conf import settings -from django.http import HttpResponse -from django.core.exceptions import ImproperlyConfigured -from django.template.context import get_standard_processors -from django.template import TemplateDoesNotExist -from jinja2 import Environment, FileSystemLoader, TemplateNotFound -from jinja2.defaults import DEFAULT_NAMESPACE - - -# the environment is unconfigured until the first template is loaded. -_jinja_env = None - - -def get_env(): - """Get the Jinja2 env and initialize it if necessary.""" - global _jinja_env - if _jinja_env is None: - _jinja_env = create_env() - return _jinja_env - - -def create_env(): - """Create a new Jinja2 environment.""" - searchpath = list(settings.JINJA2_TEMPLATE_DIRS) - return Environment(loader=FileSystemLoader(searchpath), - auto_reload=settings.TEMPLATE_DEBUG, - cache_size=getattr(settings, 'JINJA2_CACHE_SIZE', 400), - extensions=getattr(settings, 'JINJA2_EXTENSIONS', ())) - - -def get_template(template_name, globals=None): - """Load a template.""" - try: - return get_env().get_template(template_name, globals=globals) - except TemplateNotFound, e: - raise TemplateDoesNotExist(str(e)) - - -def select_template(templates, globals=None): - """Try to load one of the given templates.""" - env = get_env() - for template in templates: - try: - return env.get_template(template, globals=globals) - except TemplateNotFound: - continue - raise TemplateDoesNotExist(', '.join(templates)) - - -def render_to_string(template_name, context=None, request=None, - processors=None): - """Render a template into a string.""" - context = dict(context or {}) - if request is not None: - context['request'] = request - for processor in chain(get_standard_processors(), processors or ()): - context.update(processor(request)) - return get_template(template_name).render(context) - - -def render_to_response(template_name, context=None, request=None, - processors=None, mimetype=None): - """Render a template into a response object.""" - return HttpResponse(render_to_string(template_name, context, request, - processors), mimetype=mimetype) diff --git a/deps/v8_inspector/third_party/jinja2/ext/inlinegettext.py b/deps/v8_inspector/third_party/jinja2/ext/inlinegettext.py deleted file mode 100644 index cf4ed5e4418cd6..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/ext/inlinegettext.py +++ /dev/null @@ -1,78 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Inline Gettext - ~~~~~~~~~~~~~~ - - An example extension for Jinja2 that supports inline gettext calls. - Requires the i18n extension to be loaded. - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -import re -from jinja2.ext import Extension -from jinja2.lexer import Token, count_newlines -from jinja2.exceptions import TemplateSyntaxError - - -_outside_re = re.compile(r'\\?(gettext|_)\(') -_inside_re = re.compile(r'\\?[()]') - - -class InlineGettext(Extension): - """This extension implements support for inline gettext blocks:: - -

    _(Welcome)

    -

    _(This is a paragraph)

    - - Requires the i18n extension to be loaded and configured. - """ - - def filter_stream(self, stream): - paren_stack = 0 - - for token in stream: - if token.type is not 'data': - yield token - continue - - pos = 0 - lineno = token.lineno - - while 1: - if not paren_stack: - match = _outside_re.search(token.value, pos) - else: - match = _inside_re.search(token.value, pos) - if match is None: - break - new_pos = match.start() - if new_pos > pos: - preval = token.value[pos:new_pos] - yield Token(lineno, 'data', preval) - lineno += count_newlines(preval) - gtok = match.group() - if gtok[0] == '\\': - yield Token(lineno, 'data', gtok[1:]) - elif not paren_stack: - yield Token(lineno, 'block_begin', None) - yield Token(lineno, 'name', 'trans') - yield Token(lineno, 'block_end', None) - paren_stack = 1 - else: - if gtok == '(' or paren_stack > 1: - yield Token(lineno, 'data', gtok) - paren_stack += gtok == ')' and -1 or 1 - if not paren_stack: - yield Token(lineno, 'block_begin', None) - yield Token(lineno, 'name', 'endtrans') - yield Token(lineno, 'block_end', None) - pos = match.end() - - if pos < len(token.value): - yield Token(lineno, 'data', token.value[pos:]) - - if paren_stack: - raise TemplateSyntaxError('unclosed gettext expression', - token.lineno, stream.name, - stream.filename) diff --git a/deps/v8_inspector/third_party/jinja2/scripts/jinja2-debug.py b/deps/v8_inspector/third_party/jinja2/scripts/jinja2-debug.py deleted file mode 100755 index d052adc37e5753..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/scripts/jinja2-debug.py +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - Jinja2 Debug Interface - ~~~~~~~~~~~~~~~~~~~~~~ - - Helper script for internal Jinja2 debugging. Requires Werkzeug. - - :copyright: Copyright 2010 by Armin Ronacher. - :license: BSD. -""" -import sys -import jinja2 -from werkzeug import script - -env = jinja2.Environment(extensions=['jinja2.ext.i18n', 'jinja2.ext.do', - 'jinja2.ext.loopcontrols', - 'jinja2.ext.with_', - 'jinja2.ext.autoescape'], - autoescape=True) - -def shell_init_func(): - def _compile(x): - print(env.compile(x, raw=True)) - result = { - 'e': env, - 'c': _compile, - 't': env.from_string, - 'p': env.parse - } - for key in jinja2.__all__: - result[key] = getattr(jinja2, key) - return result - - -def action_compile(): - print(env.compile(sys.stdin.read(), raw=True)) - -action_shell = script.make_shell(shell_init_func) - - -if __name__ == '__main__': - script.run() diff --git a/deps/v8_inspector/third_party/jinja2/scripts/make-release.py b/deps/v8_inspector/third_party/jinja2/scripts/make-release.py deleted file mode 100644 index 6fd98fed546a3d..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/scripts/make-release.py +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -""" - make-release - ~~~~~~~~~~~~ - - Helper script that performs a release. Does pretty much everything - automatically for us. - - :copyright: (c) 2011 by Armin Ronacher. - :license: BSD, see LICENSE for more details. -""" -import sys -import os -import re -from datetime import datetime, date -from subprocess import Popen, PIPE - -try: - import wheel -except ImportError: - wheel = None - -_date_strip_re = re.compile(r'(?<=\d)(st|nd|rd|th)') - - -def parse_changelog(): - with open('CHANGES') as f: - lineiter = iter(f) - for line in lineiter: - match = re.search('^Version\s+(.*)', line.strip()) - if match is None: - continue - length = len(match.group(1)) - version = match.group(1).strip() - if lineiter.next().count('-') != len(match.group(0)): - continue - while 1: - change_info = lineiter.next().strip() - if change_info: - break - - match = re.search(r'(?:codename (.*),\s*)?' - r'released on (\w+\s+\d+\w+\s+\d+)(?i)', - change_info) - if match is None: - continue - - codename, datestr = match.groups() - return version, parse_date(datestr), codename - - -def bump_version(version): - try: - parts = map(int, version.split('.')) - except ValueError: - fail('Current version is not numeric') - parts[-1] += 1 - return '.'.join(map(str, parts)) - - -def parse_date(string): - string = _date_strip_re.sub('', string) - return datetime.strptime(string, '%B %d %Y') - - -def set_filename_version(filename, version_number, pattern): - changed = [] - def inject_version(match): - before, old, after = match.groups() - changed.append(True) - return before + version_number + after - with open(filename) as f: - contents = re.sub(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, - inject_version, f.read()) - - if not changed: - fail('Could not find %s in %s', pattern, filename) - - with open(filename, 'w') as f: - f.write(contents) - - -def set_init_version(version): - info('Setting __init__.py version to %s', version) - set_filename_version('jinja2/__init__.py', version, '__version__') - - -def set_setup_version(version): - info('Setting setup.py version to %s', version) - set_filename_version('setup.py', version, 'version') - - -def build_and_upload(): - cmd = [sys.executable, 'setup.py', 'release', 'sdist', 'bdist_wheel', 'upload'] - if wheel is not None: - cmd.insert(4, 'bdist_wheel') - Popen(cmd).wait() - - -def fail(message, *args): - print >> sys.stderr, 'Error:', message % args - sys.exit(1) - - -def info(message, *args): - print >> sys.stderr, message % args - - -def get_git_tags(): - return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines()) - - -def git_is_clean(): - return Popen(['git', 'diff', '--quiet']).wait() == 0 - - -def make_git_commit(message, *args): - message = message % args - Popen(['git', 'commit', '-am', message]).wait() - - -def make_git_tag(tag): - info('Tagging "%s"', tag) - Popen(['git', 'tag', tag]).wait() - - -def main(): - os.chdir(os.path.join(os.path.dirname(__file__), '..')) - - rv = parse_changelog() - if rv is None: - fail('Could not parse changelog') - - version, release_date, codename = rv - dev_version = bump_version(version) + '.dev' - - info('Releasing %s (codename %s, release date %s)', - version, codename, release_date.strftime('%d/%m/%Y')) - tags = get_git_tags() - - if version in tags: - fail('Version "%s" is already tagged', version) - if release_date.date() != date.today(): - fail('Release date is not today (%s != %s)', release_date.date(), date.today()) - - if not git_is_clean(): - fail('You have uncommitted changes in git') - - if wheel is None: - print ('Warning: You need to install the wheel package ' - 'to upload a wheel distribution.') - - set_init_version(version) - set_setup_version(version) - make_git_commit('Bump version number to %s', version) - make_git_tag(version) - build_and_upload() - set_init_version(dev_version) - set_setup_version(dev_version) - - -if __name__ == '__main__': - main() diff --git a/deps/v8_inspector/third_party/jinja2/scripts/pylintrc b/deps/v8_inspector/third_party/jinja2/scripts/pylintrc deleted file mode 100644 index 4f85b49066fe0b..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/scripts/pylintrc +++ /dev/null @@ -1,301 +0,0 @@ -# lint Python modules using external checkers. -# -# This is the main checker controling the other ones and the reports -# generation. It is itself both a raw checker and an astng checker in order -# to: -# * handle message activation / deactivation at the module level -# * handle some basic but necessary stats'data (number of classes, methods...) -# -[MASTER] - -# Specify a configuration file. -#rcfile= - -# Profiled execution. -profile=no - -# Add to the black list. It should be a base name, not a -# path. You may set this option multiple times. -ignore=.svn - -# Pickle collected data for later comparisons. -persistent=yes - -# Set the cache size for astng objects. -cache-size=500 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins= - - -[MESSAGES CONTROL] - -# Enable only checker(s) with the given id(s). This option conflict with the -# disable-checker option -#enable-checker= - -# Enable all checker(s) except those with the given id(s). This option conflict -# with the disable-checker option -#disable-checker= - -# Enable all messages in the listed categories. -#enable-msg-cat= - -# Disable all messages in the listed categories. -#disable-msg-cat= - -# Enable the message(s) with the given id(s). -#enable-msg= - -# Disable the message(s) with the given id(s). -disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R0201 - - -[REPORTS] - -# set the output format. Available formats are text, parseable, colorized and -# html -output-format=colorized - -# Include message's id in output -include-ids=yes - -# Put messages in a separate file for each module / package specified on the -# command line instead of printing them on stdout. Reports (if any) will be -# written in a file name "pylint_global.[txt|html]". -files-output=no - -# Tells wether to display a full report or only the messages -reports=yes - -# Python expression which should return a note less than 10 (10 is the highest -# note).You have access to the variables errors warning, statement which -# respectivly contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (R0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Add a comment according to your evaluation note. This is used by the global -# evaluation report (R0004). -comment=no - -# Enable the report(s) with the given id(s). -#enable-report= - -# Disable the report(s) with the given id(s). -#disable-report= - - -# checks for -# * unused variables / imports -# * undefined variables -# * redefinition of variable from builtins or from an outer scope -# * use of variable before assigment -# -[VARIABLES] - -# Tells wether we should check for unused import in __init__ files. -init-import=no - -# A regular expression matching names used for dummy variables (i.e. not used). -dummy-variables-rgx=_|dummy - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - - -# try to find bugs in the code using type inference -# -[TYPECHECK] - -# Tells wether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# When zope mode is activated, consider the acquired-members option to ignore -# access to some undefined attributes. -zope=no - -# List of members which are usually get through zope's acquisition mecanism and -# so shouldn't trigger E0201 when accessed (need zope=yes to be considered). -acquired-members=REQUEST,acl_users,aq_parent - - -# checks for : -# * doc strings -# * modules / classes / functions / methods / arguments / variables name -# * number of arguments, local variables, branchs, returns and statements in -# functions, methods -# * required module attributes -# * dangerous default values as arguments -# * redefinition of function / method / class -# * uses of the global statement -# -[BASIC] - -# Required attributes for module, separated by a comma -required-attributes= - -# Regular expression which should only match functions or classes name which do -# not require a docstring -no-docstring-rgx=__.*__ - -# Regular expression which should only match correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Regular expression which should only match correct module level names -const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$ - -# Regular expression which should only match correct class names -class-rgx=[A-Z_][a-zA-Z0-9]+$ - -# Regular expression which should only match correct function names -function-rgx=[a-z_][a-z0-9_]*$ - -# Regular expression which should only match correct method names -method-rgx=[a-z_][a-z0-9_]*$ - -# Regular expression which should only match correct instance attribute names -attr-rgx=[a-z_][a-z0-9_]*$ - -# Regular expression which should only match correct argument names -argument-rgx=[a-z_][a-z0-9_]*$ - -# Regular expression which should only match correct variable names -variable-rgx=[a-z_][a-z0-9_]*$ - -# Regular expression which should only match correct list comprehension / -# generator expression variable names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Good variable names which should always be accepted, separated by a comma -good-names=i,j,k,ex,Run,_ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# List of builtins function names that should not be used, separated by a comma -bad-functions=apply,input - - -# checks for sign of poor/misdesign: -# * number of methods, attributes, local variables... -# * size, complexity of functions, methods -# -[DESIGN] - -# Maximum number of arguments for function / method -max-args=12 - -# Maximum number of locals for function / method body -max-locals=30 - -# Maximum number of return / yield for function / method body -max-returns=12 - -# Maximum number of branch for function / method body -max-branchs=30 - -# Maximum number of statements in function / method body -max-statements=60 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of attributes for a class (see R0902). -max-attributes=20 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=0 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - - -# checks for -# * external modules dependencies -# * relative / wildcard imports -# * cyclic imports -# * uses of deprecated modules -# -[IMPORTS] - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=regsub,string,TERMIOS,Bastion,rexec - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report R0402 must not be disabled) -import-graph= - -# Create a graph of external dependencies in the given file (report R0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of internal dependencies in the given file (report R0402 must -# not be disabled) -int-import-graph= - - -# checks for : -# * methods without self as first argument -# * overridden methods signature -# * access only to existant members via self -# * attributes not defined in the __init__ method -# * supported interfaces implementation -# * unreachable code -# -[CLASSES] - -# List of interface methods to ignore, separated by a comma. This is used for -# instance to not check methods defines in Zope's Interface base class. -ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - - -# checks for similarities and duplicated code. This computation may be -# memory / CPU intensive, so you should disable it if you experiments some -# problems. -# -[SIMILARITIES] - -# Minimum lines number of a similarity. -min-similarity-lines=10 - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - - -# checks for: -# * warning notes in the code like FIXME, XXX -# * PEP 263: source code with non ascii character but no encoding declaration -# -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -notes=FIXME,XXX,TODO - - -# checks for : -# * unauthorized constructions -# * strict indentation -# * line length -# * use of <> instead of != -# -[FORMAT] - -# Maximum number of characters on a single line. -max-line-length=90 - -# Maximum number of lines in a module -max-module-lines=1000 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' diff --git a/deps/v8_inspector/third_party/jinja2/setup.cfg b/deps/v8_inspector/third_party/jinja2/setup.cfg deleted file mode 100644 index 058cdfc1c68e17..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/setup.cfg +++ /dev/null @@ -1,8 +0,0 @@ -[wheel] -universal = 1 - -[aliases] -release = egg_info -RDb '' - -[pytest] -norecursedirs = .* *.egg *.egg-info env* artwork docs examples diff --git a/deps/v8_inspector/third_party/jinja2/setup.py b/deps/v8_inspector/third_party/jinja2/setup.py deleted file mode 100644 index 507fd073533fb9..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/setup.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Jinja2 -~~~~~~ - -Jinja2 is a template engine written in pure Python. It provides a -`Django`_ inspired non-XML syntax but supports inline expressions and -an optional `sandboxed`_ environment. - -Nutshell --------- - -Here a small example of a Jinja template:: - - {% extends 'base.html' %} - {% block title %}Memberlist{% endblock %} - {% block content %} - - {% endblock %} - -Philosophy ----------- - -Application logic is for the controller but don't try to make the life -for the template designer too hard by giving him too few functionality. - -For more informations visit the new `Jinja2 webpage`_ and `documentation`_. - -.. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security) -.. _Django: http://www.djangoproject.com/ -.. _Jinja2 webpage: http://jinja.pocoo.org/ -.. _documentation: http://jinja.pocoo.org/2/documentation/ -""" -from setuptools import setup - - -setup( - name='Jinja2', - version='2.9.dev', - url='http://jinja.pocoo.org/', - license='BSD', - author='Armin Ronacher', - author_email='armin.ronacher@active-4.com', - description='A small but fast and easy to use stand-alone template ' - 'engine written in pure python.', - long_description=__doc__, - # jinja is egg safe. But we hate eggs - zip_safe=False, - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Web Environment', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', - 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'Topic :: Text Processing :: Markup :: HTML' - ], - packages=['jinja2'], - install_requires=['MarkupSafe'], - extras_require={'i18n': ['Babel>=0.8']}, - include_package_data=True, - entry_points=""" - [babel.extractors] - jinja2 = jinja2.ext:babel_extract[i18n] - """ -) diff --git a/deps/v8_inspector/third_party/jinja2/tox.ini b/deps/v8_inspector/third_party/jinja2/tox.ini deleted file mode 100644 index 0daabf75b6160d..00000000000000 --- a/deps/v8_inspector/third_party/jinja2/tox.ini +++ /dev/null @@ -1,9 +0,0 @@ -[tox] -envlist = py26, py27, pypy, py33, py34, py35 - -[testenv] -commands = - py.test [] - -deps = - pytest diff --git a/deps/v8_inspector/third_party/markupsafe/.gitignore b/deps/v8_inspector/third_party/markupsafe/.gitignore deleted file mode 100644 index e3a879439104c2..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -.DS_Store -*.pyc -*.pyo -*.o -*.so -env -dist -build -.tox -*.egg-info diff --git a/deps/v8_inspector/third_party/markupsafe/.travis.yml b/deps/v8_inspector/third_party/markupsafe/.travis.yml deleted file mode 100644 index c0128baf9c546b..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -sudo: false -language: python -python: - - "2.6" - - "2.7" - - "3.3" - - "3.4" - - "3.5" -install: - - "python setup.py install" -script: make test diff --git a/deps/v8_inspector/third_party/markupsafe/CHANGES b/deps/v8_inspector/third_party/markupsafe/CHANGES deleted file mode 100644 index 706a230c754412..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/CHANGES +++ /dev/null @@ -1,48 +0,0 @@ -MarkupSafe Changelog -==================== - -Version 1.0 ------------ - -- Fixed custom types not invoking `__unicode__` when used - with `format()`. -- Added `__version__` module attribute -- Improve unescape code to leave lone ampersands alone. - -Version 0.18 ------------- - -- Fixed `__mul__` and string splitting on Python 3. - -Version 0.17 ------------- - -- Fixed a bug with broken interpolation on tuples. - -Version 0.16 ------------- - -- Improved Python 3 Support and removed 2to3 -- Removed support for Python 3.2 and 2.5 - -Version 0.15 ------------- - -- Fixed a typo that caused the library to fail to install - on pypy and jython -.- - -Version 0.14 ------------- - -- Release fix for 0.13. - -Version 0.13 ------------- - -- Do not attempt to compile extension for PyPy or Jython. -- Work around some 64bit Windows issues. - -Version 0.12 ------------- - -- improved PyPy compatibility diff --git a/deps/v8_inspector/third_party/markupsafe/MANIFEST.in b/deps/v8_inspector/third_party/markupsafe/MANIFEST.in deleted file mode 100644 index d50e4e0dc798d6..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include LICENSE README.rst AUTHORS -recursive-include markupsafe *.c diff --git a/deps/v8_inspector/third_party/markupsafe/Makefile b/deps/v8_inspector/third_party/markupsafe/Makefile deleted file mode 100644 index fd263b160a5e22..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -test: - python setup.py test - -tox-test: - tox - -.PYONY: test tox-test diff --git a/deps/v8_inspector/third_party/markupsafe/README.rst b/deps/v8_inspector/third_party/markupsafe/README.rst deleted file mode 100644 index 53dcd023a98924..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/README.rst +++ /dev/null @@ -1,101 +0,0 @@ -MarkupSafe -========== - -Implements a unicode subclass that supports HTML strings: - ->>> from markupsafe import Markup, escape ->>> escape("") -Markup(u'<script>alert(document.cookie);</script>') ->>> tmpl = Markup("%s") ->>> tmpl % "Peter > Lustig" -Markup(u'Peter > Lustig') - -If you want to make an object unicode that is not yet unicode -but don't want to lose the taint information, you can use the -`soft_unicode` function. (On Python 3 you can also use `soft_str` which -is a different name for the same function). - ->>> from markupsafe import soft_unicode ->>> soft_unicode(42) -u'42' ->>> soft_unicode(Markup('foo')) -Markup(u'foo') - -HTML Representations --------------------- - -Objects can customize their HTML markup equivalent by overriding -the `__html__` function: - ->>> class Foo(object): -... def __html__(self): -... return 'Nice' -... ->>> escape(Foo()) -Markup(u'Nice') ->>> Markup(Foo()) -Markup(u'Nice') - -Silent Escapes --------------- - -Since MarkupSafe 0.10 there is now also a separate escape function -called `escape_silent` that returns an empty string for `None` for -consistency with other systems that return empty strings for `None` -when escaping (for instance Pylons' webhelpers). - -If you also want to use this for the escape method of the Markup -object, you can create your own subclass that does that:: - - from markupsafe import Markup, escape_silent as escape - - class SilentMarkup(Markup): - __slots__ = () - - @classmethod - def escape(cls, s): - return cls(escape(s)) - -New-Style String Formatting ---------------------------- - -Starting with MarkupSafe 0.21 new style string formats from Python 2.6 and -3.x are now fully supported. Previously the escape behavior of those -functions was spotty at best. The new implementations operates under the -following algorithm: - -1. if an object has an ``__html_format__`` method it is called as - replacement for ``__format__`` with the format specifier. It either - has to return a string or markup object. -2. if an object has an ``__html__`` method it is called. -3. otherwise the default format system of Python kicks in and the result - is HTML escaped. - -Here is how you can implement your own formatting:: - - class User(object): - - def __init__(self, id, username): - self.id = id - self.username = username - - def __html_format__(self, format_spec): - if format_spec == 'link': - return Markup('{1}').format( - self.id, - self.__html__(), - ) - elif format_spec: - raise ValueError('Invalid format spec') - return self.__html__() - - def __html__(self): - return Markup('{0}').format(self.username) - -And to format that user: - ->>> user = User(1, 'foo') ->>> Markup('

    User: {0:link}').format(user) -Markup(u'

    User: foo') - -Markupsafe supports Python 2.6, 2.7 and Python 3.3 and higher. diff --git a/deps/v8_inspector/third_party/markupsafe/bench/bench_basic.py b/deps/v8_inspector/third_party/markupsafe/bench/bench_basic.py deleted file mode 100644 index 1172d150bb2721..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/bench/bench_basic.py +++ /dev/null @@ -1,5 +0,0 @@ -from markupsafe import escape - - -def run(): - escape('Hello World!') diff --git a/deps/v8_inspector/third_party/markupsafe/bench/bench_largestring.py b/deps/v8_inspector/third_party/markupsafe/bench/bench_largestring.py deleted file mode 100644 index 7bde595c10a8f8..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/bench/bench_largestring.py +++ /dev/null @@ -1,6 +0,0 @@ -from markupsafe import escape - - -def run(): - string = 'Hello World!' * 1000 - escape(string) diff --git a/deps/v8_inspector/third_party/markupsafe/bench/bench_long_empty_string.py b/deps/v8_inspector/third_party/markupsafe/bench/bench_long_empty_string.py deleted file mode 100644 index 320fb0a93bf7be..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/bench/bench_long_empty_string.py +++ /dev/null @@ -1,6 +0,0 @@ -from markupsafe import escape - - -def run(): - string = 'Hello World!' * 1000 - escape(string) diff --git a/deps/v8_inspector/third_party/markupsafe/bench/bench_long_suffix.py b/deps/v8_inspector/third_party/markupsafe/bench/bench_long_suffix.py deleted file mode 100644 index 43fe56371ea4d8..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/bench/bench_long_suffix.py +++ /dev/null @@ -1,6 +0,0 @@ -from markupsafe import escape - - -def run(): - string = 'Hello World!' + 'x' * 100000 - escape(string) diff --git a/deps/v8_inspector/third_party/markupsafe/bench/bench_short_empty_string.py b/deps/v8_inspector/third_party/markupsafe/bench/bench_short_empty_string.py deleted file mode 100644 index 91cccc49916f3d..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/bench/bench_short_empty_string.py +++ /dev/null @@ -1,5 +0,0 @@ -from markupsafe import escape - - -def run(): - escape('Hello World!') diff --git a/deps/v8_inspector/third_party/markupsafe/bench/runbench.py b/deps/v8_inspector/third_party/markupsafe/bench/runbench.py deleted file mode 100644 index 2ebdc53c58d467..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/bench/runbench.py +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env python -""" - Runs the benchmarks -""" -import sys -import os -import re -from subprocess import Popen - -_filename_re = re.compile(r'^bench_(.*?)\.py$') -bench_directory = os.path.abspath(os.path.dirname(__file__)) - - -def list_benchmarks(): - result = [] - for name in os.listdir(bench_directory): - match = _filename_re.match(name) - if match is not None: - result.append(match.group(1)) - result.sort(key=lambda x: (x.startswith('logging_'), x.lower())) - return result - - -def run_bench(name): - sys.stdout.write('%-32s' % name) - sys.stdout.flush() - Popen([sys.executable, '-mtimeit', '-s', - 'from bench_%s import run' % name, - 'run()']).wait() - - -def main(): - print '=' * 80 - print 'Running benchmark for MarkupSafe' - print '-' * 80 - os.chdir(bench_directory) - for bench in list_benchmarks(): - run_bench(bench) - print '-' * 80 - - -if __name__ == '__main__': - main() diff --git a/deps/v8_inspector/third_party/markupsafe/markupsafe/tests.py b/deps/v8_inspector/third_party/markupsafe/markupsafe/tests.py deleted file mode 100644 index f3e2379e0c8341..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/markupsafe/tests.py +++ /dev/null @@ -1,207 +0,0 @@ -# -*- coding: utf-8 -*- -import gc -import sys -import unittest -from markupsafe import Markup, escape, escape_silent -from markupsafe._compat import text_type, PY2 - - -class MarkupTestCase(unittest.TestCase): - - def test_adding(self): - # adding two strings should escape the unsafe one - unsafe = '' - safe = Markup('username') - assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe) - - def test_string_interpolation(self): - # string interpolations are safe to use too - assert Markup('%s') % '' == \ - '<bad user>' - assert Markup('%(username)s') % { - 'username': '' - } == '<bad user>' - - assert Markup('%i') % 3.14 == '3' - assert Markup('%.2f') % 3.14 == '3.14' - - def test_type_behavior(self): - # an escaped object is markup too - assert type(Markup('foo') + 'bar') is Markup - - # and it implements __html__ by returning itself - x = Markup("foo") - assert x.__html__() is x - - def test_html_interop(self): - # it also knows how to treat __html__ objects - class Foo(object): - def __html__(self): - return 'awesome' - def __unicode__(self): - return 'awesome' - __str__ = __unicode__ - assert Markup(Foo()) == 'awesome' - assert Markup('%s') % Foo() == \ - 'awesome' - - def test_tuple_interpol(self): - self.assertEqual(Markup('%s:%s') % ( - '', - '', - ), Markup(u'<foo>:<bar>')) - - def test_dict_interpol(self): - self.assertEqual(Markup('%(foo)s') % { - 'foo': '', - }, Markup(u'<foo>')) - self.assertEqual(Markup('%(foo)s:%(bar)s') % { - 'foo': '', - 'bar': '', - }, Markup(u'<foo>:<bar>')) - - def test_escaping(self): - # escaping - assert escape('"<>&\'') == '"<>&'' - assert Markup("Foo & Bar").striptags() == "Foo & Bar" - - def test_unescape(self): - assert Markup("<test>").unescape() == "" - assert "jack & tavi are cooler than mike & russ" == \ - Markup("jack & tavi are cooler than mike & russ").unescape(), \ - Markup("jack & tavi are cooler than mike & russ").unescape() - - # Test that unescape is idempotent - original = '&foo;' - once = Markup(original).unescape() - twice = Markup(once).unescape() - expected = "&foo;" - assert expected == once == twice, (once, twice) - - def test_formatting(self): - for actual, expected in ( - (Markup('%i') % 3.14, '3'), - (Markup('%.2f') % 3.14159, '3.14'), - (Markup('%s %s %s') % ('<', 123, '>'), '< 123 >'), - (Markup('{awesome}').format(awesome=''), - '<awesome>'), - (Markup('{0[1][bar]}').format([0, {'bar': ''}]), - '<bar/>'), - (Markup('{0[1][bar]}').format([0, {'bar': Markup('')}]), - '')): - assert actual == expected, "%r should be %r!" % (actual, expected) - - # This is new in 2.7 - if sys.version_info >= (2, 7): - def test_formatting_empty(self): - formatted = Markup('{}').format(0) - assert formatted == Markup('0') - - def test_custom_formatting(self): - class HasHTMLOnly(object): - def __html__(self): - return Markup('') - - class HasHTMLAndFormat(object): - def __html__(self): - return Markup('') - def __html_format__(self, spec): - return Markup('') - - assert Markup('{0}').format(HasHTMLOnly()) == Markup('') - assert Markup('{0}').format(HasHTMLAndFormat()) == Markup('') - - def test_complex_custom_formatting(self): - class User(object): - def __init__(self, id, username): - self.id = id - self.username = username - def __html_format__(self, format_spec): - if format_spec == 'link': - return Markup('{1}').format( - self.id, - self.__html__(), - ) - elif format_spec: - raise ValueError('Invalid format spec') - return self.__html__() - def __html__(self): - return Markup('{0}').format(self.username) - - user = User(1, 'foo') - assert Markup('

    User: {0:link}').format(user) == \ - Markup('

    User: foo') - - def test_formatting_with_objects(self): - class Stringable(object): - def __unicode__(self): - return u'строка' - if PY2: - def __str__(self): - return 'some other value' - else: - __str__ = __unicode__ - - assert Markup('{s}').format(s=Stringable()) == \ - Markup(u'строка') - - def test_all_set(self): - import markupsafe as markup - for item in markup.__all__: - getattr(markup, item) - - def test_escape_silent(self): - assert escape_silent(None) == Markup() - assert escape(None) == Markup(None) - assert escape_silent('') == Markup(u'<foo>') - - def test_splitting(self): - self.assertEqual(Markup('a b').split(), [ - Markup('a'), - Markup('b') - ]) - self.assertEqual(Markup('a b').rsplit(), [ - Markup('a'), - Markup('b') - ]) - self.assertEqual(Markup('a\nb').splitlines(), [ - Markup('a'), - Markup('b') - ]) - - def test_mul(self): - self.assertEqual(Markup('a') * 3, Markup('aaa')) - - -class MarkupLeakTestCase(unittest.TestCase): - - def test_markup_leaks(self): - counts = set() - for count in range(20): - for item in range(1000): - escape("foo") - escape("") - escape(u"foo") - escape(u"") - if hasattr(sys, 'pypy_version_info'): - gc.collect() - counts.add(len(gc.get_objects())) - assert len(counts) == 1, 'ouch, c extension seems to ' \ - 'leak objects, got: ' + str(len(counts)) - - -def suite(): - suite = unittest.TestSuite() - suite.addTest(unittest.makeSuite(MarkupTestCase)) - - # this test only tests the c extension - if not hasattr(escape, 'func_code'): - suite.addTest(unittest.makeSuite(MarkupLeakTestCase)) - - return suite - - -if __name__ == '__main__': - unittest.main(defaultTest='suite') - -# vim:sts=4:sw=4:et: diff --git a/deps/v8_inspector/third_party/markupsafe/setup.py b/deps/v8_inspector/third_party/markupsafe/setup.py deleted file mode 100644 index aff786d5e95301..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/setup.py +++ /dev/null @@ -1,133 +0,0 @@ -import os -import re -import ast -import sys -from setuptools import setup, Extension, Feature -from distutils.command.build_ext import build_ext -from distutils.errors import CCompilerError, DistutilsExecError, \ - DistutilsPlatformError - - -# fail safe compilation shamelessly stolen from the simplejson -# setup.py file. Original author: Bob Ippolito - -is_jython = 'java' in sys.platform -is_pypy = hasattr(sys, 'pypy_version_info') - -with open('markupsafe/__init__.py') as f: - version = ast.literal_eval(re.search( - '^__version__\s+=\s+(.*?)$(?sm)', f.read()).group(1)) - - -speedups = Feature( - 'optional C speed-enhancement module', - standard=True, - ext_modules=[ - Extension('markupsafe._speedups', ['markupsafe/_speedups.c']), - ], -) - -# Known errors when running build_ext.build_extension method -ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError) -if sys.platform == 'win32' and sys.version_info > (2, 6): - # 2.6's distutils.msvc9compiler can raise an IOError when failing to - # find the compiler - ext_errors += (IOError,) -# Known errors when running build_ext.run method -run_errors = (DistutilsPlatformError,) -if sys.platform == 'darwin': - run_errors += (SystemError,) - - -class BuildFailed(Exception): - pass - - -class ve_build_ext(build_ext): - """This class allows C extension building to fail.""" - - def run(self): - try: - build_ext.run(self) - except run_errors: - raise BuildFailed() - - def build_extension(self, ext): - try: - build_ext.build_extension(self, ext) - except ext_errors: - raise BuildFailed() - except ValueError: - # this can happen on Windows 64 bit, see Python issue 7511 - if "'path'" in str(sys.exc_info()[1]): # works with Python 2 and 3 - raise BuildFailed() - raise - - -def echo(msg=''): - sys.stdout.write(msg + '\n') - - -readme = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() - - -def run_setup(with_binary): - features = {} - if with_binary: - features['speedups'] = speedups - setup( - name='MarkupSafe', - version=version, - url='http://github.com/mitsuhiko/markupsafe', - license='BSD', - author='Armin Ronacher', - author_email='armin.ronacher@active-4.com', - description='Implements a XML/HTML/XHTML Markup safe string for Python', - long_description=readme, - zip_safe=False, - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Web Environment', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: BSD License', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3', - 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', - 'Topic :: Software Development :: Libraries :: Python Modules', - 'Topic :: Text Processing :: Markup :: HTML' - ], - packages=['markupsafe'], - test_suite='markupsafe.tests.suite', - include_package_data=True, - cmdclass={'build_ext': ve_build_ext}, - features=features, - ) - - -def try_building_extension(): - try: - run_setup(True) - except BuildFailed: - LINE = '=' * 74 - BUILD_EXT_WARNING = 'WARNING: The C extension could not be ' \ - 'compiled, speedups are not enabled.' - - echo(LINE) - echo(BUILD_EXT_WARNING) - echo('Failure information, if any, is above.') - echo('Retrying the build without the C extension now.') - echo() - - run_setup(False) - - echo(LINE) - echo(BUILD_EXT_WARNING) - echo('Plain-Python installation succeeded.') - echo(LINE) - - -if not (is_pypy or is_jython): - try_building_extension() -else: - run_setup(False) diff --git a/deps/v8_inspector/third_party/markupsafe/tox.ini b/deps/v8_inspector/third_party/markupsafe/tox.ini deleted file mode 100644 index 9b854eb2bf91d9..00000000000000 --- a/deps/v8_inspector/third_party/markupsafe/tox.ini +++ /dev/null @@ -1,5 +0,0 @@ -[tox] -envlist = py26, py27, pypy, py33, py34, py35 - -[testenv] -commands = python setup.py test diff --git a/node.gyp b/node.gyp index 0d5b6c27ef60d7..673a1d10effaa8 100644 --- a/node.gyp +++ b/node.gyp @@ -332,7 +332,7 @@ 'deps/v8/src/third_party/vtune/v8vtune.gyp:v8_vtune' ], }], - [ 'v8_inspector=="true"', { + [ 'v8_enable_inspector==1', { 'defines': [ 'HAVE_INSPECTOR=1', ], @@ -345,11 +345,9 @@ 'src/inspector_socket_server.h', ], 'dependencies': [ - 'deps/v8_inspector/src/inspector/inspector.gyp:standalone_inspector', 'v8_inspector_compress_protocol_json#host', ], 'include_dirs': [ - 'deps/v8_inspector/include', '<(SHARED_INTERMEDIATE_DIR)/include', # for inspector '<(SHARED_INTERMEDIATE_DIR)', ], @@ -692,13 +690,13 @@ 'type': 'none', 'toolsets': ['host'], 'conditions': [ - [ 'v8_inspector=="true"', { + [ 'v8_enable_inspector==1', { 'actions': [ { 'action_name': 'v8_inspector_compress_protocol_json', 'process_outputs_as_sources': 1, 'inputs': [ - 'deps/v8_inspector/src/inspector/js_protocol.json', + 'deps/v8/src/inspector/js_protocol.json', ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/v8_inspector_protocol_json.h', @@ -910,7 +908,7 @@ ], 'conditions': [ - ['v8_inspector=="true"', { + ['v8_enable_inspector==1', { 'defines': [ 'HAVE_INSPECTOR=1', ], diff --git a/src/node_version.h b/src/node_version.h index b7760cf04ba46d..6a83929a82e77d 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -52,6 +52,6 @@ * an API is broken in the C++ side, including in v8 or * other dependencies. */ -#define NODE_MODULE_VERSION 52 /* Node.js v8.0.0 */ +#define NODE_MODULE_VERSION 53 /* Node.js v8.0.0 */ #endif // SRC_NODE_VERSION_H_ diff --git a/test/parallel/test-intl-no-icu-data.js b/test/parallel/test-intl-no-icu-data.js index ce5e9a08121cdc..695a4698b56738 100644 --- a/test/parallel/test-intl-no-icu-data.js +++ b/test/parallel/test-intl-no-icu-data.js @@ -4,6 +4,5 @@ require('../common'); const assert = require('assert'); const config = process.binding('config'); -// No-op when ICU case mappings are unavailable. -assert.strictEqual('ç'.toLocaleUpperCase('el'), 'ç'); +assert.deepStrictEqual(Intl.NumberFormat.supportedLocalesOf('en'), []); assert.strictEqual(config.icuDataDir, 'test/fixtures/empty/'); diff --git a/tools/license-builder.sh b/tools/license-builder.sh index 8e20df02174d73..de06fdb2e2a2c5 100755 --- a/tools/license-builder.sh +++ b/tools/license-builder.sh @@ -80,15 +80,6 @@ addlicense "cpplint.py" "tools/cpplint.py" \ addlicense "ESLint" "tools/eslint" "$(cat ${rootdir}/tools/eslint/LICENSE)" addlicense "gtest" "deps/gtest" "$(cat ${rootdir}/deps/gtest/LICENSE)" -# v8_inspector -addlicense "v8_inspector" "deps/v8_inspector/third_party/v8_inspector" \ - "$(cat ${rootdir}/deps/v8_inspector/third_party/v8_inspector/LICENSE)" -# Build tooling for v8_inspector -addlicense "jinja2" "deps/v8_inspector/third_party/jinja2" \ - "$(cat ${rootdir}/deps/v8_inspector/third_party/jinja2/LICENSE)" -addlicense "markupsafe" "deps/v8_inspector/third_party/markupsafe" \ - "$(cat ${rootdir}/deps/v8_inspector/third_party/markupsafe/LICENSE)" - mv $tmplicense $licensefile