1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "host/libs/image_aggregator/sparse_image_utils.h" 18 19 #include <string.h> 20 21 #include <fstream> 22 23 #include <android-base/logging.h> 24 25 #include "common/libs/utils/subprocess.h" 26 #include "host/libs/config/cuttlefish_config.h" 27 28 const char ANDROID_SPARSE_IMAGE_MAGIC[] = "\x3A\xFF\x26\xED"; 29 namespace cuttlefish { 30 IsSparseImage(const std::string & image_path)31bool IsSparseImage(const std::string& image_path) { 32 std::ifstream file(image_path, std::ios::binary); 33 if (!file) { 34 LOG(FATAL) << "Could not open " << image_path; 35 return false; 36 } 37 char buffer[5] = {0}; 38 file.read(buffer, 4); 39 file.close(); 40 return strcmp(ANDROID_SPARSE_IMAGE_MAGIC, buffer) == 0; 41 } 42 ConvertToRawImage(const std::string & image_path)43bool ConvertToRawImage(const std::string& image_path) { 44 if (!IsSparseImage(image_path)) { 45 LOG(DEBUG) << "Skip non-sparse image " << image_path; 46 return false; 47 } 48 49 auto simg2img_path = HostBinaryPath("simg2img"); 50 Command simg2img_cmd(simg2img_path); 51 std::string tmp_raw_image_path = image_path + ".raw"; 52 simg2img_cmd.AddParameter(image_path); 53 simg2img_cmd.AddParameter(tmp_raw_image_path); 54 55 // Use simg2img to convert sparse image to raw image. 56 int success = simg2img_cmd.Start().Wait(); 57 if (success != 0) { 58 LOG(FATAL) << "Unable to convert Android sparse image " << image_path 59 << " to raw image. " << success; 60 return false; 61 } 62 63 // Replace the original sparse image with the raw image. 64 Command mv_cmd("/bin/mv"); 65 mv_cmd.AddParameter("-f"); 66 mv_cmd.AddParameter(tmp_raw_image_path); 67 mv_cmd.AddParameter(image_path); 68 success = mv_cmd.Start().Wait(); 69 if (success != 0) { 70 LOG(FATAL) << "Unable to replace original sparse image " << success; 71 return false; 72 } 73 74 return true; 75 } 76 77 } // namespace cuttlefish 78