Upload Kmake

This commit is contained in:
Gorochu
2026-05-26 23:36:42 -07:00
parent ba051b2f74
commit 555ec72358
41615 changed files with 13344630 additions and 1 deletions

8
deps/v8/tools/profiling/README.md vendored Normal file
View File

@ -0,0 +1,8 @@
# Profiling Tools
This directory contains various helper scripts to assist with profiling
d8 and chrome.
## linux perf
For [linux perf](https://perf.wiki.kernel.org/) support you can find more
documentation and instructions at <https://v8.dev/docs/linux-perf>.

69
deps/v8/tools/profiling/android-ll-prof.sh vendored Executable file
View File

@ -0,0 +1,69 @@
#!/bin/bash
# Copyright 2012 the V8 project 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.
# Runs d8 with the given arguments on the device under 'perf' and
# processes the profiler trace and v8 logs using ll_prof.py.
#
# Usage:
# > ./tools/android-ll-prof.sh (debug|release) "args to d8" "args to ll_prof.py"
#
# The script creates deploy directory deploy/data/local/tmp/v8, copies there
# the d8 binary either from out/android_arm.release or out/android_arm.debug,
# and then sync the deploy directory with /data/local/tmp/v8 on the device.
# You can put JS files in the deploy directory before running the script.
# Note: $ANDROID_NDK_ROOT must be set.
MODE=$1
RUN_ARGS=$2
LL_PROF_ARGS=$3
BASE=`cd $(dirname "$0")/..; pwd`
DEPLOY="$BASE/deploy"
set +e
mkdir -p "$DEPLOY/data/local/tmp/v8"
cp "$BASE/out/android_arm.$MODE/d8" "$DEPLOY/data/local/tmp/v8/d8"
adb -p "$DEPLOY" sync data
adb shell "cd /data/local/tmp/v8;\
perf record -R -e cycles -c 10000 -f -i \
./d8 --ll_prof --gc-fake-mmap=/data/local/tmp/__v8_gc__ $RUN_ARGS"
adb pull /data/local/tmp/v8/v8.log .
adb pull /data/local/tmp/v8/v8.log.ll .
adb pull /data/perf.data .
ARCH=arm-linux-androideabi-4.6
TOOLCHAIN="${ANDROID_NDK_ROOT}/toolchains/$ARCH/prebuilt/linux-x86/bin"
$BASE/tools/ll_prof.py --host-root="$BASE/deploy" \
--gc-fake-mmap=/data/local/tmp/__v8_gc__ \
--objdump="$TOOLCHAIN/arm-linux-androideabi-objdump" \
$LL_PROF_ARGS

View File

@ -0,0 +1,103 @@
#!/usr/bin/env bash
# Copyright 2022 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.
PERF_DATA_DIR="."
PERF_DATA_PREFIX="chrome_renderer"
PERF_CLOCKID="mono"
PERF_CALL_GRAPH="fp"
PERF_FREQ_DEFAULT=10000
PERF_FREQ=""
PERF_COUNT=""
PERF_RAW_ARGS=""
RENDERER_ID="0"
for i in "$@"; do
case $i in
-h|--help)
cat <<EOF
Usage: path/to/chrome --renderer-cmd-prefix='$0 [OPTION]' [CHROME OPTIONS]
This script is mostly used in conjuction with linux_perf.py to run linux-perf
for each renderer process.
It generates perf.data files that can be read by pprof or linux-perf.
File naming: \$OUT_DIR/\$PREFIX_\$PARENT_PID_\$RENDERER_ID.perf.data
Options:
--perf-data-dir=OUT_DIR Change the location where perf.data is written.
Default: '${PERF_DATA_DIR}'
--perf-data-prefix=PREFIX Set a custom prefix for all generated
perf.data files.
Default: '${PERF_DATA_PREFIX}'
Pass-though Options:
--perf-count=SAMPLE_DELTA Forwards options to 'perf record --count'
Default: not used
--perf-freq=FREQUENCY Forwards options to 'perf record --freq'
Default: ${PERF_FREQ_DEFAULT}
--perf-clockid=CLOCK_TYPE Forwards options to 'perf record --clockid'
Default: '${PERF_CLOCKID}'
--perf-call-graph=MODE Forwards options to 'perf record --call-graph'
Default: '${PERF_CALL_GRAPH}'
--perf-args=ARGS Forwards raw options to 'perf record \$ARGS'
Default: not used
EOF
exit
;;
--perf-data-dir=*)
PERF_DATA_DIR="${i#*=}"
shift
;;
--perf-data-prefix=*)
PERF_DATA_PREFIX="${i#*=}"
shift
;;
--perf-freq=*)
PERF_FREQ="${i#*=}"
shift
;;
--perf-count=*)
PERF_COUNT="${i#*=}"
shift
;;
--perf-call-graph*)
PERF_CALL_GRAPH="${i#*=}"
shift
;;
--perf-clockid*)
PERF_CLOCKID="${i#*=}"
shift
;;
--perf-args*)
PERF_RAW_ARGS="${i#*=}"
shift
;;
--renderer-client-id=*)
# Don't shift this option since it is passed in (and used by) chrome.
RENDERER_ID="${i#*=}"
;;
*)
;;
esac
done
SAMPLE_TRIGGER=""
if [ -n "${PERF_COUNT}" ]; then
SAMPLE_TRIGGER+="--count=${PERF_COUNT}"
elif [ -n "${PERF_FREQ}" ]; then
SAMPLE_TRIGGER+=" --freq=${PERF_FREQ}"
else
SAMPLE_TRIGGER="--freq=${PERF_FREQ_DEFAULT}"
fi
# Make sure `perf record` doesn't create `.debug/` in the home directory.
export JITDUMPDIR="${PERF_DATA_DIR}";
PERF_OUTPUT="${PERF_DATA_DIR}/${PERF_DATA_PREFIX}_${PPID}_${RENDERER_ID}.perf.data";
perf record \
--call-graph=${PERF_CALL_GRAPH} \
--clockid=${PERF_CLOCKID} \
${SAMPLE_TRIGGER} \
${PERF_RAW_ARGS} \
--output="${PERF_OUTPUT}" \
-- $@

