Assigning an article in a byte object in Python

GAHH, the code doesn't work - this is really bad code!

in RemoveRETNs toOutput [currentLoc - 0x00400000] = b '\ xCC' TypeError: object 'bytes' does not support element assignment

How can I fix this:

inputFile = 'original.exe' outputFile = 'output.txt' patchedFile = 'original_patched.exe' def GetFileContents(filename): f = open(filename, 'rb') fileContents = f.read() f.close() return fileContents def FindAll(fileContents, strToFind): found = [] lastOffset = -1 while True: lastOffset += 1 lastOffset = fileContents.find(b'\xC3\xCC\xCC\xCC\xCC', lastOffset) if lastOffset != -1: found.append(lastOffset) else: break return found def FixOffsets(offsetList): for current in range(0, len(offsetList)): offsetList[current] += 0x00400000 return offsetList def AbsentFromList(toFind, theList): for i in theList: if i == toFind: return True return False # Outputs the original file with all RETNs replaced with INT3s. def RemoveRETNs(locationsOfRETNs, oldFilesContents, newFilesName): target = open(newFilesName, 'wb') toOutput = oldFilesContents for currentLoc in locationsOfRETNs: toOutput[currentLoc - 0x00400000] = b'\xCC' target.write(toOutput) target.close() fileContents = GetFileContents(inputFile) offsets = FixOffsets(FindAll(fileContents, '\xC3\xCC\xCC\xCC\xCC')) RemoveRETNs(offsets, fileContents, patchedFile) 

What am I doing wrong, and what can I do to fix this? Code example?

+4
source share
2 answers

Change the return GetFileContents to

 return bytearray(fileContents) 

and the rest should work. You need to use bytearray , not bytes simply because the first is read / written, the last (which you are using now) is read-only.

+13
source

Bytestrings (and strings in general) are immutable objects in Python. By creating them, you cannot change them. Instead, you need to create a new one that has some of the old content. (For example, with a baseline, newString = oldString[:offset] + newChar + oldString[offset+1:] or the like.)

Instead, you may need to convert bytestring to a list of bytes first or bytearray, manipulate it, and then convert bytearray / list back to a static string after all the manipulations are done. This allows you to create a new line for each replacement operation.

+6
source

All Articles