2. 2
Hello
● Julien PAULI
● Programming in PHP since early 2000s
● PHP Internals hacker and trainer
● PHP 5.5/5.6 Release Manager
● Working at SensioLabs in Paris - Blackfire
● Writing PHP tech articles and books
● http://phpinternalsbook.com
● @julienpauli - http://jpauli.tech - jpauli@php.net
● Like working on OSS such as PHP :-)
6. 6
Coeur : main et ext/standard
● 55K LOC
● str_
● array_
● files and streams
● ...
7. 7
Extensions : ext/xxx
● 530K LOC for ext/
● "Extensions" and "Zend extensions"
● Static or dynamic compilation and linking
● Add features
● Consume resources
● php -m ; php --re
● Mandatory ext :
● core / date / pcre / reflection / SPL / standard / hash
● Other extensions :
● http://pecl.php.net
8. 8
PHP
● A program in itself
● Written in C
● Goal : Define a programming Web language
● High level, interpreted
● Interpreted language
● Less efficient than native-instr compiled language
● but simpler to handle
17. 17
Sementical analysis (parsing)
● "Understands" a set of tokens
● Defines the language syntax
● Parser generator : GNU/Bison (LALR)
● Foreach token or token set
● → Execute a function to generate an AST statement
● → Goto next token
● → Can generate "Parse error" and halt
● Very tied to lexical analyzer
20. 20
Compilation
● Invoked on final AST
● Userland AST: https://github.com/nikic/php-ast
● Creates an OPCodes array
● OPCode = low level VM instruction
● Somehow similar to low level assembly
● Example : ADD (a,b) → c ; CONCAT(c,d) → e ; etc...
● Compilation step is very heavy
● Lots of checks
● address resolutions
● many stacks and memory pools
● Some early optimizations/computations are performed
25. 25
Execution
● Execute OPCodes
● Most complex part of Zend Engine
● VM executor
● zend_vm_execute.h
● Each OPCode
● is run through a handler() function
● "zend_vm_handler"
● runs the instructions in an infinite dipatch
loop
● Branching possibles (loops, catch blocks,
gotos, etc...)
Startup
Shutdown
zend_compile_file()
zend_execute()
28. 28
OPCode Cache
● First time
● Compile
● Cache to SHM
● Execute
● Then, if file did not change
● Load from SHM
● Execute
● Compilation is too heavy
● Prevent it with OPCode cache
32. 42
Zend Memory Manager
● ZendMM : Request bound dynamic memory allocator
● Owns its heap reclaimed using malloc() / mmap()
● Used by PHP, Zend Engine and extensions while
treating a request
● Tunable
● zend_alloc.c/h
33. 44
Memory consumption
● memory_get_usage(): size used by your runtime code
● memory_get_usage(true): size allocated through the OS
● ZendMM caches blocks
● use gc_mem_caches() to reclaim them if needed
● Use your OS to be accurate
php> echo memory_get_usage();
625272
php> echo memory_get_usage(1);
786432
cat /proc/13399/status
Name:php
State: S (sleeping)
VmPeak: 154440 kB
VmSize: 133700 kB
VmRSS: 10304 kB
VmData: 4316 kB
VmStk: 136 kB
VmExe: 9876 kB
VmLib: 13408 kB