create_partition.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # This file is part of asmc, a bootstrapping OS with minimal seed
  4. # Copyright (C) 2018 Giovanni Mascellani <gio@debian.org>
  5. # https://gitlab.com/giomasce/asmc
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. import sys
  17. import os
  18. import struct
  19. import shutil
  20. def main():
  21. assert 2 <= len(sys.argv) <= 6
  22. mbr_filename = sys.argv[1]
  23. parts_filenames = sys.argv[2:]
  24. mbr_size = os.stat(mbr_filename).st_size
  25. parts_sizes = [os.stat(x).st_size for x in parts_filenames]
  26. assert 0 <= len(parts_sizes) <= 4
  27. with open(mbr_filename, 'rb') as fmbr:
  28. mbr = fmbr.read()
  29. assert len(mbr) == 512
  30. # Check we are not overwriting anything
  31. assert mbr[0x1be:0x1fe] == b'\0' * (0x1fe - 0x1be)
  32. current_lba = 1
  33. parts_data = b''
  34. for size in parts_sizes:
  35. sectors = (size + 511) // 512
  36. parts_data += b'\x00\xff\xff\xff\x01\xff\xff\xff'
  37. parts_data += struct.pack('<II', current_lba, sectors)
  38. current_lba += sectors
  39. for i in range(4 - len(parts_sizes)):
  40. parts_data += b'\x00' * 16
  41. mbr = mbr[:0x1be] + parts_data + mbr[0x1fe:]
  42. assert len(mbr) == 512
  43. # Output MBR with partitions
  44. sys.stdout.buffer.write(mbr)
  45. for i in range(len(parts_sizes)):
  46. with open(parts_filenames[i], 'rb') as fin:
  47. shutil.copyfileobj(fin, sys.stdout.buffer)
  48. size = parts_sizes[i]
  49. if size % 512 != 0:
  50. sys.stdout.buffer.write(b'\0' * (512 - size % 512))
  51. if __name__ == '__main__':
  52. main()