Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PHP Opcodes Dynamically at Runtime

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?

like image 654
ebudi Avatar asked Jan 12 '15 14:01

ebudi


1 Answers

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.

like image 172
Tim Penner Avatar answered Nov 17 '22 23:11

Tim Penner