336
deps/v8/tools/profiling/linux-perf-chrome.py vendored Executable file
View File

@ -0,0 +1,336 @@
#!/usr/bin/env python3
# Copyright 2022 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.
from datetime import datetime
from datetime import timedelta
import multiprocessing
import optparse
import os
from pathlib import Path
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import psutil
renderer_cmd_file = (Path(__file__).parent /
'linux-perf-chrome-renderer-cmd.sh').resolve()
assert renderer_cmd_file.is_file()
renderer_cmd_prefix = f"{renderer_cmd_file} --perf-data-prefix=chrome_renderer"
# ==============================================================================
usage = """Usage: %prog $CHROME_BIN [OPTION]... -- [CHROME_OPTION]... [URL]
This script runs linux-perf on all render process with custom V8 logging to get
support to resolve JS function names.
The perf data is written to OUT_DIR separate by renderer process.
See https://v8.dev/docs/linux-perf for more detailed instructions.
"""
parser = optparse.OptionParser(usage=usage)
parser.add_option(
"--perf-data-dir",
default=None,
metavar="OUT_DIR",
help=("Output directory for linux perf profile files."
"Defaults to './perf_profile_chrome_%Y-%m-%d_%H%M%S'"))
linux_perf_group = optparse.OptionGroup(
parser,
"Linux perf options",
)
linux_perf_group.add_option(
"--freq",
metavar="FREQUENCY",
help=("Sampling frequency in herz. Either use int or 'max'. "
"Sets `perf record --freq=FREQUENCY'. Defaults to 10000"))
linux_perf_group.add_option(
"--count",
type=int,
metavar="COUNT",
help=("Sample trigger after count events. "
"Sets `perf record --count=COUNT'. Not used by default."))
linux_perf_group.add_option(
"--call-graph",
metavar="TYPE",
type=str,
help="Sets `perf record --call-graph=TYPE`. Defaults to `fp`.")
linux_perf_group.add_option(
"--clockid",
metavar="TYPE",
type=str,
help="Sets `perf record --clockid=TYPE`. Defaults to 'mono'")
parser.add_option_group(linux_perf_group)
parser.add_option(
"--profile-browser-process",
action="store_true",
default=False,
help="Also start linux-perf for the browser process. "
"By default only renderer processes are sampled. "
"Outputs 'browser_*.perf.data' in the CDW")
parser.add_option("--timeout", type=float, help="Stop chrome after N seconds")
chrome_options = optparse.OptionGroup(
parser, "Chrome-forwarded Options",
"These convenience for a better script experience that are forward directly"
"to chrome. Any other chrome option can be passed after the '--' arguments"
"separator.")
chrome_options.add_option(
"--user-data-dir",
dest="user_data_dir",
default=None,
help="Chrome's profile location. "
"By default a temp directory is used.")
chrome_options.add_option(
"--js-flags",
dest="js_flags",
help="Comma-separated list of flags passed to V8.")
chrome_options.add_option(
"--renderer-cmd-prefix",
default=None,
help=f"Set command prefix, used for each new chrome renderer process."
"Default: {renderer_cmd_prefix}")
FEATURES_DOC = "See chrome's base/feature_list.h source file for more dertails"
chrome_options.add_option(
"--enable-features",
help="Comma-separated list of enabled chrome features. " + FEATURES_DOC)
chrome_options.add_option(
"--disable-features",
help="Command-separated list of disabled chrome features. " + FEATURES_DOC)
parser.add_option_group(chrome_options)
# ==============================================================================
def log(*args):
print("")
print("=" * 80)
print(*args)
print("=" * 80)
# ==============================================================================
(options, args) = parser.parse_args()
if len(args) == 0:
parser.error("No chrome binary provided")
chrome_bin = Path(args.pop(0)).absolute()
if not chrome_bin.exists():
parser.error(f"Chrome '{chrome_bin}' does not exist")
CUSTOM_PERF_OPTIONS = ("clockid", "call_graph", "freq", "count")
if options.freq and options.count:
parser.error("--freq and --count are mutually exclusive. "
"See `perf record --help' for more details.")
if options.renderer_cmd_prefix:
for perf_option in CUSTOM_PERF_OPTIONS + ("perf_data_dir",):
if getattr(options, perf_option):
flag_name = perf_option.replace("_", "-")
parser.error(f"Cannot specify --{flag_name} "
"if a custom --renderer-cmd-prefix is provided")
if options.perf_data_dir:
perf_data_dir = Path(options.perf_data_dir).absolute()
else:
date = datetime.now().strftime("%Y-%m-%d_%H%M%S")
perf_data_dir = Path.cwd() / f"perf_profile_chrome_{date}"
perf_data_dir.mkdir(parents=True, exist_ok=True)
if not perf_data_dir.is_dir():
parser.error(f"--perf-data-dir={options.perf_data_dir} "
"is not an directory or does not exist.")
if not options.renderer_cmd_prefix:
options.perf_data_dir = perf_data_dir
renderer_cmd_prefix = [str(renderer_cmd_file)]
for perf_option in CUSTOM_PERF_OPTIONS:
flag_value = getattr(options, perf_option)
if flag_value:
flag_name = perf_option.replace("_", "-")
renderer_cmd_prefix.append(f"--{flag_name}={flag_value}")
renderer_cmd_prefix.append(f"--perf-data-dir={options.perf_data_dir}")
options.renderer_cmd_prefix = shlex.join(renderer_cmd_prefix)
if options.timeout and options.timeout < 2:
parser.error("--timeout should be more than 2 seconds")
# ==============================================================================
old_cwd = Path.cwd()
os.chdir(perf_data_dir)
# ==============================================================================
JS_FLAGS_PERF = ("--perf-prof", "--interpreted-frames-native-stack")
def wait_for_process_timeout(process):
delta = timedelta(seconds=options.timeout)
start_time = datetime.now()
while True:
if (datetime.now() - start_time) >= delta:
return False
processHasStopped = process.poll() is not None
if processHasStopped:
return True
time.sleep(0.5)
return False
with tempfile.TemporaryDirectory(prefix="chrome-") as tmp_dir_path:
tempdir = Path(tmp_dir_path)
cmd = [
str(chrome_bin),
]
if options.user_data_dir is None:
options.user_data_dir = tempdir
cmd.append(f"--user-data-dir={options.user_data_dir}")
cmd += [
"--no-sandbox",
"--enable-benchmarking",
"--no-first-run",
"--no-default-browser-check",
f"--renderer-cmd-prefix={options.renderer_cmd_prefix}",
]
# Do the magic js-flag concatenation to properly forward them to the
# renderer command
js_flags = set(JS_FLAGS_PERF)
if options.js_flags:
js_flags.update(shlex.split(options.js_flags))
cmd += [f"--js-flags={','.join(list(js_flags))}"]
if options.enable_features:
cmd += [f"--enable-features={options.enable_features}"]
if options.disable_features:
cmd += [f"--disable-features={options.disable_features}"]
cmd += args
log("CHROME CMD: ", shlex.join(cmd))
if options.profile_browser_process:
perf_data_file = f"{tempdir.name}_browser.perf.data"
perf_cmd = [
"perf",
"record",
f"--call-graph={options.call_graph or 'fp'}",
f"--freq={options.freq or 10000}",
f"--clockid={options.clockid or 'mono'}",
f"--output={perf_data_file}",
"--",
]
cmd = perf_cmd + cmd
log("LINUX PERF CMD: ", shlex.join(cmd))
if options.timeout is None:
try:
subprocess.check_call(cmd, start_new_session=True)
log("Waiting for linux-perf to flush all perf data")
time.sleep(3)
except:
log("ERROR running perf record")
else:
process = subprocess.Popen(cmd)
if not wait_for_process_timeout(process):
log(f"QUITING chrome child processes after {options.timeout}s timeout")
current_process = psutil.Process()
children = current_process.children(recursive=True)
for child in children:
if "chrome" in child.name() or "content_shell" in child.name():
print(f" quitting PID={child.pid}")
child.send_signal(signal.SIGQUIT)
log("Waiting for linux-perf to flush all perf data")
time.sleep(3)
return_status = process.poll()
if return_status is None:
log("Force quitting linux-perf")
process.send_signal(signal.SIGQUIT)
process.wait()
elif return_status != 0:
log("ERROR running perf record")
# ==============================================================================
log("PARALLEL POST PROCESSING: Injecting JS symbols")
def inject_v8_symbols(perf_dat_file):
output_file = perf_dat_file.with_suffix(".data.jitted")
cmd = [
"perf", "inject", "--jit", f"--input={perf_dat_file.absolute()}",
f"--output={output_file.absolute()}"
]
try:
subprocess.check_call(cmd)
print(f"Processed: {output_file.name}")
except:
print(shlex.join(cmd))
return None
return output_file
results = []
with multiprocessing.Pool() as pool:
results = list(
pool.imap_unordered(inject_v8_symbols, perf_data_dir.glob("*perf.data")))
results = list(filter(lambda x: x is not None, results))
if len(results) == 0:
print("No perf files were successfully processed"
f" Check for errors or partial results in '{perf_data_dir}'")
exit(1)
log(f"RESULTS in '{perf_data_dir}'")
results.sort(key=lambda x: x.stat().st_size)
BYTES_TO_MIB = 1 / 1024 / 1024
for output_file in reversed(results):
print(f"{output_file.name:67}"
f"{(output_file.stat().st_size*BYTES_TO_MIB):10.2f}MiB")
# ==============================================================================
rel_path_strings = [str(path.relative_to(old_cwd)) for path in results]
abs_path_strings = [str(path.absolute()) for path in results]
largest_result = abs_path_strings[-1]
if not shutil.which('gcertstatus'):
log("ANALYSIS")
print(f"perf report --input='{largest_result}'")
print(f"pprof {rel_path_strings}")
exit(0)
log("PPROF")
has_gcert = False
try:
print("# Checking gcert status for googlers")
subprocess.check_call("gcertstatus >&/dev/null || gcert", shell=True)
has_gcert = True
cmd = [
"pprof", "-symbolize=local", "-flame",
f"-add_comment={shlex.join(sys.argv)}"
]
print("# Processing and uploading largest pprof result")
url = subprocess.check_output(cmd + [largest_result]).decode('utf-8').strip()
print("# PPROF RESULT")
print(url)
print("# Processing and uploading combined pprof result")
url = subprocess.check_output(cmd + abs_path_strings).decode('utf-8').strip()
print("# PPROF RESULT")
print(url)
except subprocess.CalledProcessError as e:
if has_gcert:
raise Exception("Could not generate pprof results") from e
print("# Please run `gcert` for generating pprof results")
print(f"pprof -symbolize=local -flame {' '.join(rel_path_strings)}")
except KeyboardInterrupt:
exit(1)

