Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. import memory
  2.  
  3. from memory import Convention
  4. from memory import DataType
  5. from memory import Function
  6.  
  7.  
  8. class AsmFunction(Function):
  9.     def __init__(self, op_codes, convention=Convention.CDECL, args=[], return_type=DataType.VOID):
  10.         if not op_codes:
  11.             raise ValueError('At least one OP code is required.')
  12.  
  13.         self.op_codes = op_codes
  14.  
  15.         # Allocate memory
  16.         super().__init__(
  17.             memory.alloc(len(op_codes), False).address,
  18.             convention,
  19.             args,
  20.             return_type
  21.         )
  22.  
  23.         # Make the buffer executable
  24.         self.unprotect(len(op_codes))
  25.  
  26.         # Write OP codes
  27.         for offset, op_code in enumerate(op_codes):
  28.             self.set_uchar(op_code, offset)
  29.  
  30.  
  31. multiply = AsmFunction(
  32.     [
  33.         0x55,                   # push    ebp
  34.         0x8B, 0xEC,             # mov     ebp, esp
  35.         0x8B, 0x45, 0x08,       # mov     eax, [ebp+8]
  36.         0x0F, 0xAF, 0x45, 0x0C, # imul    eax, [ebp+0Ch]
  37.         0x5D,                   # pop     ebp
  38.         0xC3                    # retn
  39.     ],
  40.     args=[DataType.INT, DataType.INT],
  41.     return_type=DataType.INT
  42. )
  43.  
  44. # Output: 21
  45. print(multiply(7, 3))
  46.  
  47. multiply.dealloc()