2009-12-20 5 views
4

GAHH 코드가 작동하지 않는 것은 실제로 잘못된 코드입니다!Python의 바이트 객체에 대한 항목 할당

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) 
내가 잘못 뭐하는 거지

, 나는 그것을 해결하기 위해 무엇을 할 수 있습니까? 코드 샘플?

답변

13

return bytearray(fileContents) 

GetFileContentsreturn 문을 변경

나머지는 작동합니다. 이전에 읽기/쓰기, 단순히 후자 (현재 사용중인)가 읽기 전용이기 때문에 bytes이 아닌 bytearray을 사용해야합니다.

6

바이트 스트링 (및 문자열은 일반적으로)은 파이썬에서 불변 객체입니다. 일단 생성하면 변경할 수 없습니다. 대신 오래된 콘텐츠가있는 새 콘텐츠를 만들어야합니다. (예를 들어, 기본 문자열이 newString = oldString[:offset] + newChar + oldString[offset+1:] 인 경우)

대신에 바이트 스트링을 바이트 목록으로 변환하거나 바이트 배열을 조작하고 조작 한 다음 바이트리스트 /리스트를 다시 변환 할 수 있습니다 모든 조작이 완료된 후 정적 문자열로 이동합니다. 이렇게하면 각 바꾸기 작업에 대해 새 문자열을 만들지 않아도됩니다.

+1

바이트/바이트 테스트 목록으로 변환 한 다음 파일로 출력하려면 어떻게합니까? –

+0

'[i for i in x]'는 거의 모든 것에 대한 목록을 만들어야합니다. 최선의 방법인지는 확실하지 않지만 한 가지 방법입니다. – Thanatos

+1

'bytearray (stuff)'또는'list (stuff)'를 사용하여'stuff '를 bytearray 나 list로 각각 변환하십시오. – Amber

관련 문제