25

I want to build a PHP extension that can dynamically inspect every opcode generated from a PHP file and do some checking on that.

I came across several websites and found out a couple of functions like zend_set_user_opcode_handler, but I fail to understand how this function can be used to get a complete opcode like ASSIGN !0, 50.

I'm aware of a command like php -d vld.active=1 -d vld.execute=0 -f [filename].php which I can use to generate PHP opcodes, but as far as I know you can only access the opcodes after the PHP program terminates.

What I'd like to get from the extension is an opcode which is obtained one-by-one (dynamically) as the function executes.

Can someone help me with this issue?

Tim Penner
  • 3,551
  • 21
  • 36
ebudi
  • 287
  • 2
  • 3
  • 3
    I expect xdebug does something similar, can you look at the code for that? – halfer Jan 12 '15 at 14:46
  • Generating opcodes is rather difficult since all the stuff for doing so is marked `static` and available only within `zend_compile.c`, so you'd have to duplicate it. – Andrea Feb 03 '15 at 00:54
  • Might have more look constructing an AST instead. – Andrea Feb 03 '15 at 00:54
  • 4
    Not sure I fully understand what you want, but if you want to step through code at the opcode level (and show the opcodes that are executed) then phpdbg supports that. – NikiC Apr 06 '15 at 08:08
  • 1
    Check [this out](http://stackoverflow.com/questions/1795425/how-to-get-opcodes-of-php), it should help – dikokob Jan 28 '16 at 13:55

1 Answers1

1

You could use parsekit which is available through pecl which can be downloaded from the pecl website or installed with:

sudo pecl install parsekit

Get OPcodes from a string of PHP code during runtime:

You could use the parsekit_compile_string

The syntax for this command is:

array parsekit_compile_string ( string $phpcode [, array &$errors [, int $options = PARSEKIT_QUIET ]] )

Parameters:

phpcode

A string containing phpcode. Similar to the argument to eval().

errors

A 2D hash of errors (including fatal errors) encountered during compilation. Returned by reference.

options

One of either PARSEKIT_QUIET or PARSEKIT_SIMPLE. To produce varying degrees of verbosity in the returned output.

Return Values

Returns a complex multi-layer array structure as detailed below.

An example usage of this is:

<?php
  $ops = parsekit_compile_string('
echo "Foo\n";
', $errors, PARSEKIT_QUIET);

  var_dump($ops);
?>

The output is too long to include in this answer but is available on the documentation page


Get OPcodes from a PHP file during runtime:

You could use the parsekit_compile_file

Very similar to the above approach but parses a file instead of a string.

Tim Penner
  • 3,551
  • 21
  • 36