346
deps/v8/tools/profiling/linux-perf-d8.py vendored Executable file
View File

@ -0,0 +1,346 @@
#!/usr/bin/env python3
# Copyright 2022 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.
from datetime import datetime
from datetime import timedelta
import optparse
import os
from pathlib import Path
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import psutil
# ==============================================================================
usage = """Usage: %prog [OPTION]... $D8_BIN [D8_OPTION]... [FILE]
This script runs linux-perf with custom V8 logging to get support to resolve
JS function names.
The perf data is written to OUT_DIR separate by renderer process.
See https://v8.dev/docs/linux-perf for more detailed instructions.
See $D8_BIN --help for more flags/options
"""
parser = optparse.OptionParser(usage=usage)
# Stop parsing options after D8_BIN
parser.disable_interspersed_args()
parser.add_option(
'--perf-data-dir',
default=None,
metavar="OUT_DIR",
help=("Output directory for linux perf profile files "
"Defaults to './perf_profile_d8_%Y-%m-%d_%H%M%S'"))
parser.add_option("--timeout", type=float, help="Stop d8 after N seconds")
parser.add_option(
"--scope-to-mark-measure",
action="store_true",
default=False,
help="Scope perf recording to start at performance.mark events and stop at performance.measure events"
)
parser.add_option(
"--skip-pprof",
action="store_true",
default=False,
help="Skip pprof upload (relevant for Googlers only)")
d8_options = optparse.OptionGroup(
parser, "d8-forwarded Options",
"THese options are for a better script experience that are forward directly"
"to d8. Any other d8 option can be passed after the '--' arguments"
"separator.")
d8_options.add_option(
"--perf-prof-annotate-wasm",
help="Load wasm source map and provide annotate wasm code.",
action="store_true",
default=False)
d8_options.add_option(
"--no-interpreted-frames-native-stack",
help="For profiling v8 copies the interpreter entry trampoline for every "
"interpreted function. This makes interpreted functions identifiable on the "
"native stack at cost of a slight performance and memory overhead.",
action="store_true",
default=False)
parser.add_option_group(d8_options)
perf_options = optparse.OptionGroup(
parser, "perf-forward options", """
These options are forward directly to the `perf record` command and can be
used to manually tweak how profiling works.
See `perf record --help for more` informationn
""")
perf_options.add_option(
"--freq",
default="10000",
help="Sampling frequency, either 'max' or a number in herz. "
"Might be reduced depending on the platform. "
"Default is 10000.")
perf_options.add_option(
"--count", default=None, help="Event period to sample. Not set by default.")
perf_options.add_option("--call-graph", default="fp", help="Defaults tp 'fp'")
perf_options.add_option("--clockid", default="mono", help="Defaults to 'mono'")
perf_options.add_option("--event", default=None, help="Not set by default.")
perf_options.add_option(
"--raw-samples",
default=None,
help="Collect raw samples. Not set by default")
perf_options.add_option(
"--no-inherit",
action="store_true",
default=False,
help=" Child tasks do not inherit counters.")
parser.add_option_group(perf_options)
# ==============================================================================
def log(*args):
print("")
print("=" * 80)
print(*args)
print("=" * 80)
def main():
cleanup = []
try:
# ==========================================================================
(options, args) = parser.parse_args()
if options.freq and options.count:
parser.error("--freq and --count are mutually exclusive. "
"See `perf record --help' for more details.")
if len(args) == 0:
parser.error("No d8 binary provided")
raw_perf_args = []
d8_bin = None
while args:
additional_arg = args.pop(0)
maybe_d8_bin = Path(additional_arg).absolute()
if maybe_d8_bin.exists():
d8_bin = maybe_d8_bin
break
else:
raw_perf_args.append(additional_arg)
if not d8_bin:
parser.error(f"D8 '{d8_bin}' does not exist")
if options.perf_data_dir is None:
options.perf_data_dir = Path.cwd()
else:
options.perf_data_dir = Path(options.perf_data_dir).absolute()
options.perf_data_dir.mkdir(parents=True, exist_ok=True)
if not options.perf_data_dir.is_dir():
parser.error(f"--perf-data-dir={options.perf_data_dir} "
"is not an directory or does not exist.")
if options.timeout and options.timeout < 0:
parser.error("--timeout should be a positive number")
# ==========================================================================
def make_path_absolute(maybe_path, is_d8_js_argument=False):
if maybe_path.startswith("-"):
return maybe_path
path = Path(maybe_path)
if not path.exists():
return maybe_path
if is_d8_js_argument:
# Be slightly more strict with JS arguments as they might accidentally
# point to files that exist (e.h. JetStream workloads).
if "/" not in maybe_path:
return maybe_path
return str(path.absolute())
def make_args_paths_absolute(args):
args_absolute_paths = []
is_d8_js_argument = False
for arg in args:
if arg == "--":
is_d8_js_argument = True
args_absolute_paths.append(make_path_absolute(arg, is_d8_js_argument))
return args_absolute_paths
# Preprocess args if we change CWD to get cleaner output
if options.perf_data_dir != Path.cwd():
args = make_args_paths_absolute(args)
# ==========================================================================
old_cwd = Path.cwd()
os.chdir(options.perf_data_dir)
# ==========================================================================
cmd = [str(d8_bin), "--perf-prof"]
if not options.no_interpreted_frames_native_stack:
cmd += ["--interpreted-frames-native-stack"]
if options.perf_prof_annotate_wasm:
cmd += ["--perf-prof-annotate-wasm"]
if options.scope_to_mark_measure:
tmp_fifo_dir = tempfile.mkdtemp()
cleanup.append(lambda: shutil.rmtree(tmp_fifo_dir))
perf_ctl_fifo_path = os.path.join(tmp_fifo_dir, "perf_ctl.fifo")
perf_ack_fifo_path = os.path.join(tmp_fifo_dir, "perf_ack.fifo")
os.mkfifo(perf_ctl_fifo_path)
os.mkfifo(perf_ack_fifo_path)
perf_ctl_fd = os.open(perf_ctl_fifo_path, os.O_RDWR)
cleanup.append(lambda: os.close(perf_ctl_fd))
perf_ack_fd = os.open(perf_ack_fifo_path, os.O_RDWR)
cleanup.append(lambda: os.close(perf_ack_fd))
cmd += [
f"--perf-ctl-fd={perf_ctl_fd}", f"--perf-ack-fd={perf_ack_fd}",
"--scope-linux-perf-to-mark-measure"
]
pass_fds = [perf_ctl_fd, perf_ack_fd]
else:
pass_fds = []
cmd += args
log("D8 CMD: ", shlex.join(cmd))
datetime_str = datetime.now().strftime("%Y-%m-%d_%H%M%S")
perf_data_file = Path.cwd() / f"d8_{datetime_str}.perf.data"
perf_cmd = [
"perf", "record", f"--call-graph={options.call_graph}",
f"--clockid={options.clockid}", f"--output={perf_data_file}"
]
if options.freq:
perf_cmd += [f"--freq={options.freq}"]
if options.count:
perf_cmd += [f"--count={options.count}"]
if options.raw_samples:
perf_cmd += [f"--raw_samples={options.raw_samples}"]
if options.event:
perf_cmd += [f"--event={options.event}"]
if options.no_inherit:
perf_cmd += [f"--no-inherit"]
if raw_perf_args:
perf_cmd.extend(raw_perf_args)
if options.scope_to_mark_measure:
perf_cmd += [f"--control=fd:{perf_ctl_fd},{perf_ack_fd}", "--delay=-1"]
cmd = perf_cmd + ["--"] + cmd
log("LINUX PERF CMD: ", shlex.join(cmd))
def wait_for_process_timeout(process):
delta = timedelta(seconds=options.timeout)
start_time = datetime.now()
while True:
if (datetime.now() - start_time) >= delta:
return False
processHasStopped = process.poll() is not None
if processHasStopped:
return True
time.sleep(0.1)
return False
if options.timeout is None:
try:
subprocess.check_call(cmd, pass_fds=pass_fds)
log("Waiting for linux-perf to flush all perf data")
time.sleep(1)
except Exception as e:
log("ERROR running perf record: ", e)
else:
process = subprocess.Popen(cmd, pass_fds=pass_fds)
if not wait_for_process_timeout(process):
log(f"QUITING d8 processes after {options.timeout}s timeout")
current_process = psutil.Process()
children = current_process.children(recursive=True)
for child in children:
if "d8" in child.name():
print(f" quitting PID={child.pid}")
child.send_signal(signal.SIGQUIT)
log("Waiting for linux-perf to flush all perf data")
time.sleep(1)
return_status = process.poll()
if return_status is None:
log("Force quitting linux-perf")
process.send_signal(signal.SIGQUIT)
process.wait()
elif return_status != 0:
log("ERROR running perf record")
# ==========================================================================
log("POST PROCESSING: Injecting JS symbols")
def inject_v8_symbols(perf_dat_file):
output_file = perf_dat_file.with_suffix(".data.jitted")
cmd = [
"perf", "inject", "--jit", f"--input={perf_dat_file.absolute()}",
f"--output={output_file.absolute()}"
]
try:
subprocess.check_call(cmd)
print(f"Processed: {output_file}")
except:
print(shlex.join(cmd))
return None
return output_file
result = inject_v8_symbols(perf_data_file)
if result is None:
print(
"No perf files were successfully processed"
f" Check for errors or partial results in '{options.perf_data_dir}'")
return 1
log(f"RESULTS in '{options.perf_data_dir}'")
BYTES_TO_MIB = 1 / 1024 / 1024
print(f"{result.name:67}{(result.stat().st_size*BYTES_TO_MIB):10.2f}MiB")
# ==========================================================================
if not shutil.which('gcertstatus') or options.skip_pprof:
log("ANALYSIS")
print(f"perf report --input='{result}'")
print(f"pprof '{result}'")
return 0
log("PPROF")
has_gcert = False
try:
print("# Checking gcert status for googlers")
subprocess.check_call("gcertstatus >&/dev/null || gcert", shell=True)
has_gcert = True
cmd = [
"pprof", "-symbolize=local", "-flame",
f"-add_comment={shlex.join(sys.argv)}",
str(result.absolute())
]
print("# Processing and uploading to pprofresult")
url = subprocess.check_output(cmd).decode('utf-8').strip()
print(url)
except subprocess.CalledProcessError as e:
if has_gcert:
raise Exception("Could not generate pprof results") from e
print("# Please run `gcert` for generating pprof results")
print(f"pprof -symbolize=local -flame {result}")
except KeyboardInterrupt:
return 1
finally:
for cleanup_func in reversed(cleanup):
cleanup_func()
return 0
sys.exit(main())

