1#!/usr/bin/env python 2# 3# Copyright (C) 2021 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"""replace_bytes is a command line tool to replace bytes in a file. 17 18Typical usage: replace_bytes target_file old_file new_file 19 20 replace bytes of old_file with bytes of new_file in target_file. old_file and new_file should be 21 the same size. 22 23""" 24import argparse 25import sys 26 27 28def ParseArgs(argv): 29 parser = argparse.ArgumentParser(description='Replace bytes') 30 parser.add_argument( 31 'target_file', 32 help='path to the target file.') 33 parser.add_argument( 34 'old_file', 35 help='path to the file containing old bytes') 36 parser.add_argument( 37 'new_file', 38 help='path to the file containing new bytes') 39 return parser.parse_args(argv) 40 41 42def ReplaceBytes(target_file, old_file, new_file): 43 # read old bytes 44 with open(old_file, 'rb') as f: 45 old_bytes = f.read() 46 47 # read new bytes 48 with open(new_file, 'rb') as f: 49 new_bytes = f.read() 50 51 assert len(old_bytes) == len(new_bytes), 'Pubkeys should be the same size. (%d != %d)' % ( 52 len(old_bytes), len(new_bytes)) 53 54 # replace bytes in target_file 55 with open(target_file, 'r+b') as f: 56 pos = f.read().find(old_bytes) 57 assert pos != -1, 'Pubkey not found' 58 f.seek(pos) 59 f.write(new_bytes) 60 61 62def main(argv): 63 try: 64 args = ParseArgs(argv) 65 ReplaceBytes(args.target_file, args.old_file, args.new_file) 66 except Exception as e: 67 print(e) 68 sys.exit(1) 69 70 71if __name__ == '__main__': 72 main(sys.argv[1:]) 73