Skip to content

Commit 8cbd8f0

Browse files
authored
[libc++] Add scripts to build and test libc++ at a specified commit (#158104)
This is useful to perform historical analyses, bisections or establish a benchmarking baseline after making some changes on a branch. For example, one can run benchmarks against `main` and easily compare them to the results on the current feature branch with: libcxx/utils/test-at-commit --commit $(git merge-base main HEAD) \ -B build/baseline -- <lit args> libcxx/utils/libcxx-lit build/candidate <lit args> libcxx/utils/compare-benchmarks \ <(libcxx/utils/consolidate-benchmarks build/baseline) \ <(libcxx/utils/consolidate-benchmarks build/candidate) Doing this without these scripts would require checking out the desired baseline, setting up the build directory and running the tests manually. With these scripts, this can automatically be automated without dirtying the current checkout.
1 parent d1c0b1b commit 8cbd8f0

File tree

2 files changed

+226
-0
lines changed

2 files changed

+226
-0
lines changed

libcxx/utils/build-at-commit

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import os
5+
import subprocess
6+
import sys
7+
import tempfile
8+
9+
# Unofficial list of directories required to build libc++. This is a best guess that should work
10+
# when checking out the monorepo at most commits, but it's technically not guaranteed to work
11+
# (especially for much older commits).
12+
LIBCXX_REQUIRED_DIRECTORIES = [
13+
'libcxx',
14+
'libcxxabi',
15+
'llvm/cmake',
16+
'llvm/utils/llvm-lit',
17+
'llvm/utils/lit',
18+
'runtimes',
19+
'cmake',
20+
'third-party/benchmark',
21+
'libc'
22+
]
23+
24+
def directory_path(string):
25+
if os.path.isdir(string):
26+
return string
27+
else:
28+
raise NotADirectoryError(string)
29+
30+
def resolve_commit(git_repo, commit):
31+
"""
32+
Resolve the full commit SHA from any tree-ish.
33+
"""
34+
return subprocess.check_output(['git', '-C', git_repo, 'rev-parse', commit], text=True).strip()
35+
36+
def checkout_subdirectories(git_repo, commit, paths, destination):
37+
"""
38+
Produce a copy of the specified Git-tracked files/directories at the given commit.
39+
The resulting files and directories at placed at the given location.
40+
"""
41+
with tempfile.TemporaryDirectory() as tmp:
42+
tmpfile = os.path.join(tmp, 'archive.tar.gz')
43+
git_archive = ['git', '-C', git_repo, 'archive', '--format', 'tar.gz', '--output', tmpfile, commit, '--'] + list(paths)
44+
subprocess.check_call(git_archive)
45+
os.makedirs(destination, exist_ok=True)
46+
subprocess.check_call(['tar', '-x', '-z', '-f', tmpfile, '-C', destination])
47+
48+
def build_libcxx(src_dir, build_dir, install_dir, cmake_options):
49+
"""
50+
Build and install libc++ using the provided source, build and installation directories.
51+
"""
52+
configure = ['cmake', '-S', os.path.join(src_dir, 'runtimes'), '-B', build_dir, '-G', 'Ninja']
53+
configure += ['-D', 'LLVM_ENABLE_RUNTIMES=libcxx;libcxxabi']
54+
configure += ['-D', f'CMAKE_INSTALL_PREFIX={install_dir}']
55+
configure += ['-D', 'LIBCXXABI_USE_LLVM_UNWINDER=OFF']
56+
configure += list(cmake_options)
57+
subprocess.check_call(configure)
58+
59+
build = ['cmake', '--build', build_dir, '--target', 'install']
60+
subprocess.check_call(build)
61+
62+
def exists_in_commit(git_repo, commit, path):
63+
"""
64+
Return whether the given path (file or directory) existed at the given commit.
65+
"""
66+
cmd = ['git', '-C', git_repo, 'show', f'{commit}:{path}']
67+
result = subprocess.call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
68+
return result == 0
69+
70+
def main(argv):
71+
parser = argparse.ArgumentParser(
72+
prog='build-at-commit',
73+
description='Attempt to build libc++ at the specified commit. '
74+
'This script checks out libc++ at the given commit and does a best effort attempt '
75+
'to build it and install it to the specified location. This can be useful when '
76+
'performing bisections or historical analyses of libc++ behavior, performance, etc. '
77+
'This may not work for some commits, for example commits where the library is broken '
78+
'or much older commits when the build process was different from today\'s build process.')
79+
parser.add_argument('--commit', type=str, required=True,
80+
help='Commit to checkout and build.')
81+
parser.add_argument('--install-dir', type=str, required=True,
82+
help='Path to install the library at. This is equivalent to the `CMAKE_INSTALL_PREFIX` '
83+
'used when building.')
84+
parser.add_argument('cmake_options', nargs=argparse.REMAINDER,
85+
help='Optional arguments passed to CMake when configuring the build. Should be provided last and '
86+
'separated from other arguments with a `--`.')
87+
parser.add_argument('--git-repo', type=directory_path, default=os.getcwd(),
88+
help='Optional path to the Git repository to use. By default, the current working directory is used.')
89+
parser.add_argument('--tmp-src-dir', type=str, required=False,
90+
help='Optional path to use for the ephemeral source checkout used to perform the build. '
91+
'By default, a temporary directory is used and it is cleaned up after the build. '
92+
'If a custom directory is specified, it is not cleaned up automatically.')
93+
parser.add_argument('--tmp-build-dir', type=str, required=False,
94+
help='Optional path to use for the ephemeral build directory used during the build.'
95+
'By default, a temporary directory is used and it is cleaned up after the build. '
96+
'If a custom directory is specified, it is not cleaned up automatically.')
97+
args = parser.parse_args(argv)
98+
99+
# Gather CMake options
100+
cmake_options = []
101+
if args.cmake_options is not None:
102+
if args.cmake_options[0] != '--':
103+
raise ArgumentError('For clarity, CMake options must be separated from other options by --')
104+
cmake_options = args.cmake_options[1:]
105+
106+
# Figure out which directories to check out at the given commit. We avoid checking
107+
# out the whole monorepo as an optimization.
108+
sha = resolve_commit(args.git_repo, args.commit)
109+
checkout_dirs = [d for d in LIBCXX_REQUIRED_DIRECTORIES if exists_in_commit(args.git_repo, sha, d)]
110+
111+
tempdirs = []
112+
if args.tmp_src_dir is not None:
113+
src_dir = args.tmp_src_dir
114+
else:
115+
tempdirs.append(tempfile.TemporaryDirectory())
116+
src_dir = tempdirs[-1].name
117+
118+
if args.tmp_build_dir is not None:
119+
build_dir = args.tmp_build_dir
120+
else:
121+
tempdirs.append(tempfile.TemporaryDirectory())
122+
build_dir = tempdirs[-1].name
123+
124+
try:
125+
checkout_subdirectories(args.git_repo, sha, checkout_dirs, src_dir)
126+
build_libcxx(src_dir, build_dir, args.install_dir, cmake_options)
127+
finally:
128+
for d in tempdirs:
129+
d.cleanup()
130+
131+
if __name__ == '__main__':
132+
main(sys.argv[1:])

libcxx/utils/test-at-commit

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import logging
5+
import os
6+
import subprocess
7+
import sys
8+
import tempfile
9+
10+
PARENT_DIR = os.path.dirname(os.path.abspath(__file__))
11+
12+
LIT_CONFIG_FILE = """
13+
#
14+
# This testing configuration handles running the test suite against a version
15+
# of libc++ installed at the given path.
16+
#
17+
18+
lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
19+
20+
config.substitutions.append(('%{{flags}}',
21+
'-pthread' + (' -isysroot {{}}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else '')
22+
))
23+
config.substitutions.append(('%{{compile_flags}}', '-nostdinc++ -I {INSTALL_ROOT}/include/c++/v1 -I %{{libcxx-dir}}/test/support'))
24+
config.substitutions.append(('%{{link_flags}}', '-nostdlib++ -L {INSTALL_ROOT}/lib -Wl,-rpath,{INSTALL_ROOT}/lib -lc++'))
25+
config.substitutions.append(('%{{exec}}', '%{{executor}} --execdir %T -- '))
26+
27+
import os, site
28+
site.addsitedir(os.path.join('@LIBCXX_SOURCE_DIR@', 'utils'))
29+
import libcxx.test.params, libcxx.test.config
30+
libcxx.test.config.configure(
31+
libcxx.test.params.DEFAULT_PARAMETERS,
32+
libcxx.test.features.DEFAULT_FEATURES,
33+
config,
34+
lit_config
35+
)
36+
"""
37+
38+
def directory_path(string):
39+
if os.path.isdir(string):
40+
return string
41+
else:
42+
raise NotADirectoryError(string)
43+
44+
def main(argv):
45+
parser = argparse.ArgumentParser(
46+
prog='test-at-commit',
47+
description='Build libc++ at the specified commit and test it against the version of the test suite '
48+
'currently checked out in the specified Git repository. '
49+
'This makes it easier to perform historical analyses of libc++ behavior, gather historical '
50+
'performance data, bisect issues, and so on. '
51+
'A current limitation of this script is that it assumes the arguments passed to CMake when '
52+
'building the library.')
53+
parser.add_argument('--build', '-B', type=str, required=True,
54+
help='Path to create the build directory for running the test suite at.')
55+
parser.add_argument('--commit', type=str, required=True,
56+
help='Commit to build libc++ at.')
57+
parser.add_argument('lit_options', nargs=argparse.REMAINDER,
58+
help='Optional arguments passed to lit when running the tests. Should be provided last and '
59+
'separated from other arguments with a `--`.')
60+
parser.add_argument('--git-repo', type=directory_path, default=os.getcwd(),
61+
help='Optional path to the Git repository to use. By default, the current working directory is used.')
62+
args = parser.parse_args(argv)
63+
64+
# Gather lit options
65+
lit_options = []
66+
if args.lit_options is not None:
67+
if args.lit_options[0] != '--':
68+
raise ArgumentError('For clarity, Lit options must be separated from other options by --')
69+
lit_options = args.lit_options[1:]
70+
71+
with tempfile.TemporaryDirectory() as install_dir:
72+
# Build the library at the baseline
73+
build_cmd = [os.path.join(PARENT_DIR, 'build-at-commit'), '--install-dir', install_dir, '--commit', args.commit]
74+
build_cmd += ['--', '-DCMAKE_BUILD_TYPE=RelWithDebInfo']
75+
subprocess.check_call(build_cmd)
76+
77+
# Configure the test suite in the specified build directory
78+
os.makedirs(args.build)
79+
lit_cfg = os.path.abspath(os.path.join(args.build, 'temp_lit_cfg.cfg.in'))
80+
with open(lit_cfg, 'w') as f:
81+
f.write(LIT_CONFIG_FILE.format(INSTALL_ROOT=install_dir))
82+
83+
test_suite_cmd = ['cmake', '-B', args.build, '-S', os.path.join(args.git_repo, 'runtimes'), '-G', 'Ninja']
84+
test_suite_cmd += ['-D', 'LLVM_ENABLE_RUNTIMES=libcxx;libcxxabi']
85+
test_suite_cmd += ['-D', 'LIBCXXABI_USE_LLVM_UNWINDER=OFF']
86+
test_suite_cmd += ['-D', f'LIBCXX_TEST_CONFIG={lit_cfg}']
87+
subprocess.check_call(test_suite_cmd)
88+
89+
# Run the specified tests against the produced baseline installation
90+
lit_cmd = [os.path.join(PARENT_DIR, 'libcxx-lit'), args.build] + lit_options
91+
subprocess.check_call(lit_cmd)
92+
93+
if __name__ == '__main__':
94+
main(sys.argv[1:])

0 commit comments

Comments
 (0)