Hacking hhvm

W
Hacking HHVM
Waqar Alamgir
@wajrcs walamgir@folio3.com
Aug 13, 2015
“What is HHVM?”
HHVM is not a source code transformer
That was HPHPc, it’s dead.
▪ Runs your PHP pages live,
just like PHP
▪ Uses a builtin web server
or FastCGI – Runs anywhere
(on 64-bit x86 linux)
▪ Drop-in replacement for PHP
(mostly)
Webserver
(apache, nginx, etc…)
Database
(mysql, posges,
mongo, redis, etc…)
cart.phphome.phplogin.php
index.php
PHP
A
P
C
HHVM is not a source code transformer
That was HPHPc, it’s dead.
▪ Runs your PHP pages live,
just like PHP
▪ Uses a builtin web server
or FastCGI – Runs anywhere
(on 64-bit x86 linux)
▪ Drop-in replacement for PHP
(mostly)
Webserver
(apache, nginx, etc…)
Database
(mysql, posges,
mongo, redis, etc…)
cart.phphome.phplogin.php
index.php
HHVM
Just Plug and Pray!
Erm, I mean… Play
HHVM supports (most) PHP syntax
Tracking HEAD
▪ Pending: Splat (5.6)
(Variadics work already)
▪ Finally
▪ Generators
▪ Namespaces
And some of its own
▪ Scalar type hint
(and much much more)
▪ Async co-routines
▪ Generics
▪ Collections (smart arrays)
▪ XHP (Integrated XHTML)
▪ User Attributes
HHVM’s Parity Gap
• Only about 60% of PHP’s unit tests pass.
• 20 top framework (and more) do pass.
• So I wouldn’t sweat the small stuff.
HHVM is easy to install
If you’re on Ubuntu
▪ deb http://dl.hhvm.com/ubuntu saucy main
▪ apt-get update
▪ apt-get install hhvm (or hhvm-nightly)
▪ Provides one binary covering cli, fcgi server, and libevent server
▪ Coming very soon to a Debian near you!
Or something Debianish…
HHVM is buildable
On other linux distros (MacOSX in interp mode only)
• http://hhvm.com/repo/wiki
• gcc 4.8 or later (soon to be 4.8 or later)
• Boost 1.49 or later
• Lots of other dependencies….
• git clone git@github.com:facebook/hhvm
cmake .
make –j
• hphp/hhvm/hhvm
xkcd.org/303
Running a server
Built-in HTTP server FastCGI
Server {
Port = 80
Type = libevent
SourceRoot = /var/www
}
Log {
Level = Error
UseLogFile = true
File = /var/log/hhvm-error.log
Access { * {
File = /var/log/hhvm-access.log
Format = %h %l %u %t ”%r” %>s %b
}}
}
VirtualHost {
…}
StaticFile {
…}
Server {
Port = 9000
Type = fastcgi
SourceRoot = /var/www
}
Log {
Level = Error
UseLogFile = true
File = /var/log/hhvm-error.log
Access { * {
File = /var/log/hhvm-access.log
Format = %h %l %u %t ”%r” %>s %b
}}
}
Requires patched libevent
Running a FastCGI server
nginx HHVM
server {
server_name www.example.com;
root /var/www;
index index.php;
location ~ .php$ {
fastcgi_pass unix:/var/run/hhvm.sock
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME
/var/www$fastcgi_script_name;
include fastcgi_param;
}
}
Server {
FileSocket = /var/run/hhvm.sock
Type = fastcgi
SourceRoot = /var/www
}
Log {
Level = Error
UseLogFile = true
File = /var/log/hhvm-error.log
Access { * {
File = /var/log/hhvm-access.log
Format = %h %l %u %t ”%r” %>s %b
}}
}
HPHPC in 2010 - 2011
• Crazy cross compiler.
• Converts php to C++.
HHVM in 2013
• Complete new VM.
• Facebook is running it on Production.
• Great community, over 750 pull requests.
PHP is webscale
HHVM’s JIT is the secret sauce
HHVM – Bytecode interpreter
• PHP5 style bytecode execution
• APC-like caching of bytecodes
• Perf about on par with PHP
Modified?
Invalidate
Cache
Compile to
Bytecode
Run
Bytecode
Y
N
HHVM – Native code JIT
• Bytecodes run a few times “cold”
• Variable type inference
• Hotpath detection
• Transform to native code
Modified?
Invalidate
Cache
Compile to
Bytecode
Have native?
Run Native
Hot?
Run
Bytecode
Compile to
Native
Y
Y
Y
N
N
N
HHVM – Compiling to Native
HHVM – Repo Authoritative Mode
• “Production Mode”
• Improved offline pre-analysis
• Assumes no changes
• Another 10% or so perf gain
PreCompil
e Bytecode
Have native?
Run Native
Hot?
Run
Bytecode
Compile to
Native
Y
Y
N
N
HHVM – Warming Up Server
Your CPU on PHP.
Hacking hhvm
Hacking hhvm
Hacking hhvm
Hacking hhvm
Magento (Daniel Sloof)
https://t.co/UB1aOzJ73c
Magento (Daniel Sloof)
https://t.co/UB1aOzJ73c
Symfony
(Christian Stocker)
Requests per Second
http://bit.ly/1fCRw99
Symfony
(Christian Stocker)
Page load Time
http://bit.ly/1fCRw99
HPHPd – HPHP Debugger
• Interactive shell
• GDB-like debugging
• Standalone or w/ server
• Breakpoints
• Watches
• Macros
Extending HHVM
You *can* do that in PHP
Writing a PHP Extension…
zend_bool array_column_param_helper(zval **param,
const char *name TSRMLS_DC) {
switch (Z_TYPE_PP(param)) {
case IS_DOUBLE: convert_to_long_ex(param);
case IS_LONG: return 1;
case IS_OBJECT: convert_to_string_ex(param);
case IS_STRING: return 1;
default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "The %s key should be either a string or an integer", name);
return 0;
}
}
PHP_FUNCTION(array_column) {
zval **zcolumn = NULL, **zkey = NULL, **data;
HashTable *arr_hash;
HashPosition pointer;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "hZ!|Z!", &arr_hash, &zcolumn, &zkey) == FAILURE) { return; }
if ((zcolumn && !array_column_param_helper(zcolumn, "column" TSRMLS_CC)) ||
(zkey && !array_column_param_helper(zkey, "index" TSRMLS_CC))) {
RETURN_FALSE;
}
array_init(return_value);
for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer);
zend_hash_get_current_data_ex(arr_hash, (void**)&data, &pointer) == SUCCESS;
zend_hash_move_forward_ex(arr_hash, &pointer)) {
zval **zcolval, **zkeyval = NULL;
HashTable *ht;
if (Z_TYPE_PP(data) != IS_ARRAY) { continue; }
ht = Z_ARRVAL_PP(data);
if (!zcolumn) { zcolval = data; }
else if ((Z_TYPE_PP(zcolumn) == IS_STRING) &&
(zend_hash_find(ht, Z_STRVAL_PP(zcolumn), Z_STRLEN_PP(zcolumn) + 1, (void**)&zcolval) == FAILURE)) { continue; }
else if ((Z_TYPE_PP(zcolumn) == IS_LONG) &&
(zend_hash_index_find(ht, Z_LVAL_PP(zcolumn), (void**)&zcolval) == FAILURE)) { continue; }
if (zkey && (Z_TYPE_PP(zkey) == IS_STRING)) { zend_hash_find(ht, Z_STRVAL_PP(zkey), Z_STRLEN_PP(zkey) + 1, (void**)&zkeyval); }
else if (zkey && (Z_TYPE_PP(zkey) == IS_LONG)) { zend_hash_index_find(ht, Z_LVAL_PP(zkey), (void**)&zkeyval); }
Z_ADDREF_PP(zcolval);
if (zkeyval && Z_TYPE_PP(zkeyval) == IS_STRING) { add_assoc_zval(return_value, Z_STRVAL_PP(zkeyval), *zcolval); }
else if (zkeyval && Z_TYPE_PP(zkeyval) == IS_LONG) { add_index_zval(return_value, Z_LVAL_PP(zkeyval), *zcolval); }
else if (zkeyval && Z_TYPE_PP(zkeyval) == IS_OBJECT) {
SEPARATE_ZVAL(zkeyval);
convert_to_string(*zkeyval);
add_assoc_zval(return_value, Z_STRVAL_PP(zkeyval), *zcolval);
} else {
add_next_index_zval(return_value, *zcolval);
}
}
}
The same function in HHVM
<?php
function array_column(array $arr, $col, $key = null) {
$ret = [];
foreach($arr as $key => $val) {
if (!is_array($val)) continue;
$cval = ($col === null) ? $val : $val[$col];
if ($key === null || !isset($val[$key])) {
$ret[] = $cval;
} else {
$ret[$val[$key]] = $cval;
}
}
return $ret;
}
Crossing the PHP->C++ barrier
Array HHVM_FUNCTION(array_column, CArrRef arr, CVarRef col, CVarRef key) {
Array ret;
for (auto &pair : arr) {
Variant key = pair.first, val = pair.second;
if (val.isArray()) continue;
Array aval = val.toArray();
Variant cval = col.isNull() ? aval : aval[col];
if (key.isNull() || !aval.exists(key)) {
ret.append(cval);
} else {
ret[aval[key]] = cval;
}
}
return ret;
}
Questions
Resources
• http://hhvm.com/repo
• http://hhvm.com/blog
• http://hhvm.com/twitter
• http://docs.hhvm.com
• hphp/doc in git repository for Options and Technical… Stuff
• Freenode / #hhvm
• http://hhvm.com/fb/page
• http://hhvm.com/fb/general
• @HipHopVM
• @HackLang
1 of 33

