From 96d5fb1db9602a21b7f22648cb4b2ea5b11bf97e Mon Sep 17 00:00:00 2001 From: Anthony Maurice Date: Thu, 12 Nov 2026 22:41:39 +0000 Subject: [PATCH 1/6] Speed up desktop packaging and final SDK zip creation merge_libraries.py: - Run objcopy on each archive's object files in parallel (--jobs, default = number of CPUs). Previously every .obj was processed serially, which left firebase_firestore.lib (Windows Debug) merging on a single core for ~90 min. - Only pass objcopy the symbol renames that actually appear in each input archive (--filter_renames_per_archive, default on). objcopy's cost scales with the size of the redefinition list. - Support llvm-objcopy alongside GNU nm/ar (--binutils_objcopy_is_llvm, autodetected): don't pass GNU BFD target names to llvm-objcopy. package.sh: add -O to use llvm-objcopy (from the tools dir) with GNU nm/ar. cpp-packaging.yml: - Linux and Windows packaging use the runner's llvm-objcopy via -O. GNU objcopy does a linear lookup per symbol in the redefinition list. - Build firebase_cpp_sdk.zip and firebase_cpp_sdk_windows.zip in parallel in the merge job using multithreaded 7-Zip (new zip_package.sh, which verifies file/symlink counts and falls back to Info-ZIP), replacing single-threaded "zip -9" and the separate sequential create-windows-only-package job. - Don't recompress the already-compressed zips when uploading artifacts. build_desktop.py: on Windows, set CL=/MP so that external projects (gRPC, Abseil, Protobuf, Firestore) compile their sources in parallel. Previously grpc.vcxproj and firestore_core.vcxproj compiled on a single core at the end of every Windows build. --- .github/workflows/cpp-packaging.yml | 96 ++++++++++------- build_scripts/desktop/package.sh | 14 ++- build_scripts/other/zip_package.sh | 91 ++++++++++++++++ scripts/gha/build_desktop.py | 12 +++ scripts/merge_libraries.py | 159 ++++++++++++++++++++++------ 5 files changed, 294 insertions(+), 78 deletions(-) create mode 100755 build_scripts/other/zip_package.sh diff --git a/.github/workflows/cpp-packaging.yml b/.github/workflows/cpp-packaging.yml index e34f5fb36c..01f5c88db0 100644 --- a/.github/workflows/cpp-packaging.yml +++ b/.github/workflows/cpp-packaging.yml @@ -591,6 +591,21 @@ jobs: tar -xvzf artifacts/packaging-tools-${tools_platform}/packaging-tools.tgz -C bin rm -rf artifacts/packaging-tools-*.tgz chmod -R u+x bin + if [[ "${{ matrix.sdk_platform }}" != "darwin" ]]; then + # Use llvm-objcopy rather than GNU objcopy to rename symbols on + # Linux and Windows. GNU objcopy does a linear search of the symbol + # redefinition list for every symbol, which is extremely slow for + # large (especially Debug) libraries; llvm-objcopy uses a hash table. + # The Ubuntu runners come with several versions of LLVM installed, + # so use the newest one available. + llvm_objcopy=$(ls /usr/bin/llvm-objcopy-* 2>/dev/null | sort -V | tail -n 1) + if [[ -z "${llvm_objcopy}" ]]; then + sudo apt-get install -y llvm + llvm_objcopy=$(command -v llvm-objcopy) + fi + echo "Using ${llvm_objcopy}: $(${llvm_objcopy} --version | head -n 2 | tr '\n' ' ')" + ln -sf "${llvm_objcopy}" bin/llvm-objcopy + fi # To save space, delete any artifacts that we don't need for packaging. for pkg in artifacts/firebase-cpp-sdk-*; do if [[ "${pkg}" != "artifacts/firebase-cpp-sdk-${{ matrix.sdk_platform }}${{ matrix.suffix }}"* ]]; then @@ -608,11 +623,16 @@ jobs: # MacOS: use LLVM binutils for both X64 and ARM64 additional_flags+=(-L) elif [[ "${{ matrix.sdk_platform }}" == "windows" && "${variant}" == *"/x64/"* ]]; then - # Windows x64: force input and output target format - additional_flags+=(-f pe-x86-64,pe-bigobj-x86-64) + # Windows x64: force input and output target format (for GNU + # nm and ar; llvm-objcopy autodetects the format). + additional_flags+=(-O -f pe-x86-64,pe-bigobj-x86-64) elif [[ "${{ matrix.sdk_platform }}" == "windows" && "${variant}" == *"/x86/"* ]]; then - # Windows x86: force input and output target format - additional_flags+=(-f pe-i386,pe-bigobj-i386) + # Windows x86: force input and output target format (for GNU + # nm and ar; llvm-objcopy autodetects the format). + additional_flags+=(-O -f pe-i386,pe-bigobj-i386) + else + # Linux: use llvm-objcopy, GNU nm and ar. + additional_flags+=(-O) fi sdk-src/build_scripts/desktop/package.sh -D -b ${pkg} -o firebase-cpp-sdk-${{ matrix.sdk_platform }}${{ matrix.suffix }}-package -p ${{ matrix.sdk_platform }} -t bin -d ${variant} -P python3 -j ${additional_flags[*]} done @@ -783,8 +803,29 @@ jobs: # Save the hash of every file into the SDK package. find firebase_cpp_sdk -type f -print0 | xargs -0 ${{ env.hashCommand }} --tag > file_hashes.txt mv file_hashes.txt firebase_cpp_sdk/ - # Zip up the SDK package recursively, preserving symlinks. - zip -9 -r -y ../firebase_cpp_sdk.zip firebase_cpp_sdk + + # Create the Windows-only SDK package, using hard links to avoid + # copying the files. + mkdir -p ../windows-sdk + cp -al firebase_cpp_sdk ../windows-sdk/firebase_cpp_sdk_windows + pushd ../windows-sdk/firebase_cpp_sdk_windows + # Remove all non-Windows files. + rm -rf xcframeworks frameworks libs/linux libs/ios libs/tvos libs/darwin libs/android Android + cat > readme_windows.md < firebase_cpp_sdk_hash.txt echo "::warning ::$(cat firebase_cpp_sdk_hash.txt)" + ${{ env.hashCommand }} --tag firebase_cpp_sdk_windows.zip > firebase_cpp_sdk_windows_hash.txt + echo "::warning ::$(cat firebase_cpp_sdk_windows_hash.txt)" - name: Print final package contents shell: bash @@ -810,51 +853,22 @@ jobs: with: name: firebase_cpp_sdk.zip path: firebase_cpp_sdk.zip + # Already compressed, don't waste time compressing it again. + compression-level: 0 - create_windows_only_package: - name: create-windows-only-package - runs-on: ubuntu-22.04 - needs: [merge_packages] - steps: - - name: download SDK zip - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # ratchet:actions/download-artifact@v8 - with: - name: firebase_cpp_sdk.zip - - name: unzip SDK and remove non-Windows files - run: | - set -x - unzip -q firebase_cpp_sdk.zip -d windows-sdk - cd windows-sdk - # Rename the top-level directory. - mv firebase_cpp_sdk firebase_cpp_sdk_windows - cd firebase_cpp_sdk_windows - # Remove all non-Windows files. - rm -rf xcframeworks frameworks libs/linux libs/ios libs/tvos libs/darwin libs/android Android - cat > readme_windows.md < firebase_cpp_sdk_windows_hash.txt - echo "::warning ::$(cat firebase_cpp_sdk_windows_hash.txt)" - name: upload Windows hash uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # ratchet:actions/upload-artifact@v7 with: name: firebase_cpp_sdk_windows_hash.txt path: firebase_cpp_sdk_windows_hash.txt + - name: upload Windows SDK zip uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # ratchet:actions/upload-artifact@v7 with: name: firebase_cpp_sdk_windows.zip path: firebase_cpp_sdk_windows.zip - + # Already compressed, don't waste time compressing it again. + compression-level: 0 cleanup_packaging_artifacts: # Clean up intermediate artifacts from packaging step. @@ -879,7 +893,7 @@ jobs: trigger_integration_tests: # Trigger the integration_tests workflow. - needs: [merge_packages, download_sdk_package, create_windows_only_package, cleanup_packaging_artifacts] + needs: [merge_packages, download_sdk_package, cleanup_packaging_artifacts] if: (github.event.inputs.skipIntegrationTests == 0 || github.event.inputs.skipIntegrationTests == '') && !cancelled() && !failure() runs-on: ubuntu-22.04 steps: diff --git a/build_scripts/desktop/package.sh b/build_scripts/desktop/package.sh index a741931e6e..01aae403fe 100755 --- a/build_scripts/desktop/package.sh +++ b/build_scripts/desktop/package.sh @@ -19,6 +19,8 @@ options: -j, run merge_libraries jobs in parallel -v, enable verbose mode -L, use LLVM binutils + -O, use llvm-objcopy (from the tools directory) for objcopy only, but keep + using GNU nm and ar. Much faster than GNU objcopy when renaming many symbols. -R, print rename prefix and exit -N, print allowed namespaces and exit -D, delete package files after using them to save disk space @@ -41,6 +43,7 @@ binutils_format= temp_dir= run_in_parallel=0 use_llvm_binutils=0 +use_llvm_objcopy=0 . "${root_dir}/build_scripts/packaging.conf" @@ -59,7 +62,7 @@ abspath(){ fi } -while getopts "f:b:o:p:d:m:P:t:NRhjLDv" opt; do +while getopts "f:b:o:p:d:m:P:t:NRhjLODv" opt; do case $opt in f) binutils_format=$OPTARG @@ -90,6 +93,9 @@ while getopts "f:b:o:p:d:m:P:t:NRhjLDv" opt; do L) use_llvm_binutils=1 ;; + O) + use_llvm_objcopy=1 + ;; d) variant=$OPTARG ;; @@ -237,7 +243,11 @@ if [[ ${use_llvm_binutils} -eq 1 ]]; then readonly binutils_nm=${tools_path}/llvm-nm readonly binutils_ar=${tools_path}/llvm-ar else - readonly binutils_objcopy=${tools_path}/objcopy + if [[ ${use_llvm_objcopy} -eq 1 ]]; then + readonly binutils_objcopy=${tools_path}/llvm-objcopy + else + readonly binutils_objcopy=${tools_path}/objcopy + fi if [[ -x ${tools_path}/nm-new ]] ; then readonly binutils_nm=${tools_path}/nm-new else diff --git a/build_scripts/other/zip_package.sh b/build_scripts/other/zip_package.sh new file mode 100755 index 0000000000..7270ef3332 --- /dev/null +++ b/build_scripts/other/zip_package.sh @@ -0,0 +1,91 @@ +#!/bin/bash + +# Copyright 2026 Google LLC +# +# 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. + +# Zip up a directory recursively, preserving symlinks (e.g. inside +# frameworks), as fast as possible. +# +# Info-ZIP's "zip" is single-threaded, which makes zipping the multi-gigabyte +# SDK package very slow. If 7-Zip is available, use it to create the zip file +# with multithreaded compression instead. After creating the archive, verify +# that it contains the same number of regular files and symlinks as the +# source directory; if it doesn't (for example, if this version of 7-Zip +# doesn't support storing symlinks in zip files), fall back to Info-ZIP. +# +# Usage: zip_package.sh +# The directory is added to the archive using the given (relative) path, +# so run this from the parent of . +# +# Environment variables: +# ZIP_PACKAGE_LEVEL: Compression level, 0-9 (default: 6). +# ZIP_PACKAGE_FORCE_INFOZIP: If set to 1, always use Info-ZIP. + +set -e + +if [[ $# -ne 2 ]]; then + echo "Usage: $0 " 1>&2 + exit 2 +fi + +readonly output_zip="$1" +readonly input_dir="$2" +readonly level="${ZIP_PACKAGE_LEVEL:-6}" + +if [[ ! -d "${input_dir}" ]]; then + echo "Directory not found: ${input_dir}" 1>&2 + exit 2 +fi + +# Count the regular files and symlinks in the source directory. +expected_files=$(find "${input_dir}" -type f | wc -l) +expected_links=$(find "${input_dir}" -type l | wc -l) + +verify_zip() { + # zipinfo prints one line per entry, starting with the Unix mode string. + local listing actual_files actual_links + listing=$(zipinfo "$1" 2>/dev/null) || return 1 + actual_files=$(echo "${listing}" | grep -c '^-' || true) + actual_links=$(echo "${listing}" | grep -c '^l' || true) + echo "Zip contains ${actual_files} files and ${actual_links} symlinks" \ + "(expected ${expected_files} and ${expected_links})." + [[ "${actual_files}" -eq "${expected_files}" && + "${actual_links}" -eq "${expected_links}" ]] +} + +sevenzip= +for cmd in 7zz 7z 7za; do + if command -v "${cmd}" > /dev/null; then + sevenzip="${cmd}" + break + fi +done + +rm -f "${output_zip}" +if [[ -n "${sevenzip}" && "${ZIP_PACKAGE_FORCE_INFOZIP}" != "1" ]]; then + echo "Creating ${output_zip} with ${sevenzip} (multithreaded, level ${level})..." + # -snl: store symlinks as links. -mmt=on: multithreaded compression. + # -bso0 -bsp0: suppress the per-file output and progress indicator. + if "${sevenzip}" a -tzip -mx="${level}" -mmt=on -snl -bso0 -bsp0 \ + "${output_zip}" "${input_dir}" && verify_zip "${output_zip}"; then + exit 0 + fi + echo "Warning: ${sevenzip} failed or produced an unexpected archive," \ + "falling back to Info-ZIP." 1>&2 + rm -f "${output_zip}" +fi + +echo "Creating ${output_zip} with Info-ZIP (level ${level})..." +zip -q -"${level}" -r -y "${output_zip}" "${input_dir}" +verify_zip "${output_zip}" diff --git a/scripts/gha/build_desktop.py b/scripts/gha/build_desktop.py index 6cad9e604c..80dabc1eed 100644 --- a/scripts/gha/build_desktop.py +++ b/scripts/gha/build_desktop.py @@ -265,6 +265,18 @@ def main(): cmd = ['cmake', '--build', args.build_dir, '-j', str(os.cpu_count()), '--config', args.config] + if utils.is_windows_os(): + # "-j" above only makes MSBuild build multiple *projects* at once; each + # project's source files are still compiled one at a time unless /MP is + # passed to the compiler. Our own targets pass /MP, but external projects + # (gRPC, Abseil, Protobuf, Firestore, etc.) don't, and the external + # projects' nested builds don't get "-j" either. Large projects like + # grpc.vcxproj and firestore_core.vcxproj are at the end of the dependency + # chain, so they end up compiling on a single core for most of the build. + # The compiler reads extra options from the CL environment variable, which + # is inherited by every cl.exe invocation, including the external projects. + os.environ['CL'] = ('/MP ' + os.environ.get('CL', '')).strip() + print('Setting CL=%s to enable parallel compilation.' % os.environ['CL']) if args.target: # Example: cmake --build build -j 8 --target firebase_app firebase_auth cmd.append('--target') diff --git a/scripts/merge_libraries.py b/scripts/merge_libraries.py index c7f3e1c11b..74f7c603de 100644 --- a/scripts/merge_libraries.py +++ b/scripts/merge_libraries.py @@ -17,6 +17,7 @@ Optionally allows you to rename C and C++ symbols from certain libraries. """ +import concurrent.futures import hashlib import os import fcntl @@ -103,6 +104,22 @@ "use the given target, via the --target flag. If not set, " "will autodetect target format. If you want to specify " "different input and output formats, separate them with a comma.") +flags.DEFINE_integer( + "jobs", 0, + "Number of object files to process (via objcopy) in parallel. " + "If 0, use the number of CPUs on this machine.") +flags.DEFINE_bool( + "binutils_objcopy_is_llvm", None, + "Whether --binutils_objcopy_cmd is llvm-objcopy rather than GNU objcopy. " + "llvm-objcopy autodetects input formats and does not accept BFD target " + "names, so --force_binutils_target will not be applied to it. If not set, " + "this is autodetected from the objcopy command's filename.") +flags.DEFINE_bool( + "filter_renames_per_archive", True, + "When renaming symbols in each input archive, only pass objcopy the " + "renames for symbols that actually appear in that archive (according to " + "nm). This greatly reduces the size of the symbol redefinition list, which " + "speeds up objcopy considerably.") # Never rename system namespaces by default when --auto_hide_cpp_namespaces is enabled. IMPLICIT_CPP_NAMESPACES_TO_IGNORE = {"std", "type_info", @@ -781,6 +798,12 @@ def run_binutils_command(cmdline, error_output=None, ignore_errors=False): A list of lines of text of the command's stdout. """ global binutils_force_target_format + if cmdline[0] == FLAGS.binutils_objcopy_cmd and FLAGS.binutils_objcopy_is_llvm: + # llvm-objcopy autodetects the input format (including COFF bigobj) and + # writes the output in the same format. It doesn't understand GNU BFD + # target names such as "pe-x86-64", so never pass --target to it, and don't + # attempt the GNU-specific "ambiguous format" retry logic below. + return run_command(cmdline, error_output, ignore_errors) if binutils_force_target_format: # Once we've had to force the format once, assume all subsequent # files use the same format. Also we will need to explicitly specify this @@ -934,6 +957,74 @@ def shutdown_cache(): fcntl.lockf(handle, fcntl.LOCK_UN) +def get_archive_symbols(archive_file): + """Get the symbols in an archive, using the cache if possible. + + Args: + archive_file: Library archive file to read symbols from. + Returns: + Tuple of (defined_symbols, all_symbols), as per read_symbols_from_archive. + """ + key = os.path.abspath(archive_file) + if key not in _cache["symbols"]: + _cache["symbols"][key] = read_symbols_from_archive(archive_file) + return _cache["symbols"][key] + + +def get_unique_object_filename(lib_name_hash, obj_file): + """Get a unique (and not too long) name for an object file in an archive. + + Args: + lib_name_hash: Hash of the name of the archive containing the object file. + obj_file: Name of the object file within the archive. + Returns: + New object filename, of 255 characters or less. + """ + new_obj_file = "%s_%s" % (lib_name_hash, obj_file) + if len(new_obj_file) > 255: + # Filename is above the limit, hash the first N characters to bring + # the length down to 255 or less. + # Hashes are 32 characters plus an underscore. + # If len = 256 hash the first 34 chars. + # If len = 257 hash the first 35 chars. + split = len(new_obj_file) - (255 - 32 - 1) + new_obj_file = "%s_%s" % (hashlib.md5( + new_obj_file[:split].encode(DEFAULT_ENCODING)).hexdigest(), + new_obj_file[split:]) + return new_obj_file + + +def move_object_files(obj_file_moves, redefinition_file, jobs): + """Move (and rename symbols in) a list of object files, in parallel. + + Each object file is processed by a separate objcopy process, so we use a + thread pool to keep several objcopy processes running at once. + + Args: + obj_file_moves: List of (src_obj_file, dest_obj_file) tuples. + redefinition_file: Filename to use for redefining symbols, or None. + jobs: Maximum number of objcopy processes to run at once. + """ + if not obj_file_moves: + return + # Process the first object file on its own. If binutils needs to autodetect + # the target format, run_binutils_command() will set the global + # binutils_force_target_format during this call, which all subsequent + # (parallel) calls will then use. + move_object_file(obj_file_moves[0][0], obj_file_moves[0][1], + redefinition_file) + remaining = obj_file_moves[1:] + if jobs <= 1 or len(remaining) <= 1: + for (src, dest) in remaining: + move_object_file(src, dest, redefinition_file) + return + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as executor: + futures = [executor.submit(move_object_file, src, dest, redefinition_file) + for (src, dest) in remaining] + for future in concurrent.futures.as_completed(futures): + future.result() # Re-raise any exception from the worker thread. + + def main(argv): global binutils_force_target_format binutils_force_target_format = FLAGS.force_binutils_target @@ -960,6 +1051,10 @@ def main(argv): FLAGS.binutils_objcopy_cmd = add_abspath(FLAGS.binutils_objcopy_cmd) FLAGS.demangle_cmds = [add_abspath(c) for c in FLAGS.demangle_cmds] FLAGS.cache = (os.path.abspath(FLAGS.cache) if FLAGS.cache else None) + if FLAGS.binutils_objcopy_is_llvm is None: + FLAGS.binutils_objcopy_is_llvm = ( + "llvm-objcopy" in os.path.basename(FLAGS.binutils_objcopy_cmd)) + jobs = FLAGS.jobs if FLAGS.jobs > 0 else (os.cpu_count() or 1) init_cache() @@ -972,13 +1067,7 @@ def main(argv): [libfile, regex] = libfile_and_regex.split(":", 1) logging.debug("Scanning for C symbols in %s", libfile) regex_compiled = re.compile(regex) - if os.path.abspath(libfile) in _cache["symbols"]: - (defined_symbols, - all_symbols) = _cache["symbols"][os.path.abspath(libfile)] - else: - (defined_symbols, all_symbols) = read_symbols_from_archive(libfile) - _cache["symbols"][os.path.abspath(libfile)] = (defined_symbols, - all_symbols) + (defined_symbols, all_symbols) = get_archive_symbols(libfile) for symbol in defined_symbols: # For C symbols, only use them if they are defined. if (not is_cpp_symbol(symbol)) and regex_compiled.match(symbol): @@ -994,14 +1083,7 @@ def main(argv): all_defined_symbols = set() for input_path in input_paths + additional_input_paths: logging.debug("Scanning for C++ symbols in %s", input_path[1]) - if os.path.abspath(input_path[1]) in _cache["symbols"]: - (defined_symbols, - all_symbols) = _cache["symbols"][os.path.abspath(input_path[1])] - else: - (defined_symbols, - all_symbols) = read_symbols_from_archive(input_path[1]) - _cache["symbols"][os.path.abspath(input_path[1])] = (defined_symbols, - all_symbols) + (defined_symbols, all_symbols) = get_archive_symbols(input_path[1]) cpp_symbols.update(all_symbols if FLAGS.rename_external_cpp_symbols else defined_symbols) @@ -1016,14 +1098,30 @@ def main(argv): rename_symbols.update(rename_symbol(symbol)) shutdown_demanglers() - logging.debug("Creating symbol redefinition file for %d symbols", - len(rename_symbols)) - symbol_redefinition_file = create_symbol_redefinition_file(rename_symbols) + logging.debug("Found %d symbols to rename", len(rename_symbols)) + if not FLAGS.filter_renames_per_archive: + # Use a single redefinition file for all input archives. + logging.debug("Creating symbol redefinition file for %d symbols", + len(rename_symbols)) + symbol_redefinition_file = create_symbol_redefinition_file(rename_symbols) # List of all object files, which will be renamed to have unique names. all_obj_files = [] for input_path in input_paths: logging.debug("Checking input archive %s", input_path[1]) + if FLAGS.filter_renames_per_archive: + # objcopy's cost scales with the number of symbol redefinitions it is + # given, and the full list of renames (from all input libraries, scan + # libraries, and hidden libraries) is often far larger than what any + # single archive uses. Only pass along the renames for symbols that + # actually appear in this archive. + (_, archive_symbols) = get_archive_symbols(input_path[1]) + archive_renames = {old: new for (old, new) in rename_symbols.items() + if old in archive_symbols} + logging.debug("Creating symbol redefinition file for %d of %d symbols", + len(archive_renames), len(rename_symbols)) + symbol_redefinition_file = create_symbol_redefinition_file( + archive_renames) # Create a unique directory name from a hash of the input filename. lib_name_hash = hashlib.md5( input_path[0].encode(DEFAULT_ENCODING)).hexdigest() @@ -1054,23 +1152,14 @@ def main(argv): if symbol_redefinition_file: logging.debug("Redefining symbols in %d files", len(obj_file_list)) - for obj_file in obj_file_list: - new_obj_file = "%s_%s" % (lib_name_hash, obj_file) - if len(new_obj_file) > 255: - # Filename is above the limit, hash the first N characters to bring - # the length down to 255 or less. - # Hashes are 32 characters plus an underscore. - # If len = 256 hash the first 34 chars. - # If len = 257 hash the first 35 chars. - split = len(new_obj_file) - (255 - 32 - 1) - new_obj_file = "%s_%s" % (hashlib.md5( - new_obj_file[:split].encode(DEFAULT_ENCODING)).hexdigest(), - new_obj_file[split:]) - - # Move the .o file to its new name, renaming symbols if needed. - move_object_file(obj_file, new_obj_file, symbol_redefinition_file.name - if symbol_redefinition_file else None) - all_obj_files.append(new_obj_file) + # Move each .o file to its new name, renaming symbols if needed. + obj_file_moves = [ + (obj_file, get_unique_object_filename(lib_name_hash, obj_file)) + for obj_file in obj_file_list + ] + move_object_files(obj_file_moves, symbol_redefinition_file.name + if symbol_redefinition_file else None, jobs) + all_obj_files.extend([dest for (_, dest) in obj_file_moves]) symbol_redefinition_file = None From c6b0889008bd413f1dc17d0aac57567bc9279b2b Mon Sep 17 00:00:00 2001 From: Anthony Maurice Date: Mon, 23 Nov 2026 21:31:33 +0000 Subject: [PATCH 2/6] Log per-phase timing in merge_libraries.py Windows Debug packaging still spends 40-50 minutes merging firebase_firestore.lib after all other libraries are done, but the logs don't show where that time goes. Log (at INFO level, enabled by default via --log_timing) how long each phase takes: loading the cache, scanning C and C++ symbols, finding namespaces, computing renames, filtering renames, extracting archives, objcopy, creating the output archive, and saving the cache, along with symbol/demangle cache misses and counts. Also log each input archive that takes longer than --log_timing_archive_threshold seconds (default 10). Every line is tagged with the output library name, since package.sh runs merges in parallel. --- scripts/merge_libraries.py | 255 +++++++++++++++++++++++++++---------- 1 file changed, 185 insertions(+), 70 deletions(-) diff --git a/scripts/merge_libraries.py b/scripts/merge_libraries.py index 74f7c603de..a733b6573b 100644 --- a/scripts/merge_libraries.py +++ b/scripts/merge_libraries.py @@ -18,6 +18,7 @@ """ import concurrent.futures +import contextlib import hashlib import os import fcntl @@ -26,6 +27,7 @@ import shutil import subprocess import tempfile +import time from absl import app from absl import flags from absl import logging @@ -120,6 +122,14 @@ "renames for symbols that actually appear in that archive (according to " "nm). This greatly reduces the size of the symbol redefinition list, which " "speeds up objcopy considerably.") +flags.DEFINE_bool( + "log_timing", True, + "Log how long each phase of merging takes (at INFO level), to help find " + "bottlenecks.") +flags.DEFINE_float( + "log_timing_archive_threshold", 10.0, + "With --log_timing, also log a line for each input archive that takes at " + "least this many seconds to extract and process.") # Never rename system namespaces by default when --auto_hide_cpp_namespaces is enabled. IMPLICIT_CPP_NAMESPACES_TO_IGNORE = {"std", "type_info", @@ -341,6 +351,10 @@ def replace_strings_in_archive(archive_path, replacements): # Running C++ name demangler processes, in the order we will query them. _demanglers = [] +# Number of symbols that weren't already in the demangle cache, which means +# they had to be sent through the demangler processes. +_demangle_cache_misses = 0 + def init_demanglers(): """Initialize the demanglers. @@ -376,6 +390,8 @@ def demangle_symbol(symbol): if FLAGS.platform == "windows": symbol = re.sub(r"^\$[^$]*\$", "", symbol) # Filter out "$pdata$" etc. if symbol not in _cache["demangle"][FLAGS.platform]: + global _demangle_cache_misses + _demangle_cache_misses += 1 _cache["demangle"][FLAGS.platform][symbol] = symbol # Default: no change for demangler in _demanglers: demangled_symbol = demangler.demangle(symbol) @@ -965,12 +981,60 @@ def get_archive_symbols(archive_file): Returns: Tuple of (defined_symbols, all_symbols), as per read_symbols_from_archive. """ + global _symbol_cache_misses key = os.path.abspath(archive_file) if key not in _cache["symbols"]: + _symbol_cache_misses += 1 _cache["symbols"][key] = read_symbols_from_archive(archive_file) return _cache["symbols"][key] +# Number of archives whose symbols weren't already in the cache. +_symbol_cache_misses = 0 + + +class PhaseTimer(object): + """Measures and logs how long each phase of merging takes. + + Every log line is tagged with the output library name, since package.sh runs + several instances of this script in parallel and their output interleaves. + """ + + def __init__(self, label, enabled): + self.label = label + self.enabled = enabled + self.start_time = time.monotonic() + self.totals = {} # Phase name -> total seconds. Preserves insertion order. + + def log(self, message, *args): + if self.enabled: + logging.info("[timing %s] " + message, self.label, *args) + + @contextlib.contextmanager + def phase(self, name, log=True): + """Context manager that times a phase, adding it to the totals. + + Args: + name: Name of the phase. + log: If True, log the time for this phase when it finishes. Set this to + False for phases that run many times; they are still included in the + summary. + """ + start = time.monotonic() + try: + yield + finally: + elapsed = time.monotonic() - start + self.totals[name] = self.totals.get(name, 0.0) + elapsed + if log: + self.log("%s: %.1fs", name, elapsed) + + def log_summary(self): + total = time.monotonic() - self.start_time + self.log("TOTAL %.1fs | %s", total, ", ".join( + "%s %.1fs" % (name, secs) for (name, secs) in self.totals.items())) + + def get_unique_object_filename(lib_name_hash, obj_file): """Get a unique (and not too long) name for an object file in an archive. @@ -1055,23 +1119,33 @@ def main(argv): FLAGS.binutils_objcopy_is_llvm = ( "llvm-objcopy" in os.path.basename(FLAGS.binutils_objcopy_cmd)) jobs = FLAGS.jobs if FLAGS.jobs > 0 else (os.cpu_count() or 1) + timer = PhaseTimer(os.path.basename(output_path), FLAGS.log_timing) + timer.log("Merging %d input libraries (%d scan libraries) with %d jobs", + len(input_paths), len(additional_input_paths), jobs) - init_cache() + with timer.phase("load cache"): + init_cache() + timer.log("Cache contains symbols for %d libraries and %d demangled " + "symbols", len(_cache["symbols"]), + len(_cache["demangle"][FLAGS.platform])) # Scan through subset of libs in FLAGS.hide_c_symbols to find C symbols to # rename. rename_symbols = {} - for libfile_and_regex in FLAGS.hide_c_symbols: - if ':' not in libfile_and_regex: - libfile_and_regex += ':.' - [libfile, regex] = libfile_and_regex.split(":", 1) - logging.debug("Scanning for C symbols in %s", libfile) - regex_compiled = re.compile(regex) - (defined_symbols, all_symbols) = get_archive_symbols(libfile) - for symbol in defined_symbols: - # For C symbols, only use them if they are defined. - if (not is_cpp_symbol(symbol)) and regex_compiled.match(symbol): - rename_symbols.update(rename_symbol(symbol)) + with timer.phase("scan C symbols"): + for libfile_and_regex in FLAGS.hide_c_symbols: + if ':' not in libfile_and_regex: + libfile_and_regex += ':.' + [libfile, regex] = libfile_and_regex.split(":", 1) + logging.debug("Scanning for C symbols in %s", libfile) + regex_compiled = re.compile(regex) + (defined_symbols, all_symbols) = get_archive_symbols(libfile) + for symbol in defined_symbols: + # For C symbols, only use them if they are defined. + if (not is_cpp_symbol(symbol)) and regex_compiled.match(symbol): + rename_symbols.update(rename_symbol(symbol)) + timer.log("Found %d C symbols to rename in %d libraries", + len(rename_symbols), len(FLAGS.hide_c_symbols)) os.chdir(working_root) @@ -1081,21 +1155,40 @@ def main(argv): # hide_cpp_namespaces. cpp_symbols = set() all_defined_symbols = set() - for input_path in input_paths + additional_input_paths: - logging.debug("Scanning for C++ symbols in %s", input_path[1]) - (defined_symbols, all_symbols) = get_archive_symbols(input_path[1]) - cpp_symbols.update(all_symbols - if FLAGS.rename_external_cpp_symbols - else defined_symbols) - all_defined_symbols.update(defined_symbols) + with timer.phase("scan C++ symbols"): + for input_path in input_paths + additional_input_paths: + logging.debug("Scanning for C++ symbols in %s", input_path[1]) + (defined_symbols, all_symbols) = get_archive_symbols(input_path[1]) + cpp_symbols.update(all_symbols + if FLAGS.rename_external_cpp_symbols + else defined_symbols) + all_defined_symbols.update(defined_symbols) + timer.log("Scanned %d libraries (%d not cached): %d symbols, %d defined", + len(input_paths) + len(additional_input_paths), + _symbol_cache_misses, len(cpp_symbols), + len(all_defined_symbols)) # If we are set to scan for namespaces, do that now. if FLAGS.auto_hide_cpp_namespaces: - add_automatic_namespaces(all_defined_symbols) - - for symbol in cpp_symbols: - if is_cpp_symbol(symbol): - rename_symbols.update(rename_symbol(symbol)) + demangle_misses_before = _demangle_cache_misses + with timer.phase("find namespaces"): + add_automatic_namespaces(all_defined_symbols) + timer.log("Found %d namespaces to hide (%d symbols demangled)", + len(FLAGS.hide_cpp_namespaces), + _demangle_cache_misses - demangle_misses_before) + + demangle_misses_before = _demangle_cache_misses + num_cpp_symbols = 0 + with timer.phase("compute C++ renames"): + for symbol in cpp_symbols: + if is_cpp_symbol(symbol): + num_cpp_symbols += 1 + rename_symbols.update(rename_symbol(symbol)) + timer.log("Checked %d C++ symbols against %d namespaces " + "(%d symbols demangled); %d total symbols to rename", + num_cpp_symbols, len(FLAGS.hide_cpp_namespaces), + _demangle_cache_misses - demangle_misses_before, + len(rename_symbols)) shutdown_demanglers() logging.debug("Found %d symbols to rename", len(rename_symbols)) @@ -1107,47 +1200,58 @@ def main(argv): # List of all object files, which will be renamed to have unique names. all_obj_files = [] + total_renames_passed = 0 for input_path in input_paths: logging.debug("Checking input archive %s", input_path[1]) + archive_start = time.monotonic() + archive_name = os.path.basename(input_path[0]) if FLAGS.filter_renames_per_archive: # objcopy's cost scales with the number of symbol redefinitions it is # given, and the full list of renames (from all input libraries, scan # libraries, and hidden libraries) is often far larger than what any # single archive uses. Only pass along the renames for symbols that # actually appear in this archive. - (_, archive_symbols) = get_archive_symbols(input_path[1]) - archive_renames = {old: new for (old, new) in rename_symbols.items() - if old in archive_symbols} - logging.debug("Creating symbol redefinition file for %d of %d symbols", - len(archive_renames), len(rename_symbols)) - symbol_redefinition_file = create_symbol_redefinition_file( - archive_renames) + with timer.phase("filter renames", log=False): + (_, archive_symbols) = get_archive_symbols(input_path[1]) + archive_renames = {old: new for (old, new) in rename_symbols.items() + if old in archive_symbols} + logging.debug( + "Creating symbol redefinition file for %d of %d symbols", + len(archive_renames), len(rename_symbols)) + symbol_redefinition_file = create_symbol_redefinition_file( + archive_renames) + num_renames = len(archive_renames) + else: + num_renames = len(rename_symbols) + total_renames_passed += num_renames # Create a unique directory name from a hash of the input filename. lib_name_hash = hashlib.md5( input_path[0].encode(DEFAULT_ENCODING)).hexdigest() - (obj_file_list, errors) = list_objects_in_archive(input_path[1]) - if errors: - logging.fatal("Error listing archive %s: %s", input_path[1], errors) - - # If any of the filenames in this archive contain a "/" or "\", we need to - # replace them with "_". - obj_file_renames = {} - for obj_file in obj_file_list: - if "/" in obj_file or "\\" in obj_file: - # Extracting this will fail because it contains subdirectories. - obj_file_bin = obj_file.encode(DEFAULT_ENCODING) - new_obj_file_bin = re.sub(b"[^0-9a-zA-Z_.]", b"_", obj_file_bin) - old_obj_regex_bin = re.sub(b"[^0-9a-zA-Z_.]", b".", obj_file_bin) - obj_file_renames[old_obj_regex_bin] = new_obj_file_bin - if obj_file_renames: - # We renamed some object files within the .a file. - input_path[1] = replace_strings_in_archive(input_path[1], - obj_file_renames) - - logging.debug("Extracting input archive %s", input_path[1]) - (obj_file_list, errors) = extract_archive(input_path[1]) - if errors: - logging.fatal("Error extracting archive %s: %s", input_path[1], errors) + with timer.phase("extract archives", log=False): + (obj_file_list, errors) = list_objects_in_archive(input_path[1]) + if errors: + logging.fatal("Error listing archive %s: %s", input_path[1], errors) + + # If any of the filenames in this archive contain a "/" or "\", we + # need to replace them with "_". + obj_file_renames = {} + for obj_file in obj_file_list: + if "/" in obj_file or "\\" in obj_file: + # Extracting this will fail because it contains subdirectories. + obj_file_bin = obj_file.encode(DEFAULT_ENCODING) + new_obj_file_bin = re.sub(b"[^0-9a-zA-Z_.]", b"_", obj_file_bin) + old_obj_regex_bin = re.sub(b"[^0-9a-zA-Z_.]", b".", obj_file_bin) + obj_file_renames[old_obj_regex_bin] = new_obj_file_bin + if obj_file_renames: + # We renamed some object files within the .a file. + input_path[1] = replace_strings_in_archive(input_path[1], + obj_file_renames) + + logging.debug("Extracting input archive %s", input_path[1]) + (obj_file_list, errors) = extract_archive(input_path[1]) + if errors: + logging.fatal("Error extracting archive %s: %s", input_path[1], + errors) if symbol_redefinition_file: logging.debug("Redefining symbols in %d files", len(obj_file_list)) @@ -1157,29 +1261,40 @@ def main(argv): (obj_file, get_unique_object_filename(lib_name_hash, obj_file)) for obj_file in obj_file_list ] - move_object_files(obj_file_moves, symbol_redefinition_file.name - if symbol_redefinition_file else None, jobs) + with timer.phase("objcopy", log=False): + move_object_files(obj_file_moves, symbol_redefinition_file.name + if symbol_redefinition_file else None, jobs) all_obj_files.extend([dest for (_, dest) in obj_file_moves]) - + archive_elapsed = time.monotonic() - archive_start + if archive_elapsed >= FLAGS.log_timing_archive_threshold: + timer.log(" %s: %.1fs (%d objects, %d renames)", archive_name, + archive_elapsed, len(obj_file_list), num_renames) + + timer.log("Processed %d objects from %d input libraries (%d renames " + "passed to objcopy in total)", len(all_obj_files), + len(input_paths), total_renames_passed) symbol_redefinition_file = None # Remove any existing output lib so we can create a new one from scratch. if os.path.isfile(output_path): os.remove(output_path) - if (FLAGS.skip_creating_archives): - output_path_dir = output_path + ".dir" - logging.debug("Copying object files to %s", output_path_dir) - if not os.path.exists(output_path_dir): - os.makedirs(output_path_dir) - for obj_file in all_obj_files: - logging.debug("Copy %s to %s" % (obj_file, os.path.join(output_path_dir, os.path.basename(obj_file)))) - shutil.copyfile(obj_file, os.path.join(output_path_dir, os.path.basename(obj_file))) - else: - logging.debug("Creating output archive %s", output_path) - create_archive(output_path, all_obj_files, input_path[1]) - - shutdown_cache() + with timer.phase("create archive"): + if (FLAGS.skip_creating_archives): + output_path_dir = output_path + ".dir" + logging.debug("Copying object files to %s", output_path_dir) + if not os.path.exists(output_path_dir): + os.makedirs(output_path_dir) + for obj_file in all_obj_files: + logging.debug("Copy %s to %s" % (obj_file, os.path.join(output_path_dir, os.path.basename(obj_file)))) + shutil.copyfile(obj_file, os.path.join(output_path_dir, os.path.basename(obj_file))) + else: + logging.debug("Creating output archive %s", output_path) + create_archive(output_path, all_obj_files, input_path[1]) + + with timer.phase("save cache"): + shutdown_cache() + timer.log_summary() except Exception as e: logging.error("Got error: %s", e) From 0df01948a22bd2c70252f1a3e3a2d66af4caf971 Mon Sep 17 00:00:00 2001 From: Anthony Maurice Date: Tue, 1 Dec 2026 23:09:49 +0000 Subject: [PATCH 3/6] Speed up archive extraction and share C++ renames between merges Extraction: when an archive contains duplicate object filenames (e.g. grpc.lib), extract_archive() ran "ar xN " once per object, and each invocation reads through the entire archive. For the Windows x64 Debug grpc.lib (819 objects) this took ~45-50 minutes. Instead, extract in rounds, one "ar xN " invocation per duplicate level with all the applicable member names at once. Output filenames are unchanged. Caching: every product's merge in package.sh scans the same libraries, so the auto-detected namespaces and the C++ symbol renames (938k symbols x 668 namespaces for Windows x64 Debug, 4-6 minutes per merge) are identical each time. Store both in the shared --cache so they're computed once, during the initial "populate cache" run, and reused by the parallel merges. Cache keys include the platform, scanned libraries, namespaces and rename settings. --- scripts/merge_libraries.py | 135 ++++++++++++++++++++++++++++++++----- 1 file changed, 118 insertions(+), 17 deletions(-) diff --git a/scripts/merge_libraries.py b/scripts/merge_libraries.py index a733b6573b..8db5841a46 100644 --- a/scripts/merge_libraries.py +++ b/scripts/merge_libraries.py @@ -258,22 +258,59 @@ def extract_archive(archive_file): run_command([FLAGS.binutils_ar_cmd, "x", archive_file], errors) return (file_list, errors) else: - # Duplicate filenames, so we must extract file by file and rename as we go. - file_counts = {} - output_file_list = [] + # Duplicate filenames, so we can't extract everything at once (later + # copies would overwrite earlier ones). Instead, extract in rounds: in + # round N, extract the Nth copy of every filename that has at least N + # copies, then rename them to "N_filename" before the next round. + # + # Each "ar" invocation reads through the entire archive, so it's important + # to extract many files per invocation rather than one at a time; for + # large archives (e.g. a Windows Debug grpc.lib), extracting files + # individually took the better part of an hour. + file_counts = {} # Preserves order of first appearance. + instance_numbers = [] # For each entry in file_list, which copy it is. for f in file_list: - file_counts[f] = file_counts[f] + 1 if f in file_counts else 1 - - run_command( - [FLAGS.binutils_ar_cmd, "xN", - str(file_counts[f]), archive_file, f], errors) - new_f = os.path.join( - os.path.dirname(f), "%d_%s" % (file_counts[f], os.path.basename(f))) - os.rename(f, new_f) - output_file_list.append(new_f) + file_counts[f] = file_counts.get(f, 0) + 1 + instance_numbers.append(file_counts[f]) + + def renamed(f, n): + return os.path.join(os.path.dirname(f), "%d_%s" % (n, os.path.basename(f))) + + for n in range(1, max(file_counts.values()) + 1): + names = [f for (f, count) in file_counts.items() if count >= n] + for chunk in _chunk_command_args(names): + run_command([FLAGS.binutils_ar_cmd, "xN", str(n), archive_file] + chunk, + errors) + for f in names: + os.rename(f, renamed(f, n)) + output_file_list = [renamed(f, n) + for (f, n) in zip(file_list, instance_numbers)] return (output_file_list, errors) +def _chunk_command_args(args, max_chars=32000): + """Split a list of command-line arguments into chunks of limited length. + + Args: + args: List of arguments to split. + max_chars: Maximum total length of the arguments in each chunk. + Yields: + Lists of arguments, each with a total length of at most max_chars (or a + single argument, if that argument alone exceeds max_chars). + """ + chunk = [] + chunk_chars = 0 + for arg in args: + if chunk and chunk_chars + len(arg) + 1 > max_chars: + yield chunk + chunk = [] + chunk_chars = 0 + chunk.append(arg) + chunk_chars += len(arg) + 1 + if chunk: + yield chunk + + def list_objects_in_archive(archive_file): """List all the object files contained in a library archive. @@ -960,6 +997,44 @@ def init_cache(): _cache.update({"symbols": {}, "demangle": {}}) if FLAGS.platform not in _cache["demangle"]: _cache["demangle"][FLAGS.platform] = {} + # _cache["namespaces"] is indexed by a key describing the libraries scanned + # (see namespaces_cache_key), and holds the namespaces found to hide. + _cache.setdefault("namespaces", {}) + # _cache["cpp_renames"] is indexed by a key describing the namespaces being + # hidden (see cpp_renames_cache_key), then by C++ symbol, and holds the + # renamed symbol. + _cache.setdefault("cpp_renames", {}) + + +def namespaces_cache_key(library_paths): + """Key for caching the results of add_automatic_namespaces. + + Within a single run of package.sh, the symbols in each library file are + cached by path, so the same set of libraries always produces the same set of + namespaces. + + Args: + library_paths: Paths of all of the libraries being scanned. + Returns: + Hashable key. + """ + return (FLAGS.platform, + tuple(sorted(set(os.path.abspath(p) for p in library_paths))), + tuple(sorted(FLAGS.ignore_cpp_namespaces)), + tuple(sorted(FLAGS.hide_cpp_namespaces))) + + +def cpp_renames_cache_key(): + """Key for caching the results of rename_symbol for C++ symbols. + + rename_symbol's result for a C++ symbol depends only on the symbol itself + and the settings below, so it can be shared between runs of this script. + + Returns: + Hashable key. + """ + return (FLAGS.platform, FLAGS.rename_string, FLAGS.strict_cpp, + tuple(sorted(FLAGS.hide_cpp_namespaces))) def shutdown_cache(): @@ -1170,23 +1245,49 @@ def main(argv): # If we are set to scan for namespaces, do that now. if FLAGS.auto_hide_cpp_namespaces: + # Every product's merge (run by package.sh) scans the same set of + # libraries, so the namespaces found are the same each time. Compute + # them once and share them via the cache. + ns_key = namespaces_cache_key( + [p[1] for p in input_paths + additional_input_paths]) + cached_namespaces = _cache["namespaces"].get(ns_key) demangle_misses_before = _demangle_cache_misses with timer.phase("find namespaces"): - add_automatic_namespaces(all_defined_symbols) - timer.log("Found %d namespaces to hide (%d symbols demangled)", + if cached_namespaces is not None: + FLAGS.hide_cpp_namespaces = list(cached_namespaces) + else: + add_automatic_namespaces(all_defined_symbols) + _cache["namespaces"][ns_key] = list(FLAGS.hide_cpp_namespaces) + timer.log("Found %d namespaces to hide (%s, %d symbols demangled)", len(FLAGS.hide_cpp_namespaces), + "cached" if cached_namespaces is not None else "not cached", _demangle_cache_misses - demangle_misses_before) + # Likewise, renaming the C++ symbols is the same for every product, + # so cache the renamed symbols. Checking each symbol against every + # namespace is slow (minutes for a Windows Debug build). + cached_renames = _cache["cpp_renames"].setdefault( + cpp_renames_cache_key(), {}) demangle_misses_before = _demangle_cache_misses num_cpp_symbols = 0 + num_renames_cached = 0 with timer.phase("compute C++ renames"): for symbol in cpp_symbols: if is_cpp_symbol(symbol): num_cpp_symbols += 1 - rename_symbols.update(rename_symbol(symbol)) + new_symbol = cached_renames.get(symbol) + if new_symbol is not None: + num_renames_cached += 1 + rename_symbols[symbol] = new_symbol + else: + new_renames = rename_symbol(symbol) + rename_symbols.update(new_renames) + if symbol in new_renames: + cached_renames[symbol] = new_renames[symbol] timer.log("Checked %d C++ symbols against %d namespaces " - "(%d symbols demangled); %d total symbols to rename", - num_cpp_symbols, len(FLAGS.hide_cpp_namespaces), + "(%d cached, %d symbols demangled); %d total symbols to " + "rename", num_cpp_symbols, len(FLAGS.hide_cpp_namespaces), + num_renames_cached, _demangle_cache_misses - demangle_misses_before, len(rename_symbols)) shutdown_demanglers() From a73d2d4a5195a06871de246f1a8a27b4f071de35 Mon Sep 17 00:00:00 2001 From: Anthony Maurice Date: Wed, 2 Dec 2026 23:41:00 +0000 Subject: [PATCH 4/6] Rename archive members in a single pass The previous commit's batched extraction didn't help: the slow part of "extract archives" for the Windows Debug grpc.lib (~40 minutes) is actually replace_strings_in_archive(). MSVC archive member names contain directory separators, so every member name (819 of them for grpc.lib) gets a binary replacement over the entire archive, and it ran a separate re.sub() pass over the whole (very large) file for each name. Do all the replacements in a single pass instead, using one regex built as a trie of the patterns (so shared prefixes don't make the regex engine try every alternative at every position), and look up each match's replacement. The output is byte-for-byte identical to the old implementation. Also time member renaming separately ("rename members") from extraction. --- scripts/merge_libraries.py | 75 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 71 insertions(+), 4 deletions(-) diff --git a/scripts/merge_libraries.py b/scripts/merge_libraries.py index 8db5841a46..8ad5615e34 100644 --- a/scripts/merge_libraries.py +++ b/scripts/merge_libraries.py @@ -354,6 +354,51 @@ def create_archive(output_archive_file, object_files, old_archive=None): errors) +# Characters that replace_strings_in_archive patterns treat as wildcards. +_NON_NAME_CHARS = re.compile(b"[^0-9a-zA-Z_]") + + +def _build_trie_regex(patterns): + """Combine many patterns into one regex, factoring out common prefixes. + + A plain alternation ("a|b|c|...") of hundreds of patterns makes the regex + engine try every alternative at every position. Sharing common prefixes in + a trie makes the combined regex fast enough to run over a large file. + + Args: + patterns: List of bytes regexes, each consisting of literal [0-9a-zA-Z_] + characters and "." wildcards (as created for replace_strings_in_archive). + Returns: + Compiled regex that matches any of the patterns, preferring longer matches + when one pattern is a prefix of another. + """ + trie = {} + for pattern in patterns: + node = trie + for i in range(len(pattern)): + node = node.setdefault(pattern[i:i + 1], {}) + node[b""] = {} # End of a pattern. + + def build(node): + alternatives = [char + build(child) + for (char, child) in sorted(node.items()) if char] + if not alternatives: + return b"" + if len(alternatives) == 1: + joined = alternatives[0] + else: + joined = b"(?:" + b"|".join(alternatives) + b")" + if b"" in node: + # A pattern can also end here; make the rest optional (greedy, so the + # longer match is preferred). + if len(alternatives) == 1 and len(joined) > 1: + joined = b"(?:" + joined + b")" + return joined + b"?" + return joined + + return re.compile(build(trie), re.DOTALL) + + def replace_strings_in_archive(archive_path, replacements): """Rename object files within a library archive. @@ -376,7 +421,26 @@ def replace_strings_in_archive(archive_path, replacements): logging.error("Can't binary replace '%s' with '%s' (unequal length).", match, replace) return None - file_bytes = re.sub(match, replace, file_bytes) + # Do all of the replacements in a single pass over the archive. (Running a + # separate re.sub() per replacement means re-scanning the whole archive once + # per object file, which took ~45 minutes for a Windows Debug grpc.lib.) + compiled = {match: re.compile(match, re.DOTALL) for match in replacements} + + def replacement_for(m): + text = m.group(0) + # Each pattern is the original filename with its punctuation replaced by + # "." (match any character), so normally we can find which pattern + # matched by doing the same to the matched text. + key = _NON_NAME_CHARS.sub(b".", text) + if key in replacements: + return replacements[key] + for (match, regex) in compiled.items(): + if regex.fullmatch(text): + return replacements[match] + return text + + file_bytes = _build_trie_regex(list(replacements)).sub(replacement_for, + file_bytes) named_tempfile = tempfile.NamedTemporaryFile(suffix=".a") _tempfiles.append(named_tempfile) # Will be cleaned up on program exit. new_filename = os.path.abspath(named_tempfile.name) @@ -1328,7 +1392,7 @@ def main(argv): # Create a unique directory name from a hash of the input filename. lib_name_hash = hashlib.md5( input_path[0].encode(DEFAULT_ENCODING)).hexdigest() - with timer.phase("extract archives", log=False): + with timer.phase("rename members", log=False): (obj_file_list, errors) = list_objects_in_archive(input_path[1]) if errors: logging.fatal("Error listing archive %s: %s", input_path[1], errors) @@ -1348,6 +1412,7 @@ def main(argv): input_path[1] = replace_strings_in_archive(input_path[1], obj_file_renames) + with timer.phase("extract archives", log=False): logging.debug("Extracting input archive %s", input_path[1]) (obj_file_list, errors) = extract_archive(input_path[1]) if errors: @@ -1368,8 +1433,10 @@ def main(argv): all_obj_files.extend([dest for (_, dest) in obj_file_moves]) archive_elapsed = time.monotonic() - archive_start if archive_elapsed >= FLAGS.log_timing_archive_threshold: - timer.log(" %s: %.1fs (%d objects, %d renames)", archive_name, - archive_elapsed, len(obj_file_list), num_renames) + timer.log(" %s: %.1fs (%d objects, %d renames%s)", archive_name, + archive_elapsed, len(obj_file_list), num_renames, + ", %d member names fixed" % len(obj_file_renames) + if obj_file_renames else "") timer.log("Processed %d objects from %d input libraries (%d renames " "passed to objcopy in total)", len(all_obj_files), From 88febc88441ed6f2b8a4e63786467d6f371277dd Mon Sep 17 00:00:00 2001 From: Anthony Maurice Date: Thu, 3 Dec 2026 20:27:23 +0000 Subject: [PATCH 5/6] Remove .drectve section on Windows in merge_libraries.py Switching Windows packaging to llvm-objcopy caused LNK2001 unresolved external symbol errors in Windows Debug integration tests (app_check, database, and firestore) for pre-rename symbols such as p_thread_callback_boringssl, uWS::*, grpc_core::NoDestructSingleton<...>, and grpc_core::arena_detail::ArenaContextTraits<...>. MSVC embeds /INCLUDE: and /EXPORT: directives referencing pre-rename symbol names in the COFF .drectve section. GNU objcopy inadvertently cleared IMAGE_SCN_LNK_INFO on .drectve so MSVC link.exe ignored it, whereas llvm-objcopy preserves IMAGE_SCN_LNK_INFO, causing link.exe to process the stale directives. Strip .drectve alongside .pdata when running objcopy on Windows. --- scripts/merge_libraries.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scripts/merge_libraries.py b/scripts/merge_libraries.py index 8ad5615e34..9f907f74b5 100644 --- a/scripts/merge_libraries.py +++ b/scripts/merge_libraries.py @@ -880,7 +880,13 @@ def move_object_file(src_obj_file, dest_obj_file, redefinition_file=None): output = run_binutils_command( [FLAGS.binutils_objcopy_cmd] + (["--strip-debug"] if FLAGS.strip_debug else []) + - (["--remove-section", ".pdata"] if FLAGS.platform == "windows" else []) + + # On Windows, remove .pdata (unwind info referencing renamed symbols) and + # .drectve (linker directives such as /INCLUDE: and /EXPORT: that embed + # pre-rename symbol names in plain text; GNU objcopy inadvertently cleared + # IMAGE_SCN_LNK_INFO on .drectve so link.exe ignored it, whereas + # llvm-objcopy preserves IMAGE_SCN_LNK_INFO and causes LNK2001 errors). + (["--remove-section", ".pdata", "--remove-section", ".drectve"] + if FLAGS.platform == "windows" else []) + (["--redefine-syms=%s" % redefinition_file] if redefinition_file else []) + [src_obj_file, dest_obj_file], errors, True) From dfffa2f54487af447744cf5ffd1e3369189355fe Mon Sep 17 00:00:00 2001 From: a-maurice Date: Thu, 3 Dec 2026 16:15:01 -0800 Subject: [PATCH 6/6] Update scripts/merge_libraries.py Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- scripts/merge_libraries.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/merge_libraries.py b/scripts/merge_libraries.py index 9f907f74b5..c41836b4f3 100644 --- a/scripts/merge_libraries.py +++ b/scripts/merge_libraries.py @@ -1384,8 +1384,8 @@ def main(argv): # actually appear in this archive. with timer.phase("filter renames", log=False): (_, archive_symbols) = get_archive_symbols(input_path[1]) - archive_renames = {old: new for (old, new) in rename_symbols.items() - if old in archive_symbols} + archive_renames = {old: rename_symbols[old] for old in archive_symbols + if old in rename_symbols} logging.debug( "Creating symbol redefinition file for %d of %d symbols", len(archive_renames), len(rename_symbols))