Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crosstool/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ universal_exec_tool(
universal_exec_tool(
name = "exec_libtool",
srcs = ["libtool.cc"],
out = "libtool",
out = "apple-support-ar-wrapper",
)

# TODO: Attempt to remove need for wrapper
Expand Down
144 changes: 138 additions & 6 deletions crosstool/libtool.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,30 @@
// limitations under the License.

#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>

#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <memory>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_set>
#include <vector>

extern char** environ;

const std::regex libRegex = std::regex(".*\\.a$");
const std::regex singleArgFlags = std::regex("-arch_only|-o");
const std::unordered_set<char> supportedArFlags = {
'c', 'r', 'q', 's', 'D',
};

// An RAII temporary directory.
class TempDirectory {
Expand Down Expand Up @@ -201,10 +211,105 @@ bool hasDuplicateBasenames(const std::vector<std::string> files) {
return false;
}

bool hasOnlyArFlags(const std::string& arg) {
if (arg.empty()) {
return false;
}
for (char flag : arg) {
if (supportedArFlags.find(flag) == supportedArFlags.end()) {
return false;
}
}
return true;
}

bool isArTocOnlyInvocation(const std::vector<std::string>& args) {
return args.size() == 2 && args[0].find('s') != std::string::npos &&
args[0].find('c') == std::string::npos &&
args[0].find('r') == std::string::npos &&
args[0].find('q') == std::string::npos;
}

[[noreturn]] void processArTocOnlyArgsAndExit(
const std::vector<std::string>& args) {
const std::string archive = args[1];
if (!regex_match(archive, libRegex)) {
std::cerr << "error: expected archive file after ar flags '" << args[0]
<< "', got '" << archive
<< "'. Please report this to apple_support.\n";
exit(EXIT_FAILURE);
}
if (!std::filesystem::exists(archive)) {
std::cerr << "error: attempted to create TOC but archive file '" << archive
<< "' does not exist. Please report this to apple_support.\n";
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}

bool looksLikeArInvocation(const std::vector<std::string>& args) {
if (args.empty()) {
return false;
}
if (hasOnlyArFlags(args[0])) {
return true;
}
// If the first arg starts with a -, it's unlikely ar which is usually 'ar cr
// libfoo.a foo.o'
if (args[0].empty() || args[0][0] == '-') {
return false;
}
return args.size() >= 2 && regex_match(args[1], libRegex);
}

void processArCreateArgs(
const std::vector<std::string>& args,
std::function<void(const std::string&)> flags_consumer) {
if (!hasOnlyArFlags(args[0])) {
std::cerr << "error: unsupported ar flags '" << args[0]
<< "'. Supported flag characters are 'c', 'r', 'q', 's', "
<< "and 'D'. Please file an issue at "
<< "https://github.com/bazelbuild/apple_support/issues if this "
<< "needs to support another ar invocation.\n";
exit(EXIT_FAILURE);
}
if (args.size() < 2) {
std::cerr << "error: expected output archive after ar flags '" << args[0]
<< "'.\n";
exit(EXIT_FAILURE);
}
if (!regex_match(args[1], libRegex)) {
std::cerr << "error: expected output archive after ar flags '" << args[0]
<< "', got '" << args[1] << "'.\n";
exit(EXIT_FAILURE);
}
if (args.size() < 3) {
std::cerr
<< "error: expected at least one input file after output archive '"
<< args[1] << "'.\n";
exit(EXIT_FAILURE);
}

flags_consumer("-static");
flags_consumer("-D"); // NOTE: Always added for hermiticity
flags_consumer("-o");
flags_consumer(args[1]);
}

void processArgs(const std::vector<std::string> args,
std::function<void(const std::string&)> flags_consumer,
std::function<void(const std::string&)> files_consumer) {
for (auto it = args.begin(); it != args.end(); ++it) {
auto start = args.begin();
if (looksLikeArInvocation(args)) {
if (isArTocOnlyInvocation(args)) {
processArTocOnlyArgsAndExit(args);
}

processArCreateArgs(args, flags_consumer);
start += 2;
}

for (auto it = start; it != args.end(); ++it) {
const std::string arg = *it;
if (arg == "-filelist") {
++it;
Expand Down Expand Up @@ -236,6 +341,26 @@ void processArgs(const std::vector<std::string> args,
}
}

void logInvocation(const std::vector<std::string>& invocation_args,
const std::vector<std::string>& processed_args) {
bool first = true;
auto log_arg = [&](const std::string& arg) {
if (!first) {
std::cout << ' ';
}
std::cout << arg;
first = false;
};

for (const std::string& arg : invocation_args) {
log_arg(arg);
}
for (const std::string& arg : processed_args) {
log_arg(arg);
}
std::cout << "\n";
}

std::string hash(const std::string& input) {
std::hash<std::string> hasher;
size_t hashValue = hasher(input);
Expand Down Expand Up @@ -295,6 +420,17 @@ int main(int argc, const char* argv[]) {
processed_args.insert(processed_args.end(), files.begin(), files.end());
}

std::vector<std::string> invocation_args = {
"/usr/bin/xcrun",
"libtool",
};

// Used for testing.
if (getenv("__LIBTOOL_LOG_ONLY")) {
logInvocation(invocation_args, processed_args);
return EXIT_SUCCESS;
}

auto response_file = temp_directory->GetPath() / "bazel_libtool.params";
std::ofstream response_file_stream(response_file);
for (const auto& arg : processed_args) {
Expand All @@ -309,11 +445,7 @@ int main(int argc, const char* argv[]) {
}
response_file_stream.close();

std::vector<std::string> invocation_args = {
"/usr/bin/xcrun",
"libtool",
"@" + response_file.u8string(),
};
invocation_args.push_back("@" + response_file.u8string());

if (!runSubProcess(invocation_args)) {
return EXIT_FAILURE;
Expand Down
2 changes: 2 additions & 0 deletions test/rules/action_command_line_test.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ def _action_command_line_test_impl(ctx):
if action.argv[0] not in [
"/usr/bin/ar",
"external/local_config_cc/libtool",
"external/local_config_cc/apple-support-ar-wrapper",
"external/local_config_apple_cc/libtool",
"external/local_config_apple_cc/apple-support-ar-wrapper",
]
]
if len(matching_actions) != 1 and ctx.attr.argv_filter:
Expand Down
11 changes: 11 additions & 0 deletions test/shell/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ sh_library(
],
)

sh_test(
name = "libtool_test",
size = "small",
srcs = ["libtool_test.sh"],
data = [
":bashunit",
"//crosstool:apple-support-ar-wrapper",
"@bazel_tools//tools/bash/runfiles",
],
)

sh_test(
name = "wrapped_clang_test",
size = "small",
Expand Down
166 changes: 166 additions & 0 deletions test/shell/libtool_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
#!/bin/bash
# -*- coding: utf-8 -*-

# Copyright 2026 The Bazel Authors. All rights reserved.
#
# 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.

# Unit tests for libtool.

# --- begin runfiles.bash initialization ---
# Copy-pasted from Bazel's Bash runfiles library (tools/bash/runfiles/runfiles.bash).
set -euo pipefail
if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
if [[ -f "$0.runfiles_manifest" ]]; then
export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
elif [[ -f "$0.runfiles/MANIFEST" ]]; then
export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
export RUNFILES_DIR="$0.runfiles"
fi
fi
if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
"$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
else
echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
exit 1
fi
# --- end runfiles.bash initialization ---


# Load test environment
source "$(rlocation "apple_support/test/shell/unittest.bash")" \
|| { echo "unittest.bash not found!" >&2; exit 1; }
LIBTOOL=$(rlocation "apple_support/crosstool/apple-support-ar-wrapper")


# This env var tells libtool to log its command instead of running.
export __LIBTOOL_LOG_ONLY=1

function assert_command() {
local expected=$1
assert_equals "${expected}" "$(cat "${TEST_log}")"
}

function test_libtool_args() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" -D -no_warning_for_no_symbols -static -o output.a a.o b.o \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -D -no_warning_for_no_symbols -static -o output.a a.o b.o"
}

function test_ar_args() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" crs output.a a.o b.o \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -static -D -o output.a a.o b.o"
}

function test_ar_args_in_params_file() {
params=$(mktemp)
{
echo "crs"
echo "output.a"
echo "a.o"
echo "b.o"
} > "${params}"

env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" "@${params}" \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -static -D -o output.a a.o b.o"
}

function test_ar_args_with_input_params_file() {
params=$(mktemp)
{
echo "a.o"
echo "b.o"
} > "${params}"

env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" crs output.a "@${params}" \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -static -D -o output.a a.o b.o"
}

function test_ar_args_require_output_archive() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" crs \
>"${TEST_log}" 2>&1 && fail "libtool succeeded";
expect_log "expected output archive after ar flags 'crs'"
}

function test_ar_args_require_archive_extension() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" crs output.o input.o \
>"${TEST_log}" 2>&1 && fail "libtool succeeded";
expect_log "expected output archive after ar flags 'crs', got 'output.o'"
}

function test_ar_args_require_input_file() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" crs output.a \
>"${TEST_log}" 2>&1 && fail "libtool succeeded";
expect_log "expected at least one input file after output archive 'output.a'"
}

function test_ar_args_rust() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" cq output.a a.o b.o \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -static -D -o output.a a.o b.o"
}

function test_deterministic_ar_args() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" crsD output.a a.o b.o \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -static -D -o output.a a.o b.o"
}

function test_reordered_ar_args() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" rcs output.a a.o b.o \
>"${TEST_log}" || fail "libtool failed";
assert_command "/usr/bin/xcrun libtool -static -D -o output.a a.o b.o"
}

function test_ar_args_reject_unsupported_flags() {
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" ctx output.a a.o b.o \
>"${TEST_log}" 2>&1 && fail "libtool succeeded";
expect_log "unsupported ar flags 'ctx'"
}

function test_ar_toc_only_existing_archive() {
archive="${TEST_TMPDIR}/existing.a"
touch "${archive}"
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" s "${archive}" \
>"${TEST_log}" || fail "libtool failed";
assert_command ""
}

function test_ar_toc_only_requires_existing_archive() {
archive="${TEST_TMPDIR}/missing.a"
env DEVELOPER_DIR=developer SDKROOT=sdk \
"${LIBTOOL}" s "${archive}" \
>"${TEST_log}" 2>&1 && fail "libtool succeeded";
expect_log "archive file '${archive}' does not exist"
}

run_suite "libtool tests"
Loading