Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
[Python 3]Error con os.write()
#1
He encontrado en Internet un interesante código, el cual permite ejecutar código NASM en Python.
Desafortunadamente, esta escrito en Python 2.7. (por dios dejen de usar Python 2)
He tratado portearlo, pero llegue a un problema:
TypeError: a bytes-like object is required, not 'str'
El error está en la función os.write()
Ya he tratado con .encoding, pero aún no funciona.
Sin más, acá les dejo el código:

Código:
[code]
#!/usr/bin/env python

import subprocess, os, tempfile
from ctypes import *

PAGE_SIZE = 4096    

class AssemblerFunction(object):
 
 def __init__(self, code, ret_type, *arg_types):
   # Run Nasm
   fd, source = tempfile.mkstemp(".S", "assembly", os.getcwd())
   os.write(fd, code) #<-- aqui el error
   os.close(fd)
   target = os.path.splitext(source)[0]
   subprocess.check_call(["nasm",source])
   os.unlink(source)
   binary = file(target,"rb").read()
   os.unlink(target)
   bin_len = len(binary)

   # align our code on page boundary.
   self.code_buffer = create_string_buffer(PAGE_SIZE*2+bin_len)
   addr = (addressof(self.code_buffer) + PAGE_SIZE) & (~(PAGE_SIZE-1))
   memmove(addr, binary, bin_len)    
 
   # Change memory protection
   self.mprotect = cdll.LoadLibrary("libc.so.6").mprotect
   mp_ret = self.mprotect(addr, bin_len, 4)   # execute only.
   if mp_ret: raise OSError("Unable to change memory protection")
   
   self.func = CFUNCTYPE(ret_type, *arg_types)(addr)
   self.addr = addr
   self.bin_len = bin_len
   
 def __call__(self, *args):
   return self.func(*args)
   
 def __del__(self):
   # Revert memory protection
   if hasattr(self,"mprotect"):
     self.mprotect(self.addr, self.bin_len, 3)  


if __name__ == "__main__":
 add_func = """ BITS 64
            mov rax, rdi    ; Move the first parameter
            add rax, rsi    ; add the second parameter
            ret         ; rax will be returned
            """
            
 Add = AssemblerFunction(add_func, c_int, c_int, c_int)
 print(Add(1, 2))
 
[/code]

Por cierto, acá les dejo donde saque el código: http://code.activestate.com/recipes/5790...irectly-f/
Saludos
Responder
#2
Hola, gracias por el aporte. Aunque el código parece bastante viejo por cuanto usa funciones harto discontinuadas como os.write() y la clase file.

Para solucionar el error el código debería ser:

Código:
add_func = b""" BITS 64
            mov rax, rdi    ; Move the first parameter
            add rax, rsi    ; add the second parameter
            ret         ; rax will be returned
            """

(Nótese la "b" al inicio de la cadena).
¡No te pierdas nuestro curso oficial en Udemy para aprender Python, bases de datos SQL, orientación a objetos, tkinter y mucho más!

También ofrecemos consultoría profesional de desarrollo en Python para personas y empresas.
Responder


Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)