{"id":382114,"date":"2024-06-29T04:04:39","date_gmt":"2024-06-29T04:04:39","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=382114"},"modified":"-0001-11-30T00:00:00","modified_gmt":"-0001-11-29T21:00:00","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=382114","title":{"rendered":"<span>Is PHP compilable?! PVS-Studio searches for errors in PeachPie<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>PHP is widely known as an interpreted programming language used mainly for website development. However, few people know that PHP also has a compiler to .NET \u2013 PeachPie. But how well is it made? Will the static analyzer be able to find actual bugs in this compiler? Let&#8217;s find out!<\/p>\n<figure class=\"full-width\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/getpro\/habr\/upload_files\/fc7\/43d\/430\/fc743d430fe13888fc73e313de8ba73c.png\" width=\"580\" height=\"327\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/fc7\/43d\/430\/fc743d430fe13888fc73e313de8ba73c.png\"\/><figcaption><\/figcaption><\/figure>\n<p>It&#8217;s been a while since we posted articles on the C# projects check using PVS-Studio&#8230; And we still have to make the 2021 Top list of bugs (by the way, 2020 Top 10 bugs, you can find <a href=\"https:\/\/pvs-studio.com\/en\/blog\/posts\/csharp\/0787\/\">here<\/a>)! Well, we need to mend our ways. I am excited to show you a review of the <a href=\"https:\/\/www.peachpie.io\/\">PeachPie<\/a> check results.<\/p>\n<figure class=\"full-width\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/getpro\/habr\/upload_files\/6c9\/907\/b64\/6c9907b642df597de04ac4fd3923b8c5.png\" width=\"580\" height=\"148\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/6c9\/907\/b64\/6c9907b642df597de04ac4fd3923b8c5.png\"\/><figcaption><\/figcaption><\/figure>\n<p>To begin with, let me tell you a little about the project. PeachPie is a modern, open-source PHP language compiler and runtime for the .NET Framework and .NET. It is built on top of the Microsoft Roslyn compiler platform and is based on the first-generation <a href=\"https:\/\/github.com\/DEVSENSE\/Phalanger\">Phalanger<\/a> project. In July 2017, the project became a member of the <a href=\"https:\/\/dotnetfoundation.org\/\">.NET Foundation<\/a>. The source code is available in the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\">GitHub repository<\/a>.<\/p>\n<p>By the way, our C# analyzer also makes extensive use of the <a href=\"https:\/\/github.com\/dotnet\/roslyn\">Roslyn<\/a> capabilities, so in a way, PeachPie and PVS-Studio have something in common :). We&#8217;ve worked with Roslyn before. Moreover, we wrote a whole <a href=\"https:\/\/pvs-studio.com\/en\/blog\/posts\/csharp\/0399\/\">article<\/a> about the basics of working with this platform.<\/p>\n<p>To check PeachPie, we had to install the analyzer, open the project in Visual Studio or Rider and run the analysis using the PVS-Studio plugin. For more details, see the <a href=\"https:\/\/pvs-studio.com\/en\/docs\/\">documentation<\/a>.<\/p>\n<p>It was entertaining to check such a large and serious project. I hope you&#8217;ll also enjoy my review of the bugs found in PeachPie. Have fun reading!<\/p>\n<h3>WriteLine problems<\/h3>\n<p>Well, let&#8217;s start with an easy one \ud83d\ude42 Sometimes bugs can appear in the most unexpected and at the same time the simplest places. For example, an error may even appear in an easy <em>WriteLine<\/em> function call:<\/p>\n<pre><code>public static bool mail(....) {   \/\/ to and subject cannot contain newlines, replace with spaces   to = (to != null) ? to.Replace(\"\\r\\n\", \" \").Replace('\\n', ' ') : \"\";   subject = (subject != null) ? subject.Replace(\"\\r\\n\", \" \").Replace('\\n', ' ')                               : \"\";    Debug.WriteLine(\"MAILER\",                   \"mail('{0}','{1}','{2}','{3}')\",                   to,                   subject,                   message,                    additional_headers);    var config = ctx.Configuration.Core;      .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3025\/\">V3025<\/a> warning: Incorrect format. A different number of format items is expected while calling &#8216;WriteLine&#8217; function. Arguments not used: 1st, 2nd, 3rd, 4th, 5th. Mail.cs 25<\/p>\n<p>You would think, what has gone wrong? Everything seems to be fine. Wait a minute, though! What argument should pass the format?<\/p>\n<p>Well, let&#8217;s take a look at the <em>Debug.WriteLine<\/em> declaration:<\/p>\n<pre><code>public static void WriteLine(string format, params object[] args); <\/code><\/pre>\n<p>The format string should be passed as the first argument, and the first argument in the code is <em>&#171;MAILER&#187;<\/em>. Obviously, the developer mixed up the methods and passed the arguments incorrectly.<\/p>\n<h3>Same cases in switch<\/h3>\n<p>This section is devoted to warnings associated with performing the same actions in different case branches:<\/p>\n<pre><code>private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(....) {   var result = FlowAnalysisAnnotations.None;    foreach (var attr in attributes)   {     switch (attr.AttributeType.FullName)     {       case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;         break;       case \"System.Diagnostics.CodeAnalysis.DisallowNullAttribute\":         result |= FlowAnalysisAnnotations.DisallowNull;         break;       case \"System.Diagnostics.CodeAnalysis.MaybeNullAttribute\":         result |= FlowAnalysisAnnotations.MaybeNull;         break;       case \"System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute\":         if (TryGetBoolArgument(attr, out bool maybeNullWhen))         {           result |= maybeNullWhen ? FlowAnalysisAnnotations.MaybeNullWhenTrue                                   : FlowAnalysisAnnotations.MaybeNullWhenFalse;         }         break;       case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;         break;     }   } } <\/code><\/pre>\n<p>This fragment contains if not an error, then at least a strange thing. How quickly can you find it?<\/p>\n<p>However, don&#8217;t waste your time, the analyzer found everything for us:<\/p>\n<pre><code>private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(....) {   var result = FlowAnalysisAnnotations.None;    foreach (var attr in attributes)   {     switch (attr.AttributeType.FullName)     {       case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;         break;       ....       case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;              \/\/ &lt;=         break;     }   } } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3139\/\">V3139<\/a> warning: Two or more case-branches perform the same actions. ReflectionUtils.Nullability.cs 170<\/p>\n<p>Isn&#8217;t it strange that two different cases are handled the same way? In fact, no, this happens quite often. However, there are 2 peculiarities.<\/p>\n<p>Firstly, it&#8217;s worth noting that there is more graceful way to treat two different cases in the same way. You can rewrite the above fragment as follows:<\/p>\n<pre><code>switch (attr.AttributeType.FullName) {   case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":   case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":     result |= FlowAnalysisAnnotations.AllowNull;     break;   .... } <\/code><\/pre>\n<p>However, developers often neglect this convenient method and prefer copy-paste. Therefore, the presence of two identical branches doesn&#8217;t seem so terrible. The fact that the <em>FlowAnalysisAnnotations<\/em> enumeration has, among others, the <em>FlowAnalysisAnnotations.NotNull <\/em>value is much more suspicious. This value seems to be used when the <em>&#171;System.Diagnostics.CodeAnalysis.NotNullAttribute&#187;<\/em> value is processed:<\/p>\n<pre><code>switch (attr.AttributeType.FullName) {   case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":     result |= FlowAnalysisAnnotations.AllowNull;     break;   ....   case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":     result |= FlowAnalysisAnnotations.NotNull;              \/\/ &lt;=     break; } <\/code><\/pre>\n<h3>Immutable DateTime<\/h3>\n<p>Developers <a href=\"https:\/\/pvs-studio.com\/en\/blog\/examples\/v3010\/\">often make mistakes<\/a> because they don&#8217;t understand how the features of the &#171;modifying&#187; methods work. Here is the bug found in PeachPie:<\/p>\n<pre><code>using System_DateTime = System.DateTime;  internal static System_DateTime MakeDateTime(....) { .... }  public static long mktime(....) {   var zone = PhpTimeZone.GetCurrentTimeZone(ctx);   var local = MakeDateTime(hour, minute, second, month, day, year);    switch (daylightSaving)   {     case -1:       if (zone.IsDaylightSavingTime(local))         local.AddHours(-1);                   \/\/ &lt;=       break;     case 0:       break;     case 1:       local.AddHours(-1);                     \/\/ &lt;=       break;     default:       PhpException.ArgumentValueNotSupported(\"daylightSaving\", daylightSaving);       break;   }   return DateTimeUtils.UtcToUnixTimeStamp(TimeZoneInfo.ConvertTime(local,                                                                     ....)); } <\/code><\/pre>\n<p>The PVS-Studio warnings:<\/p>\n<ul>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3010\/\">V3010<\/a> The return value of function &#8216;AddHours&#8217; is required to be utilized. DateTimeFunctions.cs 1232<\/p>\n<\/li>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3010\/\">V3010<\/a> The return value of function &#8216;AddHours&#8217; is required to be utilized. DateTimeFunctions.cs 1239<\/p>\n<\/li>\n<\/ul>\n<p>The analyzer reports that the results of calls should be recorded somewhere \u2013 otherwise, they do not make any sense. The fact is, methods like <em>AddHours<\/em> don&#8217;t change the original object \u2013 instead, a new object is returned, and it differs from the original one accordingly. It&#8217;s difficult to say how critical this mistake is, but it&#8217;s clear that the code fragment doesn&#8217;t work correctly.<\/p>\n<h3>Try-methods with peculiarities<\/h3>\n<p>Try-methods are often super convenient for developing apps in C#. The best-known try-methods are <em>int.TryParse<\/em>, <em>Dictionary.TryGetValue<\/em>, etc. Usually, these methods return a flag that indicates the operation success. The result is written to the out parameter. The PeachPie developers decided to implement their try-methods which were supposed to work the same way. What came of it? Let&#8217;s look at the following code:<\/p>\n<pre><code>internal static bool TryParseIso8601Duration(string str,                                              out DateInfo result,                                              out bool negative) {   ....   if (pos >= length) goto InvalidFormat;    if (s[pos++] != 'P') goto InvalidFormat;    if (!Core.Convert.TryParseDigits(....))     goto Error;      if (pos >= length) goto InvalidFormat;    if (s[pos] == 'Y')   {     ....      if (!Core.Convert.TryParseDigits(....))        goto Error;      if (pos >= length) goto InvalidFormat;   }   ....   InvalidFormat:   Error:      result = default;     negative = default;     return false; } <\/code><\/pre>\n<p>This method is shortened for readability. You can find the full method by clicking the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.Library\/DateTime\/DateTimeParsing.cs\">link<\/a>. <em>Core.Convert.TryParseDigits<\/em> is called many times in the method. In cases when such a call returns <em>false<\/em>, the thread of execution jumps to the <em>Error<\/em> label, which is logical.<\/p>\n<p>On the <em>Error<\/em> label, default values are assigned to <em>out<\/em>-parameters. Then, the method returns <em>false<\/em>. Everything looks logical \u2013 the <em>TryParseIso8601Duration<\/em> method behaves exactly like standard try-methods. Well&#8230; At least, it&#8217;s what it looks like. In fact, it&#8217;s not like that :(.<\/p>\n<p>As I mentioned earlier if <em>Core.Convert.TryParseDigits<\/em> returns <em>false<\/em>, the code jumps to the <em>Error<\/em> label, where the bug\/issue handling is performed. However, here&#8217;s the trouble \u2013 the analyzer reports that <em>TryParseDigits<\/em> never returns <em>false<\/em>:<\/p>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;!Core.Convert.TryParseDigits(s, ref pos, false, out value, out numDigits)&#8217; is always false. DateTimeParsing.cs 1440<\/p>\n<p>If the negation of the call result is always <em>false<\/em>, then the call always returns <em>true<\/em>. What a specific behavior for the try-method! Is the operation always successful? Let&#8217;s finally look at <em>TryParseDigits<\/em>:<\/p>\n<pre><code>public static bool TryParseDigits(....) {   Debug.Assert(offset >= 0);    int offsetStart = offset;   result = 0;   numDigits = 0;    while (....)   {     var digit = s[offset] - '0';      if (result > (int.MaxValue - digit) \/ 10)     {       if (!eatDigits)       {         \/\/ overflow         \/\/return false;         throw new OverflowException();       }        ....        return true;     }      result = result * 10 + digit;     offset++;   }    numDigits = offset - offsetStart;   return true; } <\/code><\/pre>\n<p>The method does always return <em>true<\/em>. But the operation may fail \u2013 in this case, an exception of the <em>OverflowException<\/em> type is thrown. As for me, this is clearly not what you expect from a try-method :). By the way, there is a line with <em>return false<\/em>, but it is commented out.<\/p>\n<p>Perhaps, the use of an exception here is somehow justified. But according to the code, it seems that something went wrong. <em>TryParseDigits<\/em> and <em>TryParseIso8601Duration<\/em> using it are supposed to work like the usual try-methods \u2013 return <em>false<\/em> in case of failure. Instead, they throw unexpected exceptions.<\/p>\n<h3>Default argument value<\/h3>\n<p>The following analyzer message is simpler, but it also points to a rather strange code fragment:<\/p>\n<pre><code>private static bool Put(Context context,                         PhpResource ftp_stream,                         string remote_file,                         string local_file,                         int mode,                         bool append,                         int startpos) { .... }  public static bool ftp_put(Context context,                            PhpResource ftp_stream,                            string remote_file,                            string local_file,                            int mode = FTP_IMAGE,                            int startpos = 0) {     return Put(context,                ftp_stream,                remote_file,                local_file,                mode = FTP_IMAGE, \/\/ &lt;=                false,                startpos); } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3061\/\">V3061<\/a> warning: Parameter &#8216;mode&#8217; is always rewritten in method body before being used. Ftp.cs 306<\/p>\n<p>The <em>ftp_put<\/em> method accepts a number of parameters as input, one of the parameters is <em>mode<\/em>. It has a default value, but when it&#8217;s called, clearly, you can set another value. However, this doesn&#8217;t affect anything \u2013 <em>mode<\/em> is always overwritten, and the <em>Put<\/em> method always receives the value of the <em>FTP_IMAGE<\/em> constant.<\/p>\n<p>It&#8217;s difficult to say why everything is written this way \u2013 the construct seems meaningless. An error is most likely to be here.<\/p>\n<h3>Copy-paste sends greetings<\/h3>\n<p>The following code fragment looks like a copy-paste victim:<\/p>\n<pre><code>public static PhpValue filter_var(....) {   ....   if ((flags &amp; (int)FilterFlag.NO_PRIV_RANGE) == (int)FilterFlag.NO_PRIV_RANGE)   {     throw new NotImplementedException();   }    if ((flags &amp; (int)FilterFlag.NO_PRIV_RANGE) == (int)FilterFlag.NO_RES_RANGE)   {     throw new NotImplementedException();   }   .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3127\/\">V3127<\/a> warning: Two similar code fragments were found. Perhaps, this is a typo and &#8216;NO_RES_RANGE&#8217; variable should be used instead of &#8216;NO_PRIV_RANGE&#8217; Filter.cs 771<\/p>\n<p>It seems, the second condition had to be written this way:<\/p>\n<p><em>(flags &amp; (int)FilterFlag.<\/em><strong><em>NO_RES_RANGE<\/em><\/strong><em>) == (int)FilterFlag.NO_RES_RANGE<\/em><\/p>\n<p>Anyway, this option looks more logical and clear.<\/p>\n<h3>Just an extra check in the if statement<\/h3>\n<p>Let&#8217;s diversify our article with usual redundant code:<\/p>\n<pre><code>internal static NumberInfo IsNumber(....) {   ....   int num = AlphaNumericToDigit(c);    \/\/ unexpected character:   if (num &lt;= 15)   {     if (l == -1)     {       if (   longValue &lt; long.MaxValue \/ 16            || (   longValue == long.MaxValue \/ 16                &amp;&amp; num &lt;= long.MaxValue % 16))         \/\/ &lt;=       {         ....       }       ....     }     ....   }   .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3063\/\">V3063<\/a> warning: A part of conditional expression is always true if it is evaluated: num &lt;= long.MaxValue % 16. Conversions.cs 994<\/p>\n<p>Firstly, I&#8217;d like to say that the function code is significantly shortened for readability. Click on the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.Runtime\/Conversions.cs\">link<\/a> to see the full <em>IsNumber<\/em> source code \u2013 but let me warn you \u2013 it&#8217;s not easy to read. The function contains more than 300 code lines. It seems to go beyond accepted &#171;one screen&#187; :).<\/p>\n<p>Let&#8217;s move on to the warning. In the outer block the value of the <em>num<\/em> variable is checked \u2013 it must be less than or equal to 15. In the inner block <em>num<\/em> is checked \u2013 it must be less than or equal to <em>long.MaxValue % 16<\/em>. In doing so, the value of this expression is 15 \u2013 it&#8217;s easy to check. The code turns out to check twice that <em>num<\/em> is less than or equal to 15.<\/p>\n<p>This warning hardly indicates a real bug \u2013 someone just wrote an extra check. Maybe it was done on purpose \u2013 for example, to ease the reading of this exact code. Although the use of some variable or constant to store the comparison result seems to be an easier option. Anyway, the construct is redundant, and it&#8217;s the static analyzer duty to report this.<\/p>\n<h3>Could there be null?<\/h3>\n<p>Developers often miss checks for <em>null<\/em>. The situation is particularly interesting when a variable was checked in one place of the function, and in another (where it can still be <em>null<\/em>) \u2013 they forgot or didn&#8217;t find it necessary. And here we can only guess whether the check was redundant or there was a lack of it in some places. <em>Null<\/em> checks do not always involve the use of comparison operators \u2013 for example, the code fragment below shows that the developer used the <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/operators\/member-access-operators\">null-conditional operator<\/a>:<\/p>\n<pre><code>public static string get_parent_class(....) {   if (caller.Equals(default))   {     return null;   }    var tinfo = Type.GetTypeFromHandle(caller)?.GetPhpTypeInfo();   return tinfo.BaseType?.Name; } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3105\/\">V3105<\/a> warning: The &#8216;tinfo&#8217; variable was used after it was assigned through null-conditional operator. NullReferenceException is possible. Objects.cs 189<\/p>\n<p>According to the developer, the <em>Type.GetTypeFromHandle(caller)<\/em> call can return <em>null<\/em> \u2013 that&#8217;s why &#171;?.&#187; was used to call <em>GetPhpTypeInfo<\/em>. The <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.type.gettypefromhandle?view=net-5.0\">documentation<\/a> proves that it&#8217;s possible. <\/p>\n<p>Yay, &#171;?.&#187; saves from one exception. If the <em>GetTypeFromHandle<\/em> call returns <em>null<\/em>, then the <em>tinfo<\/em> variable is also assigned <em>null<\/em>. But when you try to access the <em>BaseType<\/em> property, another exception is thrown. Most likely, the last line misses another &#171;?&#187;:<\/p>\n<p><em>return tinfo?.BaseType?.Name;<\/em><\/p>\n<h3>Fatal warning and exceptions<\/h3>\n<p><em>Get ready, in this part you will find a real investigation&#8230;<\/em><\/p>\n<p>Here we have another warning related to <em>null<\/em> check. The triggering turned out to be much more exciting than it looked at first glance. Take a look at the code fragment:<\/p>\n<pre><code>static HashPhpResource ValidateHashResource(HashContext context) {   if (context == null)   {     PhpException.ArgumentNull(nameof(context));   }    return context.HashAlgorithm; } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3125\/\">V3125<\/a> warning: The &#8216;context&#8217; object was used after it was verified against null. Check lines: 3138, 3133. Hash.cs 3138<\/p>\n<p>Yes, the variable is checked for <em>null<\/em>, and then the property access without any verification occurs. However, look what happens if the variable value is <em>null<\/em>:<\/p>\n<pre><code>PhpException.ArgumentNull(nameof(context));<\/code><\/pre>\n<p>It appears that if the <em>context<\/em> is equal to <em>null<\/em>, the execution thread doesn&#8217;t get to the <em>HashAlgorithm<\/em> property access. Therefore, this code is safe. Is it a false positive?<\/p>\n<p>Of course, the analyzer can make mistakes. However, I know that PVS-Studio can handle such situations \u2013 the analyzer should have known that at the time of accessing <em>HashAlgorithm<\/em>, the <em>context<\/em> variable cannot be equal to <em>null<\/em>.<\/p>\n<p>But what exactly does the <em>PhpException.ArgumentNull<\/em> call do? Let&#8217;s take a look:<\/p>\n<pre><code>public static void ArgumentNull(string argument) {   Throw(PhpError.Warning, ErrResources.argument_null, argument); } <\/code><\/pre>\n<p>Hmm, looks like something is thrown. Pay attention to the first argument of the call \u2014 <em>PhpError.Warning<\/em>. Hmm, well, let&#8217;s move on to the <em>Throw<\/em> method:<\/p>\n<pre><code>public static void Throw(PhpError error, string formatString, string arg0) {   Throw(error, string.Format(formatString, arg0)); } <\/code><\/pre>\n<p>Basically, there&#8217;s nothing interesting here, take a look at another <em>Throw<\/em> overloading:<\/p>\n<pre><code>public static void Throw(PhpError error, string message) {   OnError?.Invoke(error, message);    \/\/ throw PhpFatalErrorException   \/\/ and terminate the script on fatal error   if ((error &amp; (PhpError)PhpErrorSets.Fatal) != 0)   {     throw new PhpFatalErrorException(message, innerException: null);   } } <\/code><\/pre>\n<p>And here is what we are looking for! It turns out that under the hood of this entire system there is <em>PhpFatalErrorException<\/em>. The exception seems to be thrown occasionally.<\/p>\n<p>Firstly, it&#8217;s worth looking at the places where the handlers of the <em>OnError<\/em> event are registered. They can throw exceptions too \u2013 that would be a little unexpected, but you never know. There are a few handlers, and they all are related to logging the corresponding messages. One handler is in the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.AspNetCore.Web\/PhpHandlerMiddleware.cs\">PhpHandlerMiddleware file<\/a>:<\/p>\n<pre><code>PhpException.OnError += (error, message) => {   switch (error)   {     case PhpError.Error:       logger.LogError(message);       break;      case PhpError.Warning:       logger.LogWarning(message);       break;      case PhpError.Notice:     default:       logger.LogInformation(message);       break;   } }; <\/code><\/pre>\n<p>Two another handlers are in the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.Runtime\/Errors.cs\">PhpException<\/a> class:<\/p>\n<pre><code>\/\/ trace output OnError += (error, message) => {   Trace.WriteLine(message, $\"PHP ({error})\"); };  \/\/ LogEventSource OnError += (error, message) => {   if ((error &amp; (PhpError)PhpErrorSets.Fatal) != 0)   {     LogEventSource.Log.HandleFatal(message);   }   else   {     LogEventSource.Log.HandleWarning(message);   } }; <\/code><\/pre>\n<p>Thus, event handlers do not generate any exceptions. So, let&#8217;s go back to the <em>Throw<\/em> method.<\/p>\n<pre><code>public static void Throw(PhpError error, string message) {   OnError?.Invoke(error, message);    \/\/ throw PhpFatalErrorException   \/\/ and terminate the script on fatal error   if ((error &amp; (PhpError)PhpErrorSets.Fatal) != 0)   {     throw new PhpFatalErrorException(message, innerException: null);   } } <\/code><\/pre>\n<p>As everything is clear with <em>OnError<\/em>, let&#8217;s take a closer look at the condition:<\/p>\n<pre><code>(error &amp; (PhpError)PhpErrorSets.Fatal) != 0 <\/code><\/pre>\n<p>The <em>error<\/em> parameter stores the value of the <em>PhpError<\/em> enumeration. Earlier, we noticed that the <em>error<\/em> parameter receives <em>PhpError.Warning<\/em>. An exception is thrown if the result of applying &#171;bitwise AND&#187; to the <em>error<\/em> and <em>PhpErrorSets.Fatal<\/em> is non-zero.<\/p>\n<p>The <em>PhpErrorSets.Fatal<\/em> value is a &#171;union&#187; of the <em>PhpError<\/em> enumeration elements created by the &#171;bitwise OR&#187; operation:<\/p>\n<pre><code>Fatal =   PhpError.E_ERROR | PhpError.E_COMPILE_ERROR         | PhpError.E_CORE_ERROR | PhpError.E_USER_ERROR <\/code><\/pre>\n<p>Below you can see the values of all the enumeration elements mentioned earlier:<\/p>\n<pre><code>E_ERROR = 1, E_WARNING = 2, E_CORE_ERROR = 16, E_COMPILE_ERROR = 64, E_USER_ERROR = 256, Warning = E_WARNING <\/code><\/pre>\n<p>The <em>error &amp; (PhpError)PhpErrorSets.Fatal<\/em> operation returns a non-zero value only if the <em>error<\/em> parameter has one of the following values or a combination of them:<\/p>\n<pre><code>PhpError.E_ERROR, PhpError.E_COMPILE_ERROR, PhpError.E_CORE_ERROR, PhpError.E_USER_ERROR <\/code><\/pre>\n<p>If the <em>error<\/em> parameter contains the <em>PhpError.Warning<\/em> value that equals <em>PhpError.E_WARNING<\/em>, the result of the &#171;bitwise AND&#187; operation is zero. Then the condition for throwing <em>PhpFatalErrorException<\/em> is not met.<\/p>\n<p>Let&#8217;s go back to the <em>PhpException.ArgumentNull<\/em> method:<\/p>\n<pre><code>public static void ArgumentNull(string argument) {   Throw(PhpError.Warning, ErrResources.argument_null, argument); } <\/code><\/pre>\n<p>We found out that when the <em>PhpError.Warning<\/em> value is passed, there is no exception. Perhaps, the developer didn&#8217;t want the exception to be thrown in cases when an unexpected <em>null<\/em> is passed. It&#8217;s just&#8230;<\/p>\n<pre><code>static HashPhpResource ValidateHashResource(HashContext context) {   if (context == null)   {     PhpException.ArgumentNull(nameof(context)); \/\/ no exceptions   }    return context.HashAlgorithm; \/\/ context is potential null } <\/code><\/pre>\n<p>If <em>PhpException.ArgumentNull<\/em> does not throw an exception (which is unexpected), then when we access the <em>HashAlgorithm<\/em> property, <em>NullReferenceException<\/em> occurs anyway!<\/p>\n<p>You might ask: should an exception be thrown or not? If it should, then it makes more sense to use the same <em>PhpFatalErrorException<\/em>. If no one expects an exception here, then you need to correctly process the <em>null<\/em> value of the <em>context<\/em> parameter. For example, you can use &#171;?.&#187;. Anyway, the analyzer dealt with this situation and even helped to understand the issue.<\/p>\n<h3>Another extra check? An exception again!<\/h3>\n<p>The last case proves that expecting an exception, you can get an unexpected <em>null<\/em>. The fragment below shows the opposite case:<\/p>\n<pre><code>public PhpValue offsetGet(PhpValue offset) {   var node = GetNodeAtIndex(offset);    Debug.Assert(node != null);    if (node != null)     return node.Value;   else     return PhpValue.Null; } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;node != null&#8217; is always true. Datastructures.cs 432<\/p>\n<p>Well, there&#8217;s no <em>null<\/em> here, then so be it! Why grumble? However, usually <em>null<\/em> is expected in cases when something is wrong. The code shows that this is exactly the case. But the analyzer insists that there couldn&#8217;t be <em>null<\/em>.<\/p>\n<p>You might think, it&#8217;s all about the <em>Debug.Assert<\/em> call in this case. For better or for worse, this call doesn&#8217;t affect the analyzer warnings.<\/p>\n<p>If it&#8217;s not about <em>Debug.Assert<\/em>, then what is it about? Why does the analyzer &#171;thinks&#187; that <em>node<\/em> is never equal to <em>null<\/em>? Let&#8217;s take a look at the <em>GetNodeAtIndex<\/em> method, that returns the value written to <em>node<\/em>:<\/p>\n<pre><code>private LinkedListNode&lt;PhpValue> GetNodeAtIndex(PhpValue index) {   return GetNodeAtIndex(GetValidIndex(index)); } <\/code><\/pre>\n<p>Well, we go deeper. Take a look at the <em>GetNodeAtIndex<\/em> method called here:<\/p>\n<pre><code>private LinkedListNode&lt;PhpValue> GetNodeAtIndex(long index) {   var node = _baseList.First;   while (index-- > 0 &amp;&amp; node != null)   {     node = node.Next;   }    return node ?? throw new OutOfRangeException(); } <\/code><\/pre>\n<p>Look! It seems that the method could return <em>null<\/em>&#8230; No such luck! If the loop is terminated, and <em>node<\/em> is equal to <em>null<\/em>, an exception is thrown. This way, no <em>null<\/em> can be returned.<\/p>\n<p>In case of an unexpected situation, the <em>GetNodeAtIndex<\/em> method doesn&#8217;t return <em>null<\/em>, as expected in the <em>offsetGet<\/em> method code:<\/p>\n<pre><code>public PhpValue offsetGet(PhpValue offset) {   var node = GetNodeAtIndex(offset); \/\/ potential null expected    Debug.Assert(node != null);    if (node != null) \/\/ always true     return node.Value;   else     return PhpValue.Null; \/\/ unreachable } <\/code><\/pre>\n<p>When a developer reviews this method, they can easily get deceived. According to the code fragment, it seems that the correct value or <em>PhpValue.Null<\/em> is returned. In fact, this method can throw an exception.<\/p>\n<p>The unexpected behavior of only one method in the call chain leads to unexpected behavior of all these methods \u2013 such a troublemaker! This example illustrates how useful static analysis is. It finds such problems automatically.<\/p>\n<p>By the way, there is a similar problem in the <em>offsetSet<\/em> method from the same class:<\/p>\n<pre><code>public void offsetSet(PhpValue offset, PhpValue value) {   var node = GetNodeAtIndex(offset);    Debug.Assert(node != null);    if (node != null)     node.Value = value; } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;node != null&#8217; is always true. Datastructures.cs 444<\/p>\n<h3>Assignments and reassignments<\/h3>\n<p>Why don&#8217;t we take a little break from all these investigations and have a cup of coffee?<\/p>\n<figure class=\"full-width\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/getpro\/habr\/upload_files\/3e9\/ad3\/233\/3e9ad323333f754406b4166b2475f0df.png\" width=\"580\" height=\"500\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/3e9\/ad3\/233\/3e9ad323333f754406b4166b2475f0df.png\"\/><figcaption><\/figcaption><\/figure>\n<p>While we&#8217;re drinking coffee, let&#8217;s take a look at a simple warning that indicates a weird code fragment:<\/p>\n<pre><code>internal StatStruct(Mono.Unix.Native.Stat stat) {   st_dev = (uint)stat.st_dev;   st_ctime = stat.st_ctime_nsec;   st_mtime = stat.st_mtime_nsec;   st_atime = stat.st_atime_nsec;   st_ctime = stat.st_ctime;   st_atime = stat.st_atime;   \/\/stat.st_blocks;   \/\/stat.st_blksize;   st_mtime = stat.st_mtime;   st_rdev = (uint)stat.st_rdev;   st_gid = (short)stat.st_gid;   st_uid = (short)stat.st_uid;   st_nlink = (short)stat.st_nlink;   st_mode = (FileModeFlags)stat.st_mode;   st_ino = (ushort)stat.st_ino;   st_size = stat.st_size; } <\/code><\/pre>\n<p>The PVS-Studio warnings:<\/p>\n<ul>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3008\/\">V3008<\/a> The &#8216;st_ctime&#8217; variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 78, 75. StatStruct.cs 78<\/p>\n<\/li>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3008\/\">V3008<\/a> The &#8216;st_atime&#8217; variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 79, 77. StatStruct.cs 79<\/p>\n<\/li>\n<\/ul>\n<p>Looks like the developer got tangled in all these assignments and made a typo somewhere. Due to this, <em>st_ctime<\/em> and <em>st_atime<\/em> fields receive the values twice \u2013 and the second value is not the same as the first one.<\/p>\n<p>It&#8217;s an error, isn&#8217;t it? But that&#8217;s no fun! I suggest you practice your skills and search for deeper meaning. Then try to explain in the comments why everything is the way it is.<\/p>\n<p>Meanwhile, let&#8217;s keep going \ud83d\ude42<\/p>\n<h3>These immutable strings&#8230;<\/h3>\n<p>At the very beginning of this article, when you were reading about the first warnings, we mentioned the immutability of <em>DateTime<\/em> structure instances. The following warnings remind us of a similar strings feature:<\/p>\n<pre><code>public TextElement Filter(IEncodingProvider enc,                           TextElement input,                           bool closing) {   string str = input.AsText(enc.StringEncoding);    if (pending)   {     if (str.Length == 0) str = \"\\r\";     else if (str[0] != '\\n') str.Insert(0, \"\\r\"); \/\/ &lt;=   }    str = str.Replace(\"\\r\\n\", \"\\n\");   if (str.Length != 0)   {     pending = str[str.Length - 1] == '\\r';      if (!closing &amp;&amp; pending) str.Remove(str.Length - 1, 1); \/\/ &lt;=   }         return new TextElement(str); } <\/code><\/pre>\n<p>The PVS-Studio warnings:<\/p>\n<ul>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3010\/\">V3010<\/a> The return value of function &#8216;Insert&#8217; is required to be utilized. Filters.cs 150<\/p>\n<\/li>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3010\/\">V3010<\/a> The return value of function &#8216;Remove&#8217; is required to be utilized. Filters.cs 161<\/p>\n<\/li>\n<\/ul>\n<p>Everything is simple and clear \u2013 we wanted to modify the string, but something&#8230; went wrong :(.<\/p>\n<h3>or throw != or null<\/h3>\n<p>Recently, we analyzed a case when a developer expected the function to return <em>null<\/em> but got an exception instead. Here is something similar but simpler:<\/p>\n<pre><code>public static bool stream_wrapper_register(....) {   \/\/ check if the scheme is already registered:   if (   string.IsNullOrEmpty(protocol)       || StreamWrapper.GetWrapperInternal(ctx, protocol) == null)   {     \/\/ TODO: Warning?     return false;   }    var wrapperClass = ctx.GetDeclaredTypeOrThrow(classname, true);   if (wrapperClass == null) \/\/ &lt;=   {     return false;   }    .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;wrapperClass == null&#8217; is always false. Streams.cs 555<\/p>\n<p>Of course, you can analyze it in detail, but&#8230; The method&#8217;s name says it all! <em>GetDeclaredTypeOrThrow<\/em> sort of hints that it&#8217;s going to throw an exception if something goes wrong. Again, here&#8217;s the thing \u2013 this behavior is also passed to the <em>stream_wrapper_register<\/em> method. But the developer wanted this method to return <em>false<\/em>. No such luck, here is an exception!<\/p>\n<p>In fact, we&#8217;ve already encountered deceptive names before. Do you remember when the <em>PhpException.ArgumentNull<\/em> method call didn&#8217;t actually throw an exception? So, let&#8217;s check whether <em>GetDeclaredTypeOrThrow<\/em> throws an exception:<\/p>\n<pre><code>PhpTypeInfo GetDeclaredTypeOrThrow(string name, bool autoload = false) {   return GetDeclaredType(name, autoload) ??          throw PhpException.ClassNotFoundException(name); } <\/code><\/pre>\n<p>Well, the PeachPie developers didn&#8217;t try to trick you here \u2013 it is a real exception :).<\/p>\n<h3>Strange &#8216;while true&#8217;<\/h3>\n<p>In some cases, developers use the <em>true <\/em>value as the<em> while <\/em>loop continuation condition<em>. <\/em>It seems to be a normal thing to do \u2013 to exit the loop, you can use<em> break, return,<\/em> or exceptions. Actually, the loop that has some expression (instead of the <em>true<\/em> keyword) as a condition looks far more than weird. The value of this expression always has the <em>true<\/em> value:<\/p>\n<pre><code>public static int stream_copy_to_stream(...., int offset = 0) {   ....   if (offset > 0)   {     int haveskipped = 0;      while (haveskipped != offset)  \/\/ &lt;=     {       TextElement data;        int toskip = offset - haveskipped;       if (toskip > from.GetNextDataLength())       {         data = from.ReadMaximumData();         if (data.IsNull) break;       }       else       {         data = from.ReadData(toskip, false);         if (data.IsNull) break; \/\/ EOF or error.         Debug.Assert(data.Length &lt;= toskip);       }        Debug.Assert(haveskipped &lt;= offset);     }   }   .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;haveskipped != offset&#8217; is always true. Streams.cs 769<\/p>\n<p>The <em>haveskipped<\/em> variable is declared before the loop. It is initialized with the 0 value. This value remains with it&#8230; until its death. Sounds gloomy but it is what it is. In fact, <em>haveskipped<\/em> is a constant. The value of the <em>offset<\/em> parameter also remains the same during the loop performance. And it remains the same in any place of the function (you can check it <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.Library\/Streams\/Streams.cs\">here<\/a>).<\/p>\n<p>Did the developer plan to make the loop continuation condition always true? Theoretically, it&#8217;s possible. But take a closer look at the loop. The following assignment looks strange:<\/p>\n<pre><code>int toskip = offset - haveskipped;<\/code><\/pre>\n<p>What&#8217;s the point, if <em>haveskipped<\/em> is always equal to 0?<\/p>\n<p>Something is wrong with the loop. Either a serious mistake is made here, or all these <em>haveskipped<\/em> weird things are the remains of some old unaccomplished ideas.<\/p>\n<h3>data == null &amp;&amp; throw NullReferenceException<\/h3>\n<p>Often, the use of incorrect operators in conditions leads to bugs. There&#8217;s a similar situation in the PHP compiler:<\/p>\n<pre><code>public string ReadStringContents(int maxLength) {   if (!CanRead) return null;   var result = StringBuilderUtilities.Pool.Get();    if (maxLength >= 0)   {     while (maxLength > 0 &amp;&amp; !Eof)     {       string data = ReadString(maxLength);       if (data == null &amp;&amp; data.Length > 0) break; \/\/ EOF or error.       maxLength -= data.Length;       result.Append(data);     }   }   .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3080\/\">V3080<\/a> warning: Possible null dereference. Consider inspecting &#8216;data&#8217;. PhpStream.cs 1382<\/p>\n<p>The value of the <em>data<\/em> variable is checked in the loop. If the variable equals <em>null<\/em> and its <em>Length<\/em> property has a positive value, then the loop exit occurs. Clearly, it&#8217;s impossible. Moreover, we have an exception when accessing the <em>Length<\/em> variable that has the <em>null<\/em> value. Here, the access deliberately takes place when <em>data = null<\/em>.<\/p>\n<p>Given the developer&#8217;s comment, I would rewrite the condition something like this:<\/p>\n<pre><code>data == null || data.Length == 0 <\/code><\/pre>\n<p>However, it doesn&#8217;t mean that this is the correct handling option \u2013 to fix this issue, it&#8217;s better to do deep code analysis.<\/p>\n<h3>Wrong exception<\/h3>\n<p>There are also bugs that do not look so terrible but still may cause problems. For example, in the following fragment, copy-paste hits again:<\/p>\n<pre><code>public bool addGlob(....) {   PhpException.FunctionNotSupported(nameof(addGlob));   return false; }  public bool addPattern(....) {   PhpException.FunctionNotSupported(nameof(addGlob));   return false; } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3013\/\">V3013<\/a> warning: It is odd that the body of &#8216;addGlob&#8217; function is fully equivalent to the body of &#8216;addPattern&#8217; function (506, line 515). ZipArchive.cs 506<\/p>\n<p>The <em>addGlob<\/em> function clearly isn&#8217;t supported, so when the function is called, there is an exception indicating that the <em>addGlob<\/em> function isn&#8217;t supported.<\/p>\n<p>Believing me? Tricked you! There is no exception here. This is our old friend \u2013 <em>PhpException<\/em>:<\/p>\n<pre><code>public static class PhpException {   ....   public static void FunctionNotSupported(string\/*!*\/function)   {     Debug.Assert(!string.IsNullOrEmpty(function));      Throw(PhpError.Warning,           ErrResources.notsupported_function_called,           function);   }   .... } <\/code><\/pre>\n<p>As we discussed earlier if the <em>Throw<\/em> method receives the <em>PhpError.Warning<\/em> value, there is no exception. But still, the appeared error is likely to be added to log or handled in some other way.<\/p>\n<p>Let&#8217;s go back to the original code fragment:<\/p>\n<pre><code>public bool addGlob(....) {   PhpException.FunctionNotSupported(nameof(addGlob));   return false; }  public bool addPattern(....) {   PhpException.FunctionNotSupported(nameof(addGlob));   return false; } <\/code><\/pre>\n<p>The <em>addGlob<\/em> function is not supported and when it&#8217;s called, the corresponding message is handled somehow \u2013 let&#8217;s assume that it is added to the log. The <em>addPattern<\/em> function isn&#8217;t supported either, however, the corresponding message is still addressed to <em>addGlob<\/em>.<\/p>\n<p>Clearly, it&#8217;s a copy-paste error. It&#8217;s easy to fix \u2013 you just need to report about <em>addPattern<\/em>, and not about <em>addGlob<\/em> in the <em>addPattern<\/em> method:<\/p>\n<pre><code>public bool addPattern(....) {   PhpException.FunctionNotSupported(nameof(addPattern));   return false; } <\/code><\/pre>\n<h3>Don&#8217;t blame String.Join!<\/h3>\n<p>Sometimes developers forget the features of some functions. That&#8217;s why they check wrong values. As a result, the check turns out to be meaningless, and there is no check where it has to be. It seems that the same thing happened to the <em>getallheaders<\/em> function:<\/p>\n<pre><code>public static PhpArray getallheaders(Context ctx) {   var webctx = ctx.HttpPhpContext;   if (webctx != null)   {     var headers = webctx.RequestHeaders;     if (headers != null)     {       var result = new PhpArray(16);        foreach (var h in headers)       {         result[h.Key] = string.Join(\", \", h.Value) ?? string.Empty;       }        return result;     }   }    return null; } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;string.Join(&#171;, &#171;, h.Value)&#8217; is always not null. The operator &#8216;??&#8217; is excessive. Web.cs 932<\/p>\n<p>It&#8217;s pointless to use the &#171;??&#187; operator here since the <em>string.Join<\/em> method never returns <em>null<\/em>. But it can always throw <em>ArgumentNullException<\/em> (You&#8217;re welcome!).<\/p>\n<p><em>string.Join<\/em> throws an exception if the passed reference to the sequence equals <em>null<\/em>. Therefore, it&#8217;s safer to write this line something like that:<\/p>\n<pre><code>result[h.Key] = h.Value != null ? string.Join(\", \",h.Value) : string.Empty; <\/code><\/pre>\n<p>Actually, I want to know, whether it&#8217;s possible for <em>Value<\/em> to be <em>null<\/em> at all? Maybe, we don&#8217;t have to check anything here. To figure it out, firstly, we need to understand where the <em>headers<\/em> collection came from.<\/p>\n<pre><code>public static PhpArray getallheaders(Context ctx) {   var webctx = ctx.HttpPhpContext;   if (webctx != null)   {     var headers = webctx.RequestHeaders;     ....   }    return null; } <\/code><\/pre>\n<p>The <em>headers<\/em> value is taken from <em>webctx.requestHeaders<\/em>, and the <em>webctx<\/em> value is taken from the <em>HttpPhpContext<\/em> property of the <em>ctx<\/em> object. And the <em>HttpPhpContext<\/em> property&#8230; Just take a look at this:<\/p>\n<pre><code>partial class Context : IEncodingProvider {   ....   public virtual IHttpPhpContext? HttpPhpContext => null;   .... } <\/code><\/pre>\n<p>This, apparently, is something left for later. If you look at the <em>getallheaders<\/em> method again, you see that it never works at all and simply returns <em>null<\/em>.<\/p>\n<p>Believing me again? But the property is virtual! Therefore, to understand what the <em>getallheaders<\/em> method can return, you need to analyze descendants. Personally, I decided to stop at this point \u2013 I still have to show other warnings.<\/p>\n<h3>Tiny assignment in a long method<\/h3>\n<p>Long and complex methods are likely to contain bugs. Over time, it&#8217;s difficult for developers to navigate in a large chunk of code, while it&#8217;s always terrifying to change it. Programmers add new code, the old one remains the same. Somehow this incredible construct works, thankfully. So, no surprise, there is some weirdness in such code. For example, take a look at the <em>inflate_fast<\/em> method:<\/p>\n<pre><code>internal int inflate_fast(....) {   ....   int r;   ....   if (c > e)   {     \/\/ if source crosses,     c -= e; \/\/ wrapped copy     if (q - r > 0 &amp;&amp; e > (q - r))     {       do       {         s.window[q++] = s.window[r++];       }       while (--e != 0);     }     else     {       Array.Copy(s.window, r, s.window, q, e);       q += e; r += e; e = 0;                     \/\/ &lt;=     }     r = 0;                                       \/\/ &lt;=   }   .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3008\/\">V3008<\/a> warning: The &#8216;r&#8217; variable is assigned values twice successfully. Perhaps this is a mistake. Check lines: 621, 619. InfCodes.cs 621<\/p>\n<p>To begin with, here is a <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.Library\/Zlib\/InfCodes.cs\">link<\/a> to full code. The method has more than two hundred lines of code with a bunch of nested constructs. It seems that it would be difficult to puzzle it out.<\/p>\n<p>The warning is unambiguous \u2013 first, a new value is assigned to the <em>r<\/em> variable in the block, and then it is definitely overwritten with zero. It&#8217;s hard to say what exactly is wrong here. Either the nullifying works somehow wrong, or the <em>r += e<\/em> construction is superfluous here.<\/p>\n<h3>null dereference in a boolean expression<\/h3>\n<p>Earlier, we discussed the case when an incorrectly constructed logical expression leads to an exception. Here is another example of such a warning:<\/p>\n<pre><code>public static bool IsAutoloadDeprecated(Version langVersion) {   \/\/ >= 7.2   return    langVersion != null &amp;&amp; langVersion.Major > 7           || (langVersion.Major == 7 &amp;&amp; langVersion.Minor >= 2); } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3080\/\">V3080<\/a> warning: Possible null dereference. Consider inspecting &#8216;langVersion&#8217;. AnalysisFacts.cs 20<\/p>\n<p>The code checks that the passed <em>langVersion<\/em> parameter doesn&#8217;t equal <em>null<\/em>. So, the developer assumed that <em>null<\/em> could be passed during the call. Does the check save you from an exception?<\/p>\n<p>Unfortunately, if the <em>langVersion<\/em> variable equals <em>null<\/em>, the value of the first part of the expression is <em>false<\/em>. When the second part is calculated, an exception is thrown.<\/p>\n<p>Generally, to improve readability we need to additionally format the code fragments to post in an article. This case isn&#8217;t an exception \u2013 the expression considered earlier, in fact, was written as one line:<\/p>\n<figure class=\"full-width\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/getpro\/habr\/upload_files\/98f\/2c3\/d3f\/98f2c3d3f2e8bdaccfa634eede86b85c.png\" width=\"885\" height=\"98\" data-src=\"https:\/\/habrastorage.org\/getpro\/habr\/upload_files\/98f\/2c3\/d3f\/98f2c3d3f2e8bdaccfa634eede86b85c.png\"\/><figcaption><\/figcaption><\/figure>\n<p>Given the comment, you can easily understand that either the operator precedence is mixed up here, or the bracket is misplaced. The method is most likely to look as follows:<\/p>\n<pre><code>public static bool IsAutoloadDeprecated(Version langVersion) {   \/\/ >= 7.2   return    langVersion != null           &amp;&amp; (   langVersion.Major > 7               || langVersion.Major == 7 &amp;&amp; langVersion.Minor >= 2); } <\/code><\/pre>\n<h3>That&#8217;s it!<\/h3>\n<p>Actually, no. The analyzer issued about 5 hundred warnings for the entire project, and there are many curious ones left waiting for the investigation. Therefore, I still suggest you <a href=\"https:\/\/pvs-studio.com\/en\/pvs-studio\/download\/?utm_source=peachpie-article&amp;utm_medium=link_download\">try PVS-Studio<\/a> and see what else it may find in this or other projects. Who knows, maybe you&#8217;ll manage to find some bugs that are even more exciting than all warnings that I&#8217;ve sorted out here :). Don&#8217;t forget to mention the found warnings in the comments. The bugs you found may get into the 2021 Top 10!<\/p>\n<p>Wish you good luck!<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/573288\/\"> https:\/\/habr.com\/ru\/articles\/573288\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>PHP is widely known as an interpreted programming language used mainly for website development. However, few people know that PHP also has a compiler to .NET \u2013 PeachPie. But how well is it made? Will the static analyzer be able to find actual bugs in this compiler? Let&#8217;s find out!<\/p>\n<figure class=\"full-width\"><figcaption><\/figcaption><\/figure>\n<p>It&#8217;s been a while since we posted articles on the C# projects check using PVS-Studio&#8230; And we still have to make the 2021 Top list of bugs (by the way, 2020 Top 10 bugs, you can find <a href=\"https:\/\/pvs-studio.com\/en\/blog\/posts\/csharp\/0787\/\">here<\/a>)! Well, we need to mend our ways. I am excited to show you a review of the <a href=\"https:\/\/www.peachpie.io\/\">PeachPie<\/a> check results.<\/p>\n<figure class=\"full-width\"><figcaption><\/figcaption><\/figure>\n<p>To begin with, let me tell you a little about the project. PeachPie is a modern, open-source PHP language compiler and runtime for the .NET Framework and .NET. It is built on top of the Microsoft Roslyn compiler platform and is based on the first-generation <a href=\"https:\/\/github.com\/DEVSENSE\/Phalanger\">Phalanger<\/a> project. In July 2017, the project became a member of the <a href=\"https:\/\/dotnetfoundation.org\/\">.NET Foundation<\/a>. The source code is available in the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\">GitHub repository<\/a>.<\/p>\n<p>By the way, our C# analyzer also makes extensive use of the <a href=\"https:\/\/github.com\/dotnet\/roslyn\">Roslyn<\/a> capabilities, so in a way, PeachPie and PVS-Studio have something in common :). We&#8217;ve worked with Roslyn before. Moreover, we wrote a whole <a href=\"https:\/\/pvs-studio.com\/en\/blog\/posts\/csharp\/0399\/\">article<\/a> about the basics of working with this platform.<\/p>\n<p>To check PeachPie, we had to install the analyzer, open the project in Visual Studio or Rider and run the analysis using the PVS-Studio plugin. For more details, see the <a href=\"https:\/\/pvs-studio.com\/en\/docs\/\">documentation<\/a>.<\/p>\n<p>It was entertaining to check such a large and serious project. I hope you&#8217;ll also enjoy my review of the bugs found in PeachPie. Have fun reading!<\/p>\n<h3>WriteLine problems<\/h3>\n<p>Well, let&#8217;s start with an easy one \ud83d\ude42 Sometimes bugs can appear in the most unexpected and at the same time the simplest places. For example, an error may even appear in an easy <em>WriteLine<\/em> function call:<\/p>\n<pre><code>public static bool mail(....) {   \/\/ to and subject cannot contain newlines, replace with spaces   to = (to != null) ? to.Replace(\"\\r\\n\", \" \").Replace('\\n', ' ') : \"\";   subject = (subject != null) ? subject.Replace(\"\\r\\n\", \" \").Replace('\\n', ' ')                               : \"\";    Debug.WriteLine(\"MAILER\",                   \"mail('{0}','{1}','{2}','{3}')\",                   to,                   subject,                   message,                    additional_headers);    var config = ctx.Configuration.Core;      .... } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3025\/\">V3025<\/a> warning: Incorrect format. A different number of format items is expected while calling &#8216;WriteLine&#8217; function. Arguments not used: 1st, 2nd, 3rd, 4th, 5th. Mail.cs 25<\/p>\n<p>You would think, what has gone wrong? Everything seems to be fine. Wait a minute, though! What argument should pass the format?<\/p>\n<p>Well, let&#8217;s take a look at the <em>Debug.WriteLine<\/em> declaration:<\/p>\n<pre><code>public static void WriteLine(string format, params object[] args); <\/code><\/pre>\n<p>The format string should be passed as the first argument, and the first argument in the code is <em>&#171;MAILER&#187;<\/em>. Obviously, the developer mixed up the methods and passed the arguments incorrectly.<\/p>\n<h3>Same cases in switch<\/h3>\n<p>This section is devoted to warnings associated with performing the same actions in different case branches:<\/p>\n<pre><code>private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(....) {   var result = FlowAnalysisAnnotations.None;    foreach (var attr in attributes)   {     switch (attr.AttributeType.FullName)     {       case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;         break;       case \"System.Diagnostics.CodeAnalysis.DisallowNullAttribute\":         result |= FlowAnalysisAnnotations.DisallowNull;         break;       case \"System.Diagnostics.CodeAnalysis.MaybeNullAttribute\":         result |= FlowAnalysisAnnotations.MaybeNull;         break;       case \"System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute\":         if (TryGetBoolArgument(attr, out bool maybeNullWhen))         {           result |= maybeNullWhen ? FlowAnalysisAnnotations.MaybeNullWhenTrue                                   : FlowAnalysisAnnotations.MaybeNullWhenFalse;         }         break;       case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;         break;     }   } } <\/code><\/pre>\n<p>This fragment contains if not an error, then at least a strange thing. How quickly can you find it?<\/p>\n<p>However, don&#8217;t waste your time, the analyzer found everything for us:<\/p>\n<pre><code>private static FlowAnalysisAnnotations DecodeFlowAnalysisAttributes(....) {   var result = FlowAnalysisAnnotations.None;    foreach (var attr in attributes)   {     switch (attr.AttributeType.FullName)     {       case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;         break;       ....       case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":         result |= FlowAnalysisAnnotations.AllowNull;              \/\/ &lt;=         break;     }   } } <\/code><\/pre>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3139\/\">V3139<\/a> warning: Two or more case-branches perform the same actions. ReflectionUtils.Nullability.cs 170<\/p>\n<p>Isn&#8217;t it strange that two different cases are handled the same way? In fact, no, this happens quite often. However, there are 2 peculiarities.<\/p>\n<p>Firstly, it&#8217;s worth noting that there is more graceful way to treat two different cases in the same way. You can rewrite the above fragment as follows:<\/p>\n<pre><code>switch (attr.AttributeType.FullName) {   case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":   case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":     result |= FlowAnalysisAnnotations.AllowNull;     break;   .... } <\/code><\/pre>\n<p>However, developers often neglect this convenient method and prefer copy-paste. Therefore, the presence of two identical branches doesn&#8217;t seem so terrible. The fact that the <em>FlowAnalysisAnnotations<\/em> enumeration has, among others, the <em>FlowAnalysisAnnotations.NotNull <\/em>value is much more suspicious. This value seems to be used when the <em>&#171;System.Diagnostics.CodeAnalysis.NotNullAttribute&#187;<\/em> value is processed:<\/p>\n<pre><code>switch (attr.AttributeType.FullName) {   case \"System.Diagnostics.CodeAnalysis.AllowNullAttribute\":     result |= FlowAnalysisAnnotations.AllowNull;     break;   ....   case \"System.Diagnostics.CodeAnalysis.NotNullAttribute\":     result |= FlowAnalysisAnnotations.NotNull;              \/\/ &lt;=     break; } <\/code><\/pre>\n<h3>Immutable DateTime<\/h3>\n<p>Developers <a href=\"https:\/\/pvs-studio.com\/en\/blog\/examples\/v3010\/\">often make mistakes<\/a> because they don&#8217;t understand how the features of the &#171;modifying&#187; methods work. Here is the bug found in PeachPie:<\/p>\n<pre><code>using System_DateTime = System.DateTime;  internal static System_DateTime MakeDateTime(....) { .... }  public static long mktime(....) {   var zone = PhpTimeZone.GetCurrentTimeZone(ctx);   var local = MakeDateTime(hour, minute, second, month, day, year);    switch (daylightSaving)   {     case -1:       if (zone.IsDaylightSavingTime(local))         local.AddHours(-1);                   \/\/ &lt;=       break;     case 0:       break;     case 1:       local.AddHours(-1);                     \/\/ &lt;=       break;     default:       PhpException.ArgumentValueNotSupported(\"daylightSaving\", daylightSaving);       break;   }   return DateTimeUtils.UtcToUnixTimeStamp(TimeZoneInfo.ConvertTime(local,                                                                     ....)); } <\/code><\/pre>\n<p>The PVS-Studio warnings:<\/p>\n<ul>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3010\/\">V3010<\/a> The return value of function &#8216;AddHours&#8217; is required to be utilized. DateTimeFunctions.cs 1232<\/p>\n<\/li>\n<li>\n<p><a href=\"https:\/\/pvs-studio.com\/en\/w\/v3010\/\">V3010<\/a> The return value of function &#8216;AddHours&#8217; is required to be utilized. DateTimeFunctions.cs 1239<\/p>\n<\/li>\n<\/ul>\n<p>The analyzer reports that the results of calls should be recorded somewhere \u2013 otherwise, they do not make any sense. The fact is, methods like <em>AddHours<\/em> don&#8217;t change the original object \u2013 instead, a new object is returned, and it differs from the original one accordingly. It&#8217;s difficult to say how critical this mistake is, but it&#8217;s clear that the code fragment doesn&#8217;t work correctly.<\/p>\n<h3>Try-methods with peculiarities<\/h3>\n<p>Try-methods are often super convenient for developing apps in C#. The best-known try-methods are <em>int.TryParse<\/em>, <em>Dictionary.TryGetValue<\/em>, etc. Usually, these methods return a flag that indicates the operation success. The result is written to the out parameter. The PeachPie developers decided to implement their try-methods which were supposed to work the same way. What came of it? Let&#8217;s look at the following code:<\/p>\n<pre><code>internal static bool TryParseIso8601Duration(string str,                                              out DateInfo result,                                              out bool negative) {   ....   if (pos >= length) goto InvalidFormat;    if (s[pos++] != 'P') goto InvalidFormat;    if (!Core.Convert.TryParseDigits(....))     goto Error;      if (pos >= length) goto InvalidFormat;    if (s[pos] == 'Y')   {     ....      if (!Core.Convert.TryParseDigits(....))        goto Error;      if (pos >= length) goto InvalidFormat;   }   ....   InvalidFormat:   Error:      result = default;     negative = default;     return false; } <\/code><\/pre>\n<p>This method is shortened for readability. You can find the full method by clicking the <a href=\"https:\/\/github.com\/peachpiecompiler\/peachpie\/blob\/cfbcc7cc34fb78097a53ec25b2ad78242160f22e\/src\/Peachpie.Library\/DateTime\/DateTimeParsing.cs\">link<\/a>. <em>Core.Convert.TryParseDigits<\/em> is called many times in the method. In cases when such a call returns <em>false<\/em>, the thread of execution jumps to the <em>Error<\/em> label, which is logical.<\/p>\n<p>On the <em>Error<\/em> label, default values are assigned to <em>out<\/em>-parameters. Then, the method returns <em>false<\/em>. Everything looks logical \u2013 the <em>TryParseIso8601Duration<\/em> method behaves exactly like standard try-methods. Well&#8230; At least, it&#8217;s what it looks like. In fact, it&#8217;s not like that :(.<\/p>\n<p>As I mentioned earlier if <em>Core.Convert.TryParseDigits<\/em> returns <em>false<\/em>, the code jumps to the <em>Error<\/em> label, where the bug\/issue handling is performed. However, here&#8217;s the trouble \u2013 the analyzer reports that <em>TryParseDigits<\/em> never returns <em>false<\/em>:<\/p>\n<p>The <a href=\"https:\/\/pvs-studio.com\/en\/w\/v3022\/\">V3022<\/a> warning: Expression &#8216;!Core.Convert.TryParseDigits(s, ref pos, false, out value, out numDigits)&#8217; is always false. DateTimeParsing.cs 1440<\/p>\n<p>If the negation of the call result is always <em>false<\/em>, then the call always returns <em>true<\/em>. What a specific behavior for the try-method! Is the operation always successful? Let&#8217;s finally look at <em>TryParseDigits<\/em>:<\/p>\n<pre><code>public static bool TryParseDigits(....) {   Debug.Assert(offset >= 0);    int<\/code><\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-382114","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/382114","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=382114"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/382114\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=382114"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=382114"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=382114"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}