1# Copyright 2021 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15load( 16 "@bazel_skylib//lib:paths.bzl", 17 "paths", 18) 19 20def _rpath(go, library, executable = None): 21 """Returns the potential rpaths of a library, possibly relative to another file.""" 22 if not executable: 23 return [paths.dirname(library.short_path)] 24 25 origin = go.mode.goos == "darwin" and "@loader_path" or "$ORIGIN" 26 27 # Accomodate for two kinds of executable paths. 28 rpaths = [] 29 30 # 1. Where the executable is inside its own .runfiles directory. 31 # This is the case for generated libraries as well as remote builds. 32 # a) go back to the workspace root from the executable file in .runfiles 33 depth = executable.short_path.count("/") 34 back_to_root = paths.join(*([".."] * depth)) 35 36 # b) then walk back to the library's short path 37 rpaths.append(paths.join(origin, back_to_root, paths.dirname(library.short_path))) 38 39 # 2. Where the executable is outside the .runfiles directory: 40 # This is the case for local pre-built libraries, as well as local 41 # generated libraries. 42 runfiles_dir = paths.basename(executable.short_path) + ".runfiles" 43 rpaths.append(paths.join(origin, runfiles_dir, go._ctx.workspace_name, paths.dirname(library.short_path))) 44 45 return rpaths 46 47def _flags(go, *args, **kwargs): 48 """Returns the rpath linker flags for a library.""" 49 return ["-Wl,-rpath," + p for p in _rpath(go, *args, **kwargs)] 50 51def _install_name(f): 52 """Returns the install name for a dylib on macOS.""" 53 return f.short_path 54 55rpath = struct( 56 flags = _flags, 57 install_name = _install_name, 58 rpath = _rpath, 59) 60