1#!/bin/bash -e
2
3# Copyright 2019 Google Inc. All rights reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# Script to extract and repack an archive with specified object files.
18# Inputs:
19#  Environment:
20#   CLANG_BIN: path to the clang bin directory
21#  Arguments:
22#   -i ${file}: input file
23#   -o ${file}: output file
24#   -d ${file}: deps file
25
26set -o pipefail
27
28OPTSTRING=d:i:o:
29
30usage() {
31    cat <<EOF
32Usage: archive_repack.sh [options] <objects to repack>
33
34OPTIONS:
35    -i <file>: input file
36    -o <file>: output file
37    -d <file>: deps file
38EOF
39    exit 1
40}
41
42while getopts $OPTSTRING opt; do
43    case "$opt" in
44        d) depsfile="${OPTARG}" ;;
45        i) infile="${OPTARG}" ;;
46        o) outfile="${OPTARG}" ;;
47        ?) usage ;;
48    esac
49done
50shift "$(($OPTIND -1))"
51
52if [ -z "${infile}" ]; then
53    echo "-i argument is required"
54    usage
55fi
56
57if [ -z "${outfile}" ]; then
58    echo "-o argument is required"
59    usage
60fi
61
62# Produce deps file
63if [ ! -z "${depsfile}" ]; then
64    cat <<EOF > "${depsfile}"
65${outfile}: ${infile} ${CLANG_BIN}/llvm-ar
66EOF
67fi
68
69# Get absolute path for outfile and llvm-ar.
70LLVM_AR="${PWD}/${CLANG_BIN}/llvm-ar"
71if [[ "$outfile" != /* ]]; then
72    outfile="${PWD}/${outfile}"
73fi
74
75tempdir="${outfile}.tmp"
76
77# Clean up any previous temporary files.
78rm -f "${outfile}"
79rm -rf "${tempdir}"
80
81# Do repack
82# We have to change working directory since ar only allows extracting to CWD.
83mkdir "${tempdir}"
84cp "${infile}" "${tempdir}/archive"
85cd "${tempdir}"
86"${LLVM_AR}" x "archive"
87"${LLVM_AR}" --format=gnu qc "${outfile}" "$@"
88