Recommended

Who killed object oriented design? by
Who killed object oriented design?Who killed object oriented design?
Who killed object oriented design?Amir Barylko
6.7K views104 slides
Laravel 5.2 Gates, AuthServiceProvider and Policies by
Laravel 5.2 Gates, AuthServiceProvider and PoliciesLaravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesAlison Gianotto
3.5K views25 slides
Advanced Interfaces and Repositories in Laravel by
Advanced Interfaces and Repositories in LaravelAdvanced Interfaces and Repositories in Laravel
Advanced Interfaces and Repositories in LaravelJonathan Behr
9.4K views29 slides
Rich domain model with symfony 2.5 and doctrine 2.5 by
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
12K views90 slides
Building Modern and Secure PHP Applications – Codementor Office Hours with Be... by
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Arc & Codementor
11.2K views85 slides
Dependency Injection Smells by
Dependency Injection SmellsDependency Injection Smells
Dependency Injection SmellsMatthias Noback
9.2K views44 slides

More Related Content

What's hot

Forget about index.php and build you applications around HTTP! by
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!Kacper Gunia
5.7K views128 slides
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani by
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswanivvaswani
39.9K views62 slides
Redis for your boss by
Redis for your bossRedis for your boss
Redis for your bossElena Kolevska
748 views29 slides
Symfony2 revealed by
Symfony2 revealedSymfony2 revealed
Symfony2 revealedFabien Potencier
42.5K views135 slides
Redis for your boss 2.0 by
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0Elena Kolevska
4.6K views66 slides
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden... by
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Ville Mattila
7.8K views19 slides

