peachpiecompiler / peachpie

PeachPie - the PHP compiler and runtime for .NET and .NET Core
https://www.peachpie.io
Apache License 2.0
2.31k stars 202 forks source link

Unexpected results when working with binary strings #981

Closed kripper closed 1 year ago

kripper commented 2 years ago

This asserts fail when working with WebAssemblies:

<?
$ub = chr(220);
$s1 = str_repeat($ub, 4);
$s2 = $ub . $ub . $ub . $ub;
assert(base64_encode($s1) == "3Nzc3A==", 'str_repeat fails');
assert(base64_encode($s2) == "3Nzc3A==", 'chr() fails');
kripper commented 2 years ago

base64_encode(chr(220)) also gives a wrong result.

kripper commented 2 years ago

BTW, the test case can be easily placed inside PHPScripts/index.php following the instructions here: https://www.peachpie.io/2021/08/run-debug-php-browser.html

Then execute dotnet run inside BlazorApp\Client.

kripper commented 2 years ago

Hi @jakubmisek, do you know if there is some configuration or workaround to support working with binary strings on PeachPie WebAssemblies?

jakubmisek commented 2 years ago

@kripper there is nothing special for webasm, just a thin wrapper at https://github.com/peachpiecompiler/peachpie-blazor . Strings are handled the same

kripper commented 2 years ago

Right. I tested on peachpie (latest version) and both asserts fail too for a console app. I tried adding the (binary) cast, using mb_chr(220, 'ASCII'), but everything fails. Is there any way to create a binary string containig chr(220)?

jakubmisek commented 2 years ago

https://github.com/peachpiecompiler/peachpie/blob/9dec67e719f762c5c8c4c1a5200651471ef5096f/src/Peachpie.Library/Strings.cs#L57

chr(220) // == new byte[]{ 220 }
kripper commented 2 years ago

It seems like chr() only returns binary strings when bytevalue < 240.

        public static PhpString chr(int bytevalue)
        {
            if (bytevalue < 0xf0)
            {
                return ((char)bytevalue).ToString();
            }
            else
            {
                return new PhpString(new byte[] { (byte)bytevalue });
            }
        }
kripper commented 2 years ago

Can we add an option to make chr() compatbile with Zend's PHP? I believe most of the time we see chr() in the code is because the programmer wants to generate binary code.

jakubmisek commented 2 years ago

seems like a typo, should be string only for 32 <= bytevalue < 128

kripper commented 2 years ago

Agree.

kripper commented 1 year ago

Tested and working fine after https://github.com/peachpiecompiler/peachpie/pull/982