1008
deps/v8/tools/profiling/ll_prof.py vendored Executable file

File diff suppressed because it is too large Load Diff

69
deps/v8/tools/profiling/run-llprof.sh vendored Executable file
View File

@ -0,0 +1,69 @@
#!/bin/sh
#
# Copyright 2012 the V8 project 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.
########## Global variable definitions
# Ensure that <your CPU clock> / $SAMPLE_EVERY_N_CYCLES < $MAXIMUM_SAMPLE_RATE.
MAXIMUM_SAMPLE_RATE=10000000
SAMPLE_EVERY_N_CYCLES=10000
SAMPLE_RATE_CONFIG_FILE="/proc/sys/kernel/perf_event_max_sample_rate"
KERNEL_MAP_CONFIG_FILE="/proc/sys/kernel/kptr_restrict"
########## Usage
usage() {
cat << EOF
usage: $0 <benchmark_command>
Executes <benchmark_command> under observation by the kernel's "perf" \
framework, then calls the low level tick processor to analyze the results.
EOF
}
if [ $# -eq 0 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ] ; then
usage
exit 1
fi
########## Actual script execution
ACTUAL_SAMPLE_RATE=$(cat $SAMPLE_RATE_CONFIG_FILE)
if [ "$ACTUAL_SAMPLE_RATE" -lt "$MAXIMUM_SAMPLE_RATE" ] ; then
echo "Setting appropriate maximum sample rate..."
echo $MAXIMUM_SAMPLE_RATE | sudo tee $SAMPLE_RATE_CONFIG_FILE
fi
ACTUAL_KERNEL_MAP_RESTRICTION=$(cat $KERNEL_MAP_CONFIG_FILE)
if [ "$ACTUAL_KERNEL_MAP_RESTRICTION" -ne "0" ] ; then
echo "Disabling kernel address map restriction..."
echo 0 | sudo tee $KERNEL_MAP_CONFIG_FILE
fi
echo "Running benchmark..."
perf record -R -e cycles -c $SAMPLE_EVERY_N_CYCLES -i $@ --ll-prof