strip-binaries.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python3
  2. import argparse
  3. import os
  4. import sys
  5. from lib.config import set_verbose_mode, is_verbose_mode, verbose_mode_print
  6. from lib.util import execute, get_linux_binaries, get_out_dir
  7. def get_size(path):
  8. size = os.path.getsize(path)
  9. units = ["bytes", "KB", "MB", "GB"]
  10. for unit in units:
  11. if size < 1024:
  12. return f"{size:.2f} {unit}"
  13. size /= 1024
  14. raise ValueError("File size is too large to be processed")
  15. def strip_binaries(directory, target_cpu):
  16. if not os.path.isdir(directory):
  17. verbose_mode_print('Directory ' + directory + ' does not exist.')
  18. return
  19. verbose_mode_print('Stripping binaries in ' + directory)
  20. for binary in get_linux_binaries():
  21. verbose_mode_print('\nStripping ' + binary)
  22. binary_path = os.path.join(directory, binary)
  23. if os.path.isfile(binary_path):
  24. strip_binary(binary_path, target_cpu)
  25. def strip_binary(binary_path, target_cpu):
  26. if target_cpu == 'arm':
  27. strip = 'arm-linux-gnueabihf-strip'
  28. elif target_cpu == 'arm64':
  29. strip = 'aarch64-linux-gnu-strip'
  30. else:
  31. strip = 'strip'
  32. strip_args = [strip,
  33. '--discard-all',
  34. '--strip-debug',
  35. '--preserve-dates',
  36. binary_path]
  37. if (is_verbose_mode()):
  38. strip_args.insert(1, '--verbose')
  39. verbose_mode_print('Binary size before stripping: ' +
  40. str(get_size(binary_path)))
  41. execute(strip_args)
  42. verbose_mode_print('Binary size after stripping: ' +
  43. str(get_size(binary_path)))
  44. def main():
  45. args = parse_args()
  46. set_verbose_mode(args.verbose)
  47. if args.file:
  48. strip_binary(args.file, args.target_cpu)
  49. else:
  50. strip_binaries(args.directory, args.target_cpu)
  51. def parse_args():
  52. parser = argparse.ArgumentParser(description='Strip linux binaries')
  53. parser.add_argument('-d', '--directory',
  54. help='Path to the dir that contains files to strip.',
  55. default=get_out_dir(),
  56. required=False)
  57. parser.add_argument('-f', '--file',
  58. help='Path to a specific file to strip.',
  59. required=False)
  60. parser.add_argument('-v', '--verbose',
  61. default=False,
  62. action='store_true',
  63. help='Prints the output of the subprocesses')
  64. parser.add_argument('--target-cpu',
  65. default='',
  66. required=False,
  67. help='Target cpu of binaries to strip')
  68. return parser.parse_args()
  69. if __name__ == '__main__':
  70. sys.exit(main())