Machine code

From Rosetta Code
Revision as of 12:24, 31 December 2013 by rosettacode>Francogrex (Poke and execute machine code)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Machine code is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

The task requires poking machine code directly into memory and executing it. This is strictly for x86 (32 bit) architectures. The machine code is the opcodes of the following simple program:

mov EAX, [ESP+4]
add EAX, [ESP+8]
ret

which translates into the following opcodes: (139 68 36 4 3 68 36 8 195) and in Hex this would correspond to the following: ("8B" "44" "24" "4" "3" "44" "24" "8" "C3")

Implement the following in your favorite programming language (take the common lisp code as an example if you wish):

  1. Poke the above opcodes into a memory pointer
  2. Excute it with the following arguments: [ESP+4] => unsigned-byte argument of value 7; [ESP+8] => unsigned-byte argument of value 12; The result would be 19.
  3. Free the Pointer

Common Lisp

</lang lisp>

This uses the Clozure common lisp foreign function interface implementation
Allocate a memory pointer and poke the opcode into it

(defparameter ptr (ccl::malloc 9))

(loop for i in '(139 68 36 4 3 68 36 8 195)

  for j from 0 do
  (setf (ccl::%get-unsigned-byte ptr j) i))
Execute with the required arguments and return the result as an unsigned-byte

(ccl::ff-call ptr :UNSIGNED-BYTE 7 :UNSIGNED-BYTE 12 :UNSIGNED-BYTE)

Output = 19
Free the pointer

(ccl::free ptr) </lang>