将项分配给字节对象?
哎呀,代码不工作真是糟糕的代码啊!
in RemoveRETNs
toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment
我该怎么修复这个问题呢?
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)
我哪里做错了?我能做些什么来解决这个问题?有没有代码示例?
2 个回答
8
在Python中,字节串(bytestrings)和字符串(strings)是不可变的对象。这意味着一旦你创建了它们,就不能直接修改。如果你想改变它们,你需要创建一个新的字符串,其中包含一些旧字符串的内容。比如说,如果你有一个基本的字符串,可以用这样的方式来创建新字符串:newString = oldString[:offset] + newChar + oldString[offset+1:]
。
不过,你可以先把字节串转换成一个字节列表,或者一个字节数组(bytearray),然后对它进行操作,最后再把字节数组或列表转换回一个静态字符串。这样做可以避免每次替换时都创建一个新的字符串。
50
把 GetFileContents
函数里的 return
语句改成
return bytearray(fileContents)
这样其他部分就应该能正常工作了。你需要用 bytearray
而不是 bytes
,因为 bytearray
是可以修改的(可以读写),而 bytes
(你现在用的这个)是不可修改的(只能读)。