Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP float bug: PHP Hangs On Numeric Value

I just read an interesting article about php hanging on certain float numbers, see The Register and Exploring Binary.

I never explicitly use floats, I use number_format() to clean my input and display for example prices.

Also, as far as I am aware, all input from for example forms are strings until I tell them otherwise so I am supposing that this problem does not affect me.

Am I right, or do I need to check for example Wordpress and Squirrelmail installations on my server to see if they cast anything to float? Or better, grep all php files on my servers for float?

like image 548
jeroen Avatar asked Dec 05 '22 00:12

jeroen


2 Answers

Ways to mitigate the problem:

  1. Use a modern CPU. Most modern 64-bit CPUs would be immune (I actually had trouble finding host that allows to reproduce it since they tend to use more modern hardware). Amazon VMs seem to be immune too.
  2. Upgrade your PHP version - 5.3.5 and 5.2.17 once released (probably today) include the fix.
  3. Build with -ffloat-store in CFLAGS (will slow down the code).
  4. Manually apply the patch to your code and rebuild PHP.

Looking for the code that has float probably won't help as zend_strtod is used by the engine in many string->number conversion scenarios.

P.S. this code btw is standard BSD library strtod code, not unique to PHP. So other projects using this code might be affected too.

like image 157
StasM Avatar answered Dec 10 '22 11:12

StasM


From hackernews:

This problem occurs due to IA-32's 80-bit floating point arithmetic. The simple fix: add a "-ffloat-store" flag to your CFLAGS.

The problematic function, zend_strtod, seems to parse the mantissa (2.225...011 part) and the exponent (-308 part) separately, c> alculate the approximation of m*10^e and successively improve that approximation until the error becomes less than 0.5ulp. The problem is that this particular number causes the infinite loop (i.e. the iteration does not improve the error at all) in 80-bit FP, but does not in 64-bit FP. Since x86-64 in general uses the SSE2 instruction set (with 64-bit FP) instead of the deprecated x87 it does not have this problem.

like image 33
moinudin Avatar answered Dec 10 '22 10:12

moinudin