2022-04-11 15:38:06 +00:00
|
|
|
#!/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.
|
|
|
|
|
2022-09-07 07:44:12 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from datetime import timedelta
|
|
|
|
import multiprocessing
|
2022-04-11 15:38:06 +00:00
|
|
|
import optparse
|
|
|
|
import os
|
2022-09-07 07:44:12 +00:00
|
|
|
from pathlib import Path
|
2022-04-11 15:38:06 +00:00
|
|
|
import shlex
|
2022-09-07 07:44:12 +00:00
|
|
|
import shutil
|
2022-04-11 15:38:06 +00:00
|
|
|
import signal
|
2022-09-07 07:44:12 +00:00
|
|
|
import subprocess
|
|
|
|
import sys
|
2022-04-11 15:38:06 +00:00
|
|
|
import tempfile
|
|
|
|
import time
|
2022-09-07 07:44:12 +00:00
|
|
|
|
2022-04-11 15:38:06 +00:00
|
|
|
import psutil
|
|
|
|
|
2022-04-25 14:52:01 +00:00
|
|
|
renderer_cmd_file = Path(__file__).parent / 'linux-perf-chrome-renderer-cmd.sh'
|
2022-04-11 15:38:06 +00:00
|
|
|
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.
|
|
|
|
|
2022-09-07 07:44:12 +00:00
|
|
|
See https://v8.dev/docs/linux-perf for more detailed instructions.
|
2022-04-11 15:38:06 +00:00
|
|
|
"""
|
|
|
|
parser = optparse.OptionParser(usage=usage)
|
|
|
|
parser.add_option(
|
|
|
|
'--perf-data-dir',
|
|
|
|
default=None,
|
|
|
|
metavar="OUT_DIR",
|
|
|
|
help="Output directory for linux perf profile files")
|
|
|
|
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")
|
2022-04-14 13:20:48 +00:00
|
|
|
parser.add_option("--timeout", type=float, help="Stop chrome after N seconds")
|
2022-04-11 15:38:06 +00:00
|
|
|
|
|
|
|
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)
|
|
|
|
chrome_options.add_option("--js-flags", dest="js_flags")
|
|
|
|
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")
|
|
|
|
|
2022-04-20 10:30:16 +00:00
|
|
|
chrome_bin = Path(args.pop(0)).absolute()
|
2022-04-11 15:38:06 +00:00
|
|
|
if not chrome_bin.exists():
|
|
|
|
parser.error(f"Chrome '{chrome_bin}' does not exist")
|
|
|
|
|
|
|
|
if options.renderer_cmd_prefix is not None:
|
|
|
|
if options.perf_data_dir is not None:
|
|
|
|
parser.error("Cannot specify --perf-data-dir "
|
|
|
|
"if a custom --renderer-cmd-prefix is provided")
|
|
|
|
else:
|
|
|
|
options.renderer_cmd_prefix = str(renderer_cmd_file)
|
|
|
|
|
|
|
|
if options.perf_data_dir is None:
|
|
|
|
options.perf_data_dir = Path.cwd()
|
|
|
|
else:
|
|
|
|
options.perf_data_dir = Path(options.perf_data_dir).absolute()
|
|
|
|
|
|
|
|
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 < 2:
|
|
|
|
parser.error("--timeout should be more than 2 seconds")
|
|
|
|
|
|
|
|
# ==============================================================================
|
|
|
|
old_cwd = Path.cwd()
|
|
|
|
os.chdir(options.perf_data_dir)
|
|
|
|
|
|
|
|
# ==============================================================================
|
2022-04-25 14:52:01 +00:00
|
|
|
JS_FLAGS_PERF = ("--perf-prof", "--no-write-protect-code-memory",
|
2022-04-11 15:38:06 +00:00
|
|
|
"--interpreted-frames-native-stack")
|
|
|
|
|
2022-04-14 13:20:48 +00:00
|
|
|
|
|
|
|
def wait_for_process_timeout(process):
|
2022-07-11 14:56:24 +00:00
|
|
|
delta = timedelta(seconds=options.timeout)
|
|
|
|
start_time = datetime.now()
|
|
|
|
while True:
|
|
|
|
if (datetime.now() - start_time) >= delta:
|
|
|
|
return False
|
2022-04-14 13:20:48 +00:00
|
|
|
processHasStopped = process.poll() is not None
|
|
|
|
if processHasStopped:
|
|
|
|
return True
|
|
|
|
time.sleep(0.5)
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2022-04-11 15:38:06 +00:00
|
|
|
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:
|
|
|
|
cmd.append(f"--user-data-dir={tempdir}")
|
|
|
|
cmd += [
|
2022-09-07 07:44:12 +00:00
|
|
|
"--no-sandbox",
|
|
|
|
"--incognito",
|
|
|
|
"--enable-benchmarking",
|
|
|
|
"--no-first-run",
|
2022-04-11 15:38:06 +00:00
|
|
|
"--no-default-browser-check",
|
|
|
|
f"--renderer-cmd-prefix={options.renderer_cmd_prefix}",
|
|
|
|
]
|
2022-04-25 14:52:01 +00:00
|
|
|
|
|
|
|
# Do the magic js-flag concatenation to properly forward them to the
|
|
|
|
# renderer command
|
|
|
|
js_flags = set(JS_FLAGS_PERF)
|
2022-04-11 15:38:06 +00:00
|
|
|
if options.js_flags:
|
2022-04-25 14:52:01 +00:00
|
|
|
js_flags.update(shlex.split(options.js_flags))
|
|
|
|
cmd += [f"--js-flags={','.join(list(js_flags))}"]
|
|
|
|
|
2022-04-11 15:38:06 +00:00
|
|
|
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", "--call-graph=fp", "--freq=max", "--clockid=mono",
|
|
|
|
f"--output={perf_data_file}", "--"
|
|
|
|
]
|
|
|
|
cmd = perf_cmd + cmd
|
|
|
|
log("LINUX PERF CMD: ", shlex.join(cmd))
|
|
|
|
|
|
|
|
if options.timeout is None:
|
2022-04-20 10:30:16 +00:00
|
|
|
try:
|
2022-04-25 14:52:01 +00:00
|
|
|
subprocess.check_call(cmd, start_new_session=True)
|
|
|
|
log("Waiting for linux-perf to flush all perf data")
|
|
|
|
time.sleep(3)
|
2022-04-20 10:30:16 +00:00
|
|
|
except:
|
|
|
|
log("ERROR running perf record")
|
2022-04-11 15:38:06 +00:00
|
|
|
else:
|
|
|
|
process = subprocess.Popen(cmd)
|
2022-04-14 13:20:48 +00:00
|
|
|
if not wait_for_process_timeout(process):
|
|
|
|
log(f"QUITING chrome child processes after {options.timeout}s timeout")
|
2022-04-11 15:38:06 +00:00
|
|
|
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)
|
2022-04-25 14:52:01 +00:00
|
|
|
log("Waiting for linux-perf to flush all perf data")
|
|
|
|
time.sleep(3)
|
2022-04-20 10:30:16 +00:00
|
|
|
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")
|
2022-09-07 07:44:12 +00:00
|
|
|
|
|
|
|
# ==============================================================================
|
2022-04-11 15:38:06 +00:00
|
|
|
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}",
|
|
|
|
f"--output={output_file}"
|
|
|
|
]
|
|
|
|
try:
|
2022-04-20 10:30:16 +00:00
|
|
|
subprocess.check_call(cmd)
|
2022-04-11 15:38:06 +00:00
|
|
|
print(f"Processed: {output_file}")
|
|
|
|
except:
|
|
|
|
print(shlex.join(cmd))
|
|
|
|
return None
|
|
|
|
return output_file
|
|
|
|
|
|
|
|
|
|
|
|
results = []
|
|
|
|
with multiprocessing.Pool() as pool:
|
|
|
|
results = list(
|
|
|
|
pool.imap_unordered(inject_v8_symbols,
|
|
|
|
options.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"
|
|
|
|
" Check for errors or partial results in '{options.perf_data_dir}'")
|
|
|
|
exit(1)
|
2022-09-07 07:44:12 +00:00
|
|
|
|
2022-04-11 15:38:06 +00:00
|
|
|
log(f"RESULTS in '{options.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}{(output_file.stat().st_size*BYTES_TO_MIB):10.2f}MiB"
|
|
|
|
)
|
|
|
|
|
2022-09-07 07:44:12 +00:00
|
|
|
# ==============================================================================
|
|
|
|
path_strings = [str(path.relative_to(old_cwd)) for path in results]
|
|
|
|
largest_result = path_strings[-1]
|
|
|
|
results_str = ' '.join(path_strings)
|
|
|
|
|
|
|
|
if not shutil.which('gcertstatus'):
|
|
|
|
log("ANALYSIS")
|
|
|
|
print(f"perf report --input='{largest_result}'")
|
|
|
|
print(f"pprof {path_strings}")
|
|
|
|
exit(0)
|
|
|
|
|
2022-04-14 13:20:48 +00:00
|
|
|
log("PPROF")
|
2022-09-07 07:44:12 +00:00
|
|
|
has_gcert = False
|
|
|
|
try:
|
|
|
|
print("# Checking gcert status for googlers")
|
|
|
|
subprocess.check_call("gcertstatus >&/dev/null || gcert", shell=True)
|
|
|
|
has_gcert = True
|
|
|
|
|
|
|
|
cmd = ["pprof", "-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 + 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 -flame {' '.join(path_strings)}")
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
exit(1)
|