PHP Internals

Post on 23-Jan-2018

146 views 2 download

transcript

PHP Internals

Nico LoubserDeveloper at …..

“One night only” Curriculum.

Focus on concepts that will allow you to build things.

Lexical analysis

Syntax analysis [PHP7]

Opcode

Extensions

And some interesting facts about PHP

Terminology

1. Zvals are the datastructures holding PHP variable data. Variable points to a

Zval

2. A Reference !== Passing by reference. Reference === `Points`

3. Variables references zvals

4. Heap is the memory where zvals live

PHP Execution

Interpreted, compiled, or both?

These are the typical steps of a multipass compiler

- Lexical analysis

- Syntax analysis

- Some other steps maybe….

- Opcode [Final compilation]

Lexical analysis

Step one. Converts a script into tokens by Zend’s token engine. Really? Yes

really.

Lexical analysis. What does tokenized data look like?

Lexical analysis - can we use it for anything?

Source code highlighting and other tools.

Syntax analysis

PHP 7 introduced AST

More maintainable parser and compiler

Decoupling syntax decisions from technical issues

AST - parse tree for PHP script. [ https://github.com/nikic/PHP-Parser ]

AST - Generated code

AST - Generated code

Opcode

VLD / Bytekit / Parsekit

I used VLD, easiest to get to work.

Vulcan Logic Disassembler

Bytekit doesn’t seem to be supported, Parsekit results same is VLD.

Vulcan Logic Disassembler

ZVALS

How PHP represents data and keeps count of references for instance.

Represented by a C type called a Union.

PHP5

Zvals

The important difference between PHP 5 and PHP 7 : share the same Zval, regardless of by value or

reference.

Only once some kind of modification is performed the array will be separated.

Simulation of the copy-on-write behavior

Time to run some scripts…..

[Script can be found in github]

Extension

The hard way.

The PHP way.

The C++ way.

Extensions

I used the PHP-CPP skeleton framework. http://www.php-cpp.com/

You will need sudo apt-get install php5-dev

In Makefile

Assign your extension name to the NAME parameter, and then create a ini file with the same name.

Put this in the ini file

extension=quintillion.so

Make && make install

Run php -i | grep quintillion

/etc/php5/cli/conf.d/quintillion.ini

Comparison of normal vs extension

Live long and prosper

Internals is very interesting topic.

Knowledge about internals is good for memory, good for speed, data-structures, native implementations to interface with something.

nicoloubser@gmail.com

@Nico_Loubser