Get PHP Opcodes Dynamically at Runtime
Asked Answered
L

1

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?

Liesa answered 12/1, 2015 at 14:29 Comment(5)
I expect xdebug does something similar, can you look at the code for that?Kyanite
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.Skivvy
Might have more look constructing an AST instead.Skivvy
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.Te
Check this out, it should helpMarque
A
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.

Avalanche answered 23/3, 2016 at 17:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.