Sonntag, 2. Februar 2014

PHP Segmentation fault

This is the worst case for every php developer when hacking some code - your script runs not as expected and you get a simple message saying "Segmentation fault".

Here are the steps you can do, to track down this error.


Some simple tips to start


- Use a debugger like ZendDebugger or XDebug to find the line of code causing the error.

- Disable PHP's internal garbage collector. The garbage collector is known to often cause segmentation faults. If disabling will help you are probably found an internal reference counting bug in the garbage collector
ini_set('zend.enable_gc', 0);
- Look for recursion in your code. PHP throws a segmentation fault if you have a infinite recursion in your code

- If you have apc installed sometimes it helps to empty the cache or disable the cache

Use strace

If php runs on Linux or Mac OS you can use strace/dtruss to hook into the process and see what's happening. Strace can be installed on Debian by running

apt-get install strace

Run phpunit with strace

$ strace phpunit

Attach strace to a already running process

$ sudo strace -s 256 -p <PID>

Run any php script with strace

$ strace php index.php

Attach strace to a running cgi process

$ ps axf | grep php5-cgi # lists all running processes
#If more than one process is found you can use the tool php-strace (see below) to trace all processes at the same time. If only one process is found you can use the following command to trace:
$ sudo strace -s 256 -p <PID>
#For debugging purposes I recommend to limit the cgi processes running to one, so you can be sure to hook into the right process which is serving your browser.
# The number of running cgi processes can be edited by editing the file /etc/php5/fpm/pool.d/www.conf .

Gdb

Also you can try to run the script inside of gdb. On Debian gdb can be installed using the command "apt-get install gdb"

gdb --args php /usr/bin/phpunit
#inside gdb enter:
set env MALLOC_CHECK_=3
#then enter:
r

php-strace

I wrote a tool for easy monitoring running cgi proccesses on a server or a developer box.

php-strace helps to track down segfaults in running php processes. It starts a new strace instance for every running php5-cgi or php-fpm process to monitor whether a segfault happened.


php-strace

To get started, visit my github page. https://github.com/markus-perl/php-strace

Update

php-strace V0.3 available:
https://dl.dropboxusercontent.com/u/32252351/github/php-strace-0.3.tar.gz


9 Kommentare:

  1. Haha, google sent me here because of a segmentation fault in php-fpm when using xdebug, first tip is "use xdebug". I guess its fml then. ;-)

    AntwortenLöschen
  2. Thank you so much for this blog post, I have been searching Google from few days and nothing worked. You saved my days. Thanks a lot!

    AntwortenLöschen
  3. Dieser Kommentar wurde vom Autor entfernt.

    AntwortenLöschen