Skip to content

Instantly share code, notes, and snippets.

@ambrice
Created August 29, 2014 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ambrice/c36b46237fcc979d80c9 to your computer and use it in GitHub Desktop.
Save ambrice/c36b46237fcc979d80c9 to your computer and use it in GitHub Desktop.
Script to undo the VirtualBox broken .vhd file resize
#!/usr/bin/python
import struct
import sys
def get_chksum(data):
chksum = 0
for c in data:
chksum += ord(c)
return (~chksum & 0xffffffff)
def resize_footer(footer):
fields = list(struct.unpack('>8s2LQL4sLL2Q3L16sB427s', footer))
fields[9] = fields[8] # current_size = original_size
fields[12] = 0 # chksum = 0
new_footer = struct.pack('>8s2LQL4sLL2Q3L16sB427s', *fields)
chksum = struct.pack('>L', get_chksum(new_footer))
new_footer = new_footer[:64] + chksum + new_footer[68:]
return new_footer, fields[8]
def resize_header(header, new_table_entries):
fields = list(struct.unpack('>8s2Q4L16s2L512s24s24s24s24s24s24s24s24s256s', header))
fields[4] = new_table_entries
fields[6] = 0
new_header = struct.pack('>8s2Q4L16s2L512s24s24s24s24s24s24s24s24s256s', *fields)
chksum = struct.pack('>L', get_chksum(new_header))
new_header = new_header[:36] + chksum + new_header[40:]
return new_header
with open(sys.argv[1], 'rb+') as f:
footer = f.read(512)
header = f.read(1024)
new_footer, original_size = resize_footer(footer)
original_table_entries = original_size / 0x200000
new_header = resize_header(header, original_table_entries)
f.seek(0)
f.write(new_footer)
f.write(new_header)
f.seek(512, 2)
f.write(new_footer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment