1#!/bin/bash
2
3# Copyright (c) 2013 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7# For app bundles built with ASan, copies the runtime lib
8# (libclang_rt.asan_osx_dynamic.dylib), on which their executables depend, from
9# the compiler installation path into the bundle and fixes the dylib's install
10# name in the binary to be relative to @executable_path.
11
12set -e
13
14BINARY="${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}"
15BINARY_DIR="$(dirname "${BINARY}")"
16ASAN_DYLIB_NAME=libclang_rt.asan_osx_dynamic.dylib
17ASAN_DYLIB=$(find \
18    "${BUILT_PRODUCTS_DIR}/../../third_party/llvm-build/Release+Asserts/lib/clang/" \
19    -type f -path "*${ASAN_DYLIB_NAME}")
20
21# Find the link to the ASan runtime encoded in the binary.
22BUILTIN_DYLIB_PATH=$(otool -L "${BINARY}" | \
23    sed -Ene 's/^[[:blank:]]+(.*libclang_rt\.asan_osx_dynamic\.dylib).*$/\1/p')
24
25if [[ -z "${BUILTIN_DYLIB_PATH}" ]]; then
26  echo "${BINARY} does not depend on the ASan runtime library!" >&2
27  # TODO(glider): make this return 1 when we fully switch to the dynamic
28  # runtime in ASan.
29  exit 0
30fi
31
32DYLIB_BASENAME=$(basename "${ASAN_DYLIB}")
33if [[ "${DYLIB_BASENAME}" != "${ASAN_DYLIB_NAME}" ]]; then
34  echo "basename(${ASAN_DYLIB}) != ${ASAN_DYLIB_NAME}" >&2
35  exit 1
36fi
37
38# Check whether the directory containing the executable binary is named
39# "MacOS". In this case we're building a full-fledged OSX app and will put
40# the runtime into appname.app/Contents/Libraries/. Otherwise this is probably
41# an iOS gtest app, and the ASan runtime is put next to the executable.
42UPPER_DIR=$(dirname "${BINARY_DIR}")
43if [ "${UPPER_DIR}" == "MacOS" ]; then
44  LIBRARIES_DIR="${UPPER_DIR}/Libraries"
45  mkdir -p "${LIBRARIES_DIR}"
46  NEW_LC_ID_DYLIB="@executable_path/../Libraries/${ASAN_DYLIB_NAME}"
47else
48  LIBRARIES_DIR="${BINARY_DIR}"
49  NEW_LC_ID_DYLIB="@executable_path/${ASAN_DYLIB_NAME}"
50fi
51
52cp "${ASAN_DYLIB}" "${LIBRARIES_DIR}"
53
54# Make LC_ID_DYLIB of the runtime copy point to its location.
55install_name_tool \
56    -id "${NEW_LC_ID_DYLIB}" \
57    "${LIBRARIES_DIR}/${ASAN_DYLIB_NAME}"
58
59# Fix the rpath to the runtime library recorded in the binary.
60install_name_tool \
61    -change "${BUILTIN_DYLIB_PATH}" \
62    "${NEW_LC_ID_DYLIB}" \
63    "${BINARY}"
64