def write(self, fileobj): fileobj = fileview(fileobj, self.offset, self.size) fileobj.seek(0) # serialize all the mach-o commands self.synchronize_size() self.header.to_fileobj(fileobj) for lc, cmd, data in self.commands: lc.to_fileobj(fileobj) cmd.to_fileobj(fileobj) if isinstance(data, unicode): fileobj.write(data.encode(sys.getfilesystemencoding())) elif isinstance(data, (bytes, str)): fileobj.write(data) else: # segments.. for obj in data: obj.to_fileobj(fileobj) # zero out the unused space, doubt this is strictly necessary # and is generally probably already the case fileobj.write(B('\x00') * (self.low_offset - fileobj.tell()))
def rewriteDataForCommand(self, idx, data): lc, cmd, old_data = self.commands[idx] hdrsize = sizeof(lc.__class__) + sizeof(cmd.__class__) align = struct.calcsize('L') data = data + (B('\x00') * (align - (len(data) % align))) newsize = hdrsize + len(data) self.commands[idx] = (lc, cmd, data) self.changedHeaderSizeBy(newsize - lc.cmdsize) lc.cmdsize, cmd.name = newsize, hdrsize return True
def walkRelocatables(self, shouldRelocateCommand=_shouldRelocateCommand): """ for all relocatable commands yield (command_index, command_name, filename) """ for (idx, (lc, cmd, data)) in enumerate(self.commands): if shouldRelocateCommand(lc.cmd): name = _RELOCATABLE_NAMES[lc.cmd] ofs = cmd.name - sizeof(lc.__class__) - sizeof(cmd.__class__) yield idx, name, data[ofs:data.find(B('\x00'), ofs)].decode( sys.getfilesystemencoding())
def readSymbolTable(self, fh): cmd = self.symtab fh.seek(cmd.stroff) strtab = fh.read(cmd.strsize) fh.seek(cmd.symoff) nlists = [] for i in xrange(cmd.nsyms): cmd = nlist.from_fileobj(fh) if cmd.n_un == 0: nlists.append((cmd, '')) else: nlists.append((cmd, strtab[cmd.n_un:strtab.find(B('\x00'), cmd.n_un)])) self.nlists = nlists
def _formatinfo(format): """ Calculate the size and number of items in a struct format. """ size = struct.calcsize(format) return size, len(struct.unpack(format, B('\x00') * size))