Finding syscalls generated by PHP functions with Dtrace

I wanted to check a list of syscalls that are generated by PHP for a bunch of functions. Dtrace saved the day again, in 10 minutes I had all I needed. Here is a PHP script you can use for testing (syscalls.php) :

<?php
file_exists( __FILE__ );
file_get_contents( __FILE__ );
chdir( __DIR__ );
dir( __DIR__ );
getcwd();
opendir( __DIR__ );
scandir( __DIR__ );
new DirectoryIterator( __DIR__ );
stat( __DIR__ );
is_readable( __DIR__ );
is_writable( __DIR__ );
file_put_contents('/tmp/foo.txt', 'foo');
?>

And the small Dtrace (syscalls.d) script I used:

#!/usr/sbin/dtrace -s
#pragma D option quiet

php*:::function-entry
/pid == $target && arg0/
{
 printf( "%s%s%s\n", copyinstr(arg3), copyinstr(arg4), copyinstr(arg0) );
 self->follow++;
}

syscall:::entry
/self->follow > 0/
{
 printf("  ->%s\n", probefunc);
}

php*:::function-return
/pid == $target && arg0/
{
 self->follow -= self->follow == 0 ? 0 : 1;
 printf("\n");
}

You can test the script by running :

sudo dtrace -s syscalls.d -c "php syscalls.php"

And you should get a list like this (at least on Mac Os X)

file_exists
 ->access

file_get_contents
 ->lstat
 ->lstat
 ->open
 ->fstat
 ->lseek
 ->fstat
 ->read
 ->read
 ->read
 ->close

chdir
 ->chdir

dir
 ->open_nocancel
 ->fcntl_nocancel
 ->__sysctl
 ->fstatfs

getcwd
 ->open_nocancel
 ->fstat64
 ->fcntl_nocancel
 ->close_nocancel
 ->stat64

opendir
 ->open_nocancel
 ->fcntl_nocancel
 ->fstatfs
 ->close_nocancel

scandir
 ->open_nocancel
 ->fcntl_nocancel
 ->fstatfs
 ->getdirentries
 ->getdirentries
 ->close_nocancel

DirectoryIterator::__construct
 ->open_nocancel
 ->fcntl_nocancel
 ->fstatfs
 ->getdirentries

 ->close_nocancel
stat
 ->stat

is_readable
 ->access

is_writable
 ->access

file_put_contents
 ->lstat
 ->lstat
 ->readlink
 ->lstat
 ->lstat
 ->open
 ->fstat
 ->lseek
 ->write
 ->close

If I have time I'll post more Dtrace scripts useful for analysing what PHP does.

Edit : I fixed a small bug for the DirectoryOperator class.

Comments !

blogroll

social