What's hot(20)

Forget about index.php and build you applications around HTTP! by Kacper Gunia
Forget about index.php and build you applications around HTTP!Forget about index.php and build you applications around HTTP!
Forget about index.php and build you applications around HTTP!
Kacper Gunia5.7K views
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani by vvaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani39.9K views
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden... by Ville Mattila
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Running a Scalable And Reliable Symfony2 Application in Cloud (Symfony Sweden...
Ville Mattila7.8K views
Symfony2, creare bundle e valore per il cliente by Leonardo Proietti
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti1.3K views
Bootstrat REST APIs with Laravel 5 by Elena Kolevska
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska3.9K views
Crafting beautiful software by Jorn Oomen
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
Jorn Oomen2K views
Symfony & Javascript. Combining the best of two worlds by Ignacio Martín
Symfony & Javascript. Combining the best of two worldsSymfony & Javascript. Combining the best of two worlds
Symfony & Javascript. Combining the best of two worlds
Ignacio Martín19.3K views
ZendCon2010 The Doctrine Project by Jonathan Wage
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
Jonathan Wage1.8K views
The Zen of Lithium by Nate Abele
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele2.6K views
Phpne august-2012-symfony-components-friends by Michael Peacock
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock2.8K views
Guard Authentication: Powerful, Beautiful Security by Ryan Weaver
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
Ryan Weaver9.4K views
Inside Bokete: Web Application with Mojolicious and others by Yusuke Wada
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
Yusuke Wada8.2K views
Doctrine For Beginners by Jonathan Wage
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage1.5K views

Viewers also liked

Ley 1014 de 2006 by
Ley 1014 de 2006Ley 1014 de 2006
Ley 1014 de 2006Manuel Bedoya D
1.4K views11 slides
Concepciones de los directivos docentes frente a la ley de emprendimiento (le... by
Concepciones de los directivos docentes frente a la ley de emprendimiento (le...Concepciones de los directivos docentes frente a la ley de emprendimiento (le...
Concepciones de los directivos docentes frente a la ley de emprendimiento (le...gerenciaproy
3.6K views119 slides
Ley 1014 de 2006 by
Ley 1014 de 2006 Ley 1014 de 2006
Ley 1014 de 2006 Firicundinas
560 views3 slides
Mapa conceptual de la ley 1014 del 2006 by
Mapa conceptual de la ley 1014 del 2006Mapa conceptual de la ley 1014 del 2006
Mapa conceptual de la ley 1014 del 2006karen johanitha de castro
4.2K views7 slides
Ley 1014 monica by
Ley 1014 monicaLey 1014 monica
Ley 1014 monicamonica cardenas
1.3K views10 slides
Ley 1014 by
Ley 1014Ley 1014
Ley 1014Juan Camilo Orozco
6K views4 slides

Viewers also liked(7)

Similar to Hacking hhvm

Hacking with hhvm by
Hacking with hhvmHacking with hhvm
Hacking with hhvmElizabeth Smith
2.7K views40 slides
Diving into HHVM Extensions (php[tek] 2016) by
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)James Titcumb
613 views79 slides
Diving into HHVM Extensions (PHPNW Conference 2015) by
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)James Titcumb
1K views78 slides
Php basic for vit university by
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
946 views29 slides
Diving into HHVM Extensions (Brno PHP Conference 2015) by
Diving into HHVM Extensions (Brno PHP Conference 2015)Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)James Titcumb
680 views78 slides
Frontend Servers and NGINX: What, Where and How by
Frontend Servers and NGINX: What, Where and HowFrontend Servers and NGINX: What, Where and How
Frontend Servers and NGINX: What, Where and HowEcommerce Solution Provider SysIQ
3.8K views20 slides

Similar to Hacking hhvm(20)

Diving into HHVM Extensions (php[tek] 2016) by James Titcumb
Diving into HHVM Extensions (php[tek] 2016)Diving into HHVM Extensions (php[tek] 2016)
Diving into HHVM Extensions (php[tek] 2016)
James Titcumb613 views
Diving into HHVM Extensions (PHPNW Conference 2015) by James Titcumb
Diving into HHVM Extensions (PHPNW Conference 2015)Diving into HHVM Extensions (PHPNW Conference 2015)
Diving into HHVM Extensions (PHPNW Conference 2015)
James Titcumb1K views
Diving into HHVM Extensions (Brno PHP Conference 2015) by James Titcumb
Diving into HHVM Extensions (Brno PHP Conference 2015)Diving into HHVM Extensions (Brno PHP Conference 2015)
Diving into HHVM Extensions (Brno PHP Conference 2015)
James Titcumb680 views
Serverless Ballerina by Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
Ballerina98 views
Intro to Asynchronous Javascript by Garrett Welson
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
Garrett Welson602 views
deepjs - tools for better programming by nomocas
deepjs - tools for better programmingdeepjs - tools for better programming
deepjs - tools for better programming
nomocas552 views
Spring data iii by 명철 강
Spring data iiiSpring data iii
Spring data iii
명철 강1.3K views
Using and scaling Rack and Rack-based middleware by Alona Mekhovova
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
Alona Mekhovova1.1K views

Recently uploaded

Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Lisi Hocke
35 views124 slides
Airline Booking Software by
Airline Booking SoftwareAirline Booking Software
Airline Booking SoftwareSharmiMehta
6 views26 slides
HarshithAkkapelli_Presentation.pdf by
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
11 views16 slides
WebAssembly by
WebAssemblyWebAssembly
WebAssemblyJens Siebert
51 views18 slides
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...sparkfabrik
7 views46 slides
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsRa'Fat Al-Msie'deen
8 views49 slides

Recently uploaded(20)

Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta6 views
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik7 views
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok6 views
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs by Deltares
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
Deltares10 views
Ports-and-Adapters Architecture for Embedded HMI by Burkhard Stubert
Ports-and-Adapters Architecture for Embedded HMIPorts-and-Adapters Architecture for Embedded HMI
Ports-and-Adapters Architecture for Embedded HMI
Burkhard Stubert21 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j8 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana10 views
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi212 views
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller41 views
Dapr Unleashed: Accelerating Microservice Development by Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski10 views

Hacking hhvm

  • 1. Hacking HHVM Waqar Alamgir @wajrcs walamgir@folio3.com Aug 13, 2015
  • 3. HHVM is not a source code transformer That was HPHPc, it’s dead. ▪ Runs your PHP pages live, just like PHP ▪ Uses a builtin web server or FastCGI – Runs anywhere (on 64-bit x86 linux) ▪ Drop-in replacement for PHP (mostly) Webserver (apache, nginx, etc…) Database (mysql, posges, mongo, redis, etc…) cart.phphome.phplogin.php index.php PHP A P C
  • 4. HHVM is not a source code transformer That was HPHPc, it’s dead. ▪ Runs your PHP pages live, just like PHP ▪ Uses a builtin web server or FastCGI – Runs anywhere (on 64-bit x86 linux) ▪ Drop-in replacement for PHP (mostly) Webserver (apache, nginx, etc…) Database (mysql, posges, mongo, redis, etc…) cart.phphome.phplogin.php index.php HHVM Just Plug and Pray! Erm, I mean… Play
  • 5. HHVM supports (most) PHP syntax Tracking HEAD ▪ Pending: Splat (5.6) (Variadics work already) ▪ Finally ▪ Generators ▪ Namespaces And some of its own ▪ Scalar type hint (and much much more) ▪ Async co-routines ▪ Generics ▪ Collections (smart arrays) ▪ XHP (Integrated XHTML) ▪ User Attributes
  • 6. HHVM’s Parity Gap • Only about 60% of PHP’s unit tests pass. • 20 top framework (and more) do pass. • So I wouldn’t sweat the small stuff.
  • 7. HHVM is easy to install If you’re on Ubuntu ▪ deb http://dl.hhvm.com/ubuntu saucy main ▪ apt-get update ▪ apt-get install hhvm (or hhvm-nightly) ▪ Provides one binary covering cli, fcgi server, and libevent server ▪ Coming very soon to a Debian near you! Or something Debianish…
  • 8. HHVM is buildable On other linux distros (MacOSX in interp mode only) • http://hhvm.com/repo/wiki • gcc 4.8 or later (soon to be 4.8 or later) • Boost 1.49 or later • Lots of other dependencies…. • git clone git@github.com:facebook/hhvm cmake . make –j • hphp/hhvm/hhvm xkcd.org/303
  • 9. Running a server Built-in HTTP server FastCGI Server { Port = 80 Type = libevent SourceRoot = /var/www } Log { Level = Error UseLogFile = true File = /var/log/hhvm-error.log Access { * { File = /var/log/hhvm-access.log Format = %h %l %u %t ”%r” %>s %b }} } VirtualHost { …} StaticFile { …} Server { Port = 9000 Type = fastcgi SourceRoot = /var/www } Log { Level = Error UseLogFile = true File = /var/log/hhvm-error.log Access { * { File = /var/log/hhvm-access.log Format = %h %l %u %t ”%r” %>s %b }} } Requires patched libevent
  • 10. Running a FastCGI server nginx HHVM server { server_name www.example.com; root /var/www; index index.php; location ~ .php$ { fastcgi_pass unix:/var/run/hhvm.sock fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name; include fastcgi_param; } } Server { FileSocket = /var/run/hhvm.sock Type = fastcgi SourceRoot = /var/www } Log { Level = Error UseLogFile = true File = /var/log/hhvm-error.log Access { * { File = /var/log/hhvm-access.log Format = %h %l %u %t ”%r” %>s %b }} }
  • 11. HPHPC in 2010 - 2011 • Crazy cross compiler. • Converts php to C++. HHVM in 2013 • Complete new VM. • Facebook is running it on Production. • Great community, over 750 pull requests.
  • 12. PHP is webscale HHVM’s JIT is the secret sauce
  • 13. HHVM – Bytecode interpreter • PHP5 style bytecode execution • APC-like caching of bytecodes • Perf about on par with PHP Modified? Invalidate Cache Compile to Bytecode Run Bytecode Y N
  • 14. HHVM – Native code JIT • Bytecodes run a few times “cold” • Variable type inference • Hotpath detection • Transform to native code Modified? Invalidate Cache Compile to Bytecode Have native? Run Native Hot? Run Bytecode Compile to Native Y Y Y N N N
  • 15. HHVM – Compiling to Native
  • 16. HHVM – Repo Authoritative Mode • “Production Mode” • Improved offline pre-analysis • Assumes no changes • Another 10% or so perf gain PreCompil e Bytecode Have native? Run Native Hot? Run Bytecode Compile to Native Y Y N N
  • 17. HHVM – Warming Up Server
  • 18. Your CPU on PHP.
  • 25. Symfony (Christian Stocker) Requests per Second http://bit.ly/1fCRw99
  • 26. Symfony (Christian Stocker) Page load Time http://bit.ly/1fCRw99
  • 27. HPHPd – HPHP Debugger • Interactive shell • GDB-like debugging • Standalone or w/ server • Breakpoints • Watches • Macros
  • 28. Extending HHVM You *can* do that in PHP
  • 29. Writing a PHP Extension… zend_bool array_column_param_helper(zval **param, const char *name TSRMLS_DC) { switch (Z_TYPE_PP(param)) { case IS_DOUBLE: convert_to_long_ex(param); case IS_LONG: return 1; case IS_OBJECT: convert_to_string_ex(param); case IS_STRING: return 1; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "The %s key should be either a string or an integer", name); return 0; } } PHP_FUNCTION(array_column) { zval **zcolumn = NULL, **zkey = NULL, **data; HashTable *arr_hash; HashPosition pointer; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "hZ!|Z!", &arr_hash, &zcolumn, &zkey) == FAILURE) { return; } if ((zcolumn && !array_column_param_helper(zcolumn, "column" TSRMLS_CC)) || (zkey && !array_column_param_helper(zkey, "index" TSRMLS_CC))) { RETURN_FALSE; } array_init(return_value); for (zend_hash_internal_pointer_reset_ex(arr_hash, &pointer); zend_hash_get_current_data_ex(arr_hash, (void**)&data, &pointer) == SUCCESS; zend_hash_move_forward_ex(arr_hash, &pointer)) { zval **zcolval, **zkeyval = NULL; HashTable *ht; if (Z_TYPE_PP(data) != IS_ARRAY) { continue; } ht = Z_ARRVAL_PP(data); if (!zcolumn) { zcolval = data; } else if ((Z_TYPE_PP(zcolumn) == IS_STRING) && (zend_hash_find(ht, Z_STRVAL_PP(zcolumn), Z_STRLEN_PP(zcolumn) + 1, (void**)&zcolval) == FAILURE)) { continue; } else if ((Z_TYPE_PP(zcolumn) == IS_LONG) && (zend_hash_index_find(ht, Z_LVAL_PP(zcolumn), (void**)&zcolval) == FAILURE)) { continue; } if (zkey && (Z_TYPE_PP(zkey) == IS_STRING)) { zend_hash_find(ht, Z_STRVAL_PP(zkey), Z_STRLEN_PP(zkey) + 1, (void**)&zkeyval); } else if (zkey && (Z_TYPE_PP(zkey) == IS_LONG)) { zend_hash_index_find(ht, Z_LVAL_PP(zkey), (void**)&zkeyval); } Z_ADDREF_PP(zcolval); if (zkeyval && Z_TYPE_PP(zkeyval) == IS_STRING) { add_assoc_zval(return_value, Z_STRVAL_PP(zkeyval), *zcolval); } else if (zkeyval && Z_TYPE_PP(zkeyval) == IS_LONG) { add_index_zval(return_value, Z_LVAL_PP(zkeyval), *zcolval); } else if (zkeyval && Z_TYPE_PP(zkeyval) == IS_OBJECT) { SEPARATE_ZVAL(zkeyval); convert_to_string(*zkeyval); add_assoc_zval(return_value, Z_STRVAL_PP(zkeyval), *zcolval); } else { add_next_index_zval(return_value, *zcolval); } } }
  • 30. The same function in HHVM <?php function array_column(array $arr, $col, $key = null) { $ret = []; foreach($arr as $key => $val) { if (!is_array($val)) continue; $cval = ($col === null) ? $val : $val[$col]; if ($key === null || !isset($val[$key])) { $ret[] = $cval; } else { $ret[$val[$key]] = $cval; } } return $ret; }
  • 31. Crossing the PHP->C++ barrier Array HHVM_FUNCTION(array_column, CArrRef arr, CVarRef col, CVarRef key) { Array ret; for (auto &pair : arr) { Variant key = pair.first, val = pair.second; if (val.isArray()) continue; Array aval = val.toArray(); Variant cval = col.isNull() ? aval : aval[col]; if (key.isNull() || !aval.exists(key)) { ret.append(cval); } else { ret[aval[key]] = cval; } } return ret; }
  • 33. Resources • http://hhvm.com/repo • http://hhvm.com/blog • http://hhvm.com/twitter • http://docs.hhvm.com • hphp/doc in git repository for Options and Technical… Stuff • Freenode / #hhvm • http://hhvm.com/fb/page • http://hhvm.com/fb/general • @HipHopVM • @HackLang

