1#!/usr/bin/env python 2# coding: utf-8 3# Copyright (c) 2021 Huawei Device Co., Ltd. 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 16import os 17import sys 18import subprocess 19import shutil 20import tempfile 21 22 23def run_cmd(cmd): 24 res = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE, 25 stderr=subprocess.PIPE) 26 sout, serr = res.communicate() 27 28 return res.pid, res.returncode, sout, serr 29 30 31def build_rootdir(src_dir): 32 tmp_dir = tempfile.mkdtemp(prefix="tmp") 33 index = src_dir.rfind('/') 34 root_dir = "%sroot" % src_dir[:index + 1] 35 36 if root_dir: 37 shutil.rmtree(tmp_dir) 38 shutil.copytree(root_dir, tmp_dir, symlinks=True) 39 tmp_dir_system = os.path.join(tmp_dir, "system") 40 shutil.rmtree(tmp_dir_system, ignore_errors=True) 41 shutil.copytree(src_dir, tmp_dir_system, symlinks=True) 42 return tmp_dir 43 44 45def load_config(config_file): 46 mk_configs = [] 47 with open(config_file, "r") as file: 48 for line in file: 49 line = line.strip() 50 if not line or line.startswith("#"): 51 continue 52 mk_configs.append(line) 53 mk_configs = " ".join(mk_configs) 54 if "ext4" in mk_configs: 55 fs_type = "ext4" 56 mkfs_tools = "mkextimage.py" 57 elif "f2fs" in mk_configs: 58 mkfs_tools = "mkf2fsimage.py" 59 fs_type = "f2fs" 60 elif "cpio" in mk_configs: 61 mkfs_tools = "mkcpioimage.py" 62 fs_type = "cpio" 63 else: 64 print("not support filesystem type!!") 65 sys.exit(1) 66 return mkfs_tools, mk_configs, fs_type 67 68 69def mk_images(args): 70 if len(args) != 4: 71 print("mk_images need 4 args!!!") 72 sys.exit(1) 73 74 src_dir = args[0] 75 config_file = args[1] 76 device = args[2] 77 is_sparse = args[3] 78 79 if "system.img" in device: 80 src_dir = build_rootdir(src_dir) 81 mkfs_tools, mk_configs, _ = load_config(config_file) 82 if "ramdisk.img" in device: 83 mk_configs = \ 84 " ".join([src_dir, device, "%s/../ramdisk_resource_config.ini" % src_dir]) 85 else: 86 mk_configs = " ".join([src_dir, device, mk_configs]) 87 res = run_cmd(" ".join([mkfs_tools, mk_configs])) 88 if res[1]: 89 print(" ".join(["pid ", str(res[0]), " ret ", str(res[1]), "\n", 90 res[2].decode(), res[3].decode()])) 91 print("MkImages failed errno: %s" % str(res[1])) 92 sys.exit(2) 93 # we dont support sparse in mktools. 94 if "sparse" in is_sparse: 95 tmp_device = "%s.tmp" % device 96 run_cmd(" ".join(["img2simg ", device, " ", tmp_device])) 97 os.rename(tmp_device, device) 98 99 100if __name__ == '__main__': 101 mk_images(sys.argv[1:]) 102