1#!/system/bin/sh
2#
3# Copyright (C) 2016 The Android Open Source Project
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# create files with 644 (global read) permissions.
18umask 022
19
20# Helper function to copy files
21function do_copy() {
22  source_file=$1
23  dest_name=$2
24  # Move to a temporary file so we can do a rename and have the preopted file
25  # appear atomically in the filesystem.
26  temp_dest_name=${dest_name}.tmp
27  if ! cp ${source_file} ${temp_dest_name} ; then
28    log -p w -t cppreopts "Unable to copy file ${source_file} to ${temp_dest_name}!"
29  else
30    log -p i -t cppreopts "Copied file from ${source_file} to ${temp_dest_name}"
31    sync
32    if ! mv ${temp_dest_name} ${dest_name} ; then
33      log -p w -t cppreopts "Unable to rename temporary file from ${temp_dest_name} to ${dest_name}"
34      rm ${temp_dest_name} || log -p w -t cppreopts "Unable to remove temporary file ${temp_dest_name}"
35    else
36      log -p i -t cppreopts "Renamed temporary file from ${temp_dest_name} to ${dest_name}"
37    fi
38  fi
39}
40
41if [ $# -eq 1 ]; then
42  # Where the system_b is mounted that contains the preopt'd files
43  mountpoint=$1
44
45  if ! test -f ${mountpoint}/system-other-odex-marker ; then
46    log -p i -t cppreopts "system_other partition does not appear to have been built to contain preopted files."
47    exit 1
48  fi
49
50  log -p i -t cppreopts "cppreopts from ${mountpoint}"
51  # For each odex and vdex file do the copy task
52  # NOTE: this implementation will break in any path with spaces to favor
53  # background copy tasks
54  for file in $(find ${mountpoint} -type f -name "*.odex" -o -type f -name "*.vdex" -o -type f -name "*.art"); do
55    real_name=${file/${mountpoint}/\/system}
56    dest_name=$(preopt2cachename ${real_name})
57    if ! test $? -eq 0 ; then
58      log -p i -t cppreopts "Unable to figure out destination for ${file}"
59      continue
60    fi
61    # Copy files in background to speed things up
62    do_copy ${file} ${dest_name} &
63  done
64  # Wait for jobs to finish
65  wait
66  exit 0
67else
68  log -p e -t cppreopts "Usage: cppreopts <preopts-mount-point>"
69  exit 1
70fi
71