Editor's Notes

  1. Facebook started to work on HipHop for PHP in 2008. Their goal was to speed up the PHP execution speed and the first version of the project was composed of the tandem HPHPc/HPHPi. HPHPc is a PHP to C++ transpiler which was used to deploy the code to the production servers while HPHPi was an interpreter used during development and debug stages. HPHPc did a good job on improving performance but it was not without issues: maintaining both HPHPc and HPHPi in sync proved to be cumbersome plus some differences still existed between the transpiled code vs the interpreted one. That's why back in 2010 Facebook decided to go for another approach and created HHVM – a new virtual machine designed to replace the Zend Engine used by PHP. By the end of 2012 HHVM achieved performance parity with the former HPHPc and soon surpassed it.
  2. Facebook started to work on HipHop for PHP in 2008. Their goal was to speed up the PHP execution speed and the first version of the project was composed of the tandem HPHPc/HPHPi. HPHPc is a PHP to C++ transpiler which was used to deploy the code to the production servers while HPHPi was an interpreter used during development and debug stages. HPHPc did a good job on improving performance but it was not without issues: maintaining both HPHPc and HPHPi in sync proved to be cumbersome plus some differences still existed between the transpiled code vs the interpreted one. That's why back in 2010 Facebook decided to go for another approach and created HHVM – a new virtual machine designed to replace the Zend Engine used by PHP. By the end of 2012 HHVM achieved performance parity with the former HPHPc and soon surpassed it.
  3. Rather than directly interpret or compile PHP code directly to C++, HHVM compiles Hack and PHP into an intermediate bytecode. This bytecode is then translated into x64 machine code dynamically at runtime by a just-in-time (JIT) compiler. This compilation process allows for all sorts of optimizations that cannot be made in a statically compiled binary, thus enabling higher performance of your Hack and PHP programs.
  4. Okay to mention that we’re about to move to github.com/hhvm/hhvm
  5. This slide isn’t meant to be readable. It just illustrates how onerous writing an extension function for PHP can be.