SlideShare a Scribd company logo
1 of 6
Download to read offline
How the PVS-Studio analyzer began to
find even more errors in Unity projects
Author: Nikita Lipilin
Date: 29.06.2020
Tags: CSharp, GameDev
When developing the PVS-Studio static analyzer, we try to develop it in various directions. Thus, our
team is working on plugins for the IDE (Visual Studio, Rider), improving integration with CI, and so
on. Increasing the efficiency of project analysis under Unity is also one of our priority goals. We
believe that static analysis will allow programmers using this game engine to improve the quality of
their source code and simplify work on any projects. Therefore, we would like to increase the
popularity of PVS-Studio among companies that develop under Unity. One of the first steps in
implementing this idea was to write annotations for the methods defined in the engine. This allows a
developer to control the correctness of the code related to calls of annotated methods.
Introduction
Annotations are one of the most important mechanisms of the analyzer. They provide various
information about arguments, return values, and internal features of methods that can't be found
out in the automatic mode. At the same time, the developer who annotates a method can assume
its approximate internal structure and features of its operation, based on documentation and
common sense.
For example, calling the GetComponent method looks somewhat strange if the value it returned
isn't used. A trifling bug? In no way. Of course, this may simply be a redundant call, forgotten and
abandoned by everyone. Or it may be that some important assignment was omitted. Annotations
can help the analyzer find similar and many other errors.
Of course, we have already written a lot of annotations for the analyzer. For example, class methods
from the System namespace are annotated. In addition, there is a mechanism to automatically
annotate some methods. You can read here in detail about it. Note that this article tells more about
the part of PVS-Studio that is responsible for analyzing projects in C++. However, there is no
noticeable difference in the way annotations work for C# and C++.
Writing annotations for Unity methods
We strive to improve the quality of checking the code of projects that use Unity, which is why we
decided to annotate methods of this engine.
The initial idea was to cover all Unity methods with annotations, however there has been a lot of
them. As a result, we decided to start by annotating methods from the most commonly used classes.
Collecting information
First, we had to find out which classes are used more often than others. In addition, an important
aspect was to ensure that you can collect annotation results – new errors that the analyzer will find
in real projects thanks to the written annotations. Therefore, the first step was to search for
appropriate open source projects. However, this was not so easy to do.
The problem is that many of the projects found were quite small in terms of the source code. If there
are errors in such projects, their number is small. Not to mention the fact that it is less likely to find
some warnings related to methods from Unity in them. Occasionally, some projects came up which
almost haven't used (or haven't used at all) Unity-specific classes, although they were described as
related to the engine in one way or another. Such finds were completely unsuitable for the task at
hand.
Of course, in some cases I was lucky. For example, the gem in this collection is MixedRealityToolkit.
There is already quite a lot of code in it, which means that the collected statistics on the use of Unity
methods in such a project will be more complete.
Thus, there were 20 projects that use the engine's abilities. In order to find the most frequently used
classes, a Roslyn based utility was written that counts method calls from Unity. This program, by the
way, can also be called a static analyzer. After all, if you think about it, it really analyzes the source
code, without running the project itself.
The written "analyzer" allowed us to find classes whose average frequency of use in the found
projects was the highest:
• UnityEngine.Vector3
• UnityEngine.Mathf
• UnityEngine.Debug
• UnityEngine.GameObject
• UnityEngine.Material
• UnityEditor.EditorGUILayout
• UnityEngine.Component
• UnityEngine.Object
• UnityEngine.GUILayout
• UnityEngine.Quaternion
• and others.
Of course, this doesn't mean that these classes are actually used very often by developers – after all,
statistics based on such a small set of projects aren't particularly trustworthy. However, to start
with, this information was enough to make sure that the annotated methods' classes were used at
least somewhere.
Annotating
After getting the necessary information, it's time to do the actual annotation. The documentation
and the Unity editor, where the test project was created, were reliable helpers in this case. It was
necessary to check some points that weren't specified in the documentation. For example, it was not
always clear whether passing null as any argument would lead to an error, or whether the program
would continue running without problems. Of course, passing null is usually not a good practice, but
in this case, we only considered errors that interrupted the execution flow, or were logged by the
Unity editor as an error.
During these checks, interesting features of some methods were found. For example, running the
code
MeshRenderer renderer = cube.GetComponent<MeshRenderer>();
Material m = renderer.material;
List<int> outNames = null;
m.GetTexturePropertyNameIDs(outNames);
makes the Unity editor itself crash, although usually in such cases, the current script execution is
interrupted and the corresponding error is logged. Of course, it is unlikely that developers often
write such things, but the fact that the Unity editor can be crashed by running regular scripts isn't
nice. The same thing happens in at least one other case:
MeshRenderer renderer = cube.GetComponent<MeshRenderer>();
Material m = renderer.material;
string keyWord = null;
bool isEnabled = m.IsKeywordEnabled(keyWord);
These issues are relevant for the Unity 2019.3.10f1 editor.
Collecting the results
After the annotation is completed, you need to check how this will affect the warnings being issued.
Before adding annotations, an error log is generated for each of the selected projects, which we call
the reference log. Then the new annotations are embedded in the analyzer and the projects are
checked again. The generated warning lists will differ from the reference ones due to annotations.
The annotation testing procedure is performed automatically using the CSharpAnalyserTester
program specifically written for these needs. It runs analysis on projects, then compares the
resulting logs with the reference ones and generates files containing information about differences.
The described approach is also used to find out what changes in logs appear when a new diagnostic
is added or an existing one is changed.
As noted earlier, it was difficult to find large open projects under Unity. This is unpleasant, as the
analyzer would be able to produce more interesting warnings for them. At the same time, there
would be much more differences between reference logs and logs generated after annotation.
Nevertheless, the written annotations helped to identify several suspicious points in the projects
under consideration, which is also a favorable result of the work.
For example, a bit strange call of GetComponent was found:
void OnEnable()
{
GameObject uiManager = GameObject.Find("UIRoot");
if (uiManager)
{
uiManager.GetComponent<UIManager>();
}
}
Analyzer warning: V3010 The return value of function 'GetComponent' is required to be utilized. -
ADDITIONAL IN CURRENT UIEditorWindow.cs 22
Based on the documentation, it is logical to conclude that the value returned by this method should
be used in some way. Therefore, it was marked accordingly when annotated. In this case, the result
of the call isn't assigned to anything, which looks a bit strange.
Here is another example of additional analyzer warnings:
public void ChangeLocalID(int newID)
{
if (this.LocalPlayer == null) // <=
{
this.DebugReturn(
DebugLevel.WARNING,
string.Format(
....,
this.LocalPlayer,
this.CurrentRoom.Players == null, // <=
newID
)
);
}
if (this.CurrentRoom == null) // <=
{
this.LocalPlayer.ChangeLocalID(newID); // <=
this.LocalPlayer.RoomReference = null;
}
else
{
// remove old actorId from actor list
this.CurrentRoom.RemovePlayer(this.LocalPlayer);
// change to new actor/player ID
this.LocalPlayer.ChangeLocalID(newID);
// update the room's list with the new reference
this.CurrentRoom.StorePlayer(this.LocalPlayer);
}
}
Analyzer warnings:
• V3095 The 'this.CurrentRoom' object was used before it was verified against null. Check
lines: 1709, 1712. - ADDITIONAL IN CURRENT LoadBalancingClient.cs 1709
• V3125 The 'this.LocalPlayer' object was used after it was verified against null. Check lines:
1715, 1707. - ADDITIONAL IN CURRENT LoadBalancingClient.cs 1715
Note that PVS-Studio doesn't pay attention to passing LocalPlayer to string.Format, since this won't
cause an error. And the code looks like it was written intentionally.
In this case, the impact of annotations isn't so obvious. However, they are the reason for these
triggerings. So here comes the question - why were there no such warnings before?
The fact is that the DebugReturn method makes several calls, which in theory could affect the value
of the CurrentRoom property:
public virtual void DebugReturn(DebugLevel level, string message)
{
#if !SUPPORTED_UNITY
Debug.WriteLine(message);
#else
if (level == DebugLevel.ERROR)
{
Debug.LogError(message);
}
else if (level == DebugLevel.WARNING)
{
Debug.LogWarning(message);
}
else if (level == DebugLevel.INFO)
{
Debug.Log(message);
}
else if (level == DebugLevel.ALL)
{
Debug.Log(message);
}
#endif
}
The analyzer doesn't know how the called methods work, so it doesn't know how they will affect the
situation. For example, PVS-Studio assumes that the value of this.CurrentRoom may have changed
during the DebugReturn method, so the check is performed next.
The annotations also provided the information that methods called inside DebugReturn won't affect
the values of other variables. Therefore, using a variable before checking it for null can be
considered suspicious.
Conclusion
To sum up, annotating Unity-specific methods will undoubtedly allow you to find more errors in
projects that use this engine. However, annotating all available methods will take quite a long time.
It is more efficient to annotate the most frequently used ones first. However, in order to understand
which classes are used more often, you need suitable projects with a large code base. In addition,
large projects allow much better control over the effectiveness of annotation. We will continue to do
all this in the near future.
The analyzer is constantly being developed and refined. Adding annotations to Unity methods is just
one example of extending its abilities. Thus, over time, the efficiency of PVS-Studio increases. So if
you haven't tried PVS-Studio yet, it's time to fix it by downloading it from the corresponding page.
There you can also get a trial key for the analyzer to get acquainted with its abilities by checking
various projects.

More Related Content

What's hot

Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...Andrey Karpov
 
150412 38 beamer methods of binary analysis
150412 38 beamer methods of  binary analysis150412 38 beamer methods of  binary analysis
150412 38 beamer methods of binary analysisRaghu Palakodety
 
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-StudioHow to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-StudioPVS-Studio
 
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...acijjournal
 
War of the Machines: PVS-Studio vs. TensorFlow
War of the Machines: PVS-Studio vs. TensorFlowWar of the Machines: PVS-Studio vs. TensorFlow
War of the Machines: PVS-Studio vs. TensorFlowPVS-Studio
 
Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...PVS-Studio
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactusHimanshu
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggyPVS-Studio
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Deepak Singhvi
 
Quick test professional certifcation questions and tutorial2
Quick test professional certifcation questions and tutorial2Quick test professional certifcation questions and tutorial2
Quick test professional certifcation questions and tutorial2Ramu Palanki
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckAndrey Karpov
 
Cppcheck and PVS-Studio compared
Cppcheck and PVS-Studio comparedCppcheck and PVS-Studio compared
Cppcheck and PVS-Studio comparedPVS-Studio
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityPVS-Studio
 

What's hot (20)

Rootkit case
Rootkit caseRootkit case
Rootkit case
 
Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
150412 38 beamer methods of binary analysis
150412 38 beamer methods of  binary analysis150412 38 beamer methods of  binary analysis
150412 38 beamer methods of binary analysis
 
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-StudioHow to Improve Visual C++ 2017 Libraries Using PVS-Studio
How to Improve Visual C++ 2017 Libraries Using PVS-Studio
 
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
AUTOCODECOVERGEN: PROTOTYPE OF DATA DRIVEN UNIT TEST GENRATION TOOL THAT GUAR...
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
War of the Machines: PVS-Studio vs. TensorFlow
War of the Machines: PVS-Studio vs. TensorFlowWar of the Machines: PVS-Studio vs. TensorFlow
War of the Machines: PVS-Studio vs. TensorFlow
 
Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...Static analysis is most efficient when being used regularly. We'll tell you w...
Static analysis is most efficient when being used regularly. We'll tell you w...
 
Junit and cactus
Junit and cactusJunit and cactus
Junit and cactus
 
Why Windows 8 drivers are buggy
Why Windows 8 drivers are buggyWhy Windows 8 drivers are buggy
Why Windows 8 drivers are buggy
 
J Unit
J UnitJ Unit
J Unit
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.Testing and Mocking Object - The Art of Mocking.
Testing and Mocking Object - The Art of Mocking.
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Quick test professional certifcation questions and tutorial2
Quick test professional certifcation questions and tutorial2Quick test professional certifcation questions and tutorial2
Quick test professional certifcation questions and tutorial2
 
PVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd CheckPVS-Studio vs Chromium. 3-rd Check
PVS-Studio vs Chromium. 3-rd Check
 
Cppcheck and PVS-Studio compared
Cppcheck and PVS-Studio comparedCppcheck and PVS-Studio compared
Cppcheck and PVS-Studio compared
 
We Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High QualityWe Continue Exploring Tizen: C# Components Proved to be of High Quality
We Continue Exploring Tizen: C# Components Proved to be of High Quality
 
Junit
JunitJunit
Junit
 

Similar to How the PVS-Studio analyzer began to find even more errors in Unity projects

Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team developmentAndrey Karpov
 
Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team developmentPVS-Studio
 
Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team developmentPVS-Studio
 
Static analysis as part of the development process in Unreal Engine
Static analysis as part of the development process in Unreal EngineStatic analysis as part of the development process in Unreal Engine
Static analysis as part of the development process in Unreal EnginePVS-Studio
 
Searching for bugs in Mono: there are hundreds of them!
Searching for bugs in Mono: there are hundreds of them!Searching for bugs in Mono: there are hundreds of them!
Searching for bugs in Mono: there are hundreds of them!PVS-Studio
 
PVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to BoostPVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to BoostAndrey Karpov
 
S D D Program Development Tools
S D D  Program  Development  ToolsS D D  Program  Development  Tools
S D D Program Development Toolsgavhays
 
How we test the code analyzer
How we test the code analyzerHow we test the code analyzer
How we test the code analyzerPVS-Studio
 
How we test the code analyzer
How we test the code analyzerHow we test the code analyzer
How we test the code analyzerPVS-Studio
 
Static Analysis: From Getting Started to Integration
Static Analysis: From Getting Started to IntegrationStatic Analysis: From Getting Started to Integration
Static Analysis: From Getting Started to IntegrationAndrey Karpov
 
Espressif IoT Development Framework: 71 Shots in the Foot
Espressif IoT Development Framework: 71 Shots in the FootEspressif IoT Development Framework: 71 Shots in the Foot
Espressif IoT Development Framework: 71 Shots in the FootAndrey Karpov
 
An ideal static analyzer, or why ideals are unachievable
An ideal static analyzer, or why ideals are unachievableAn ideal static analyzer, or why ideals are unachievable
An ideal static analyzer, or why ideals are unachievablePVS-Studio
 
0136 ideal static_analyzer
0136 ideal static_analyzer0136 ideal static_analyzer
0136 ideal static_analyzerPVS-Studio
 
The Development History of PVS-Studio for Linux
The Development History of PVS-Studio for LinuxThe Development History of PVS-Studio for Linux
The Development History of PVS-Studio for LinuxPVS-Studio
 
PVS-Studio confesses its love for Linux
PVS-Studio confesses its love for LinuxPVS-Studio confesses its love for Linux
PVS-Studio confesses its love for LinuxPVS-Studio
 
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...Andrey Karpov
 
If the coding bug is banal, it doesn't meant it's not crucial
If the coding bug is banal, it doesn't meant it's not crucialIf the coding bug is banal, it doesn't meant it's not crucial
If the coding bug is banal, it doesn't meant it's not crucialPVS-Studio
 
Three Interviews About Static Code Analyzers
Three Interviews About Static Code AnalyzersThree Interviews About Static Code Analyzers
Three Interviews About Static Code AnalyzersAndrey Karpov
 

Similar to How the PVS-Studio analyzer began to find even more errors in Unity projects (20)

Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team development
 
Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team development
 
Regular use of static code analysis in team development
Regular use of static code analysis in team developmentRegular use of static code analysis in team development
Regular use of static code analysis in team development
 
Static analysis as part of the development process in Unreal Engine
Static analysis as part of the development process in Unreal EngineStatic analysis as part of the development process in Unreal Engine
Static analysis as part of the development process in Unreal Engine
 
Searching for bugs in Mono: there are hundreds of them!
Searching for bugs in Mono: there are hundreds of them!Searching for bugs in Mono: there are hundreds of them!
Searching for bugs in Mono: there are hundreds of them!
 
PVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to BoostPVS-Studio Has Finally Got to Boost
PVS-Studio Has Finally Got to Boost
 
S D D Program Development Tools
S D D  Program  Development  ToolsS D D  Program  Development  Tools
S D D Program Development Tools
 
How we test the code analyzer
How we test the code analyzerHow we test the code analyzer
How we test the code analyzer
 
How we test the code analyzer
How we test the code analyzerHow we test the code analyzer
How we test the code analyzer
 
Static Analysis: From Getting Started to Integration
Static Analysis: From Getting Started to IntegrationStatic Analysis: From Getting Started to Integration
Static Analysis: From Getting Started to Integration
 
Espressif IoT Development Framework: 71 Shots in the Foot
Espressif IoT Development Framework: 71 Shots in the FootEspressif IoT Development Framework: 71 Shots in the Foot
Espressif IoT Development Framework: 71 Shots in the Foot
 
An ideal static analyzer, or why ideals are unachievable
An ideal static analyzer, or why ideals are unachievableAn ideal static analyzer, or why ideals are unachievable
An ideal static analyzer, or why ideals are unachievable
 
0136 ideal static_analyzer
0136 ideal static_analyzer0136 ideal static_analyzer
0136 ideal static_analyzer
 
test
testtest
test
 
The Development History of PVS-Studio for Linux
The Development History of PVS-Studio for LinuxThe Development History of PVS-Studio for Linux
The Development History of PVS-Studio for Linux
 
PVS-Studio confesses its love for Linux
PVS-Studio confesses its love for LinuxPVS-Studio confesses its love for Linux
PVS-Studio confesses its love for Linux
 
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
PVS-Studio and CppCat: An Interview with Andrey Karpov, the Project CTO and D...
 
test
testtest
test
 
If the coding bug is banal, it doesn't meant it's not crucial
If the coding bug is banal, it doesn't meant it's not crucialIf the coding bug is banal, it doesn't meant it's not crucial
If the coding bug is banal, it doesn't meant it's not crucial
 
Three Interviews About Static Code Analyzers
Three Interviews About Static Code AnalyzersThree Interviews About Static Code Analyzers
Three Interviews About Static Code Analyzers
 

More from Andrey Karpov

60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста60 антипаттернов для С++ программиста
60 антипаттернов для С++ программистаAndrey Karpov
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developerAndrey Karpov
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Andrey Karpov
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesAndrey Karpov
 
PVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewPVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewAndrey Karpov
 
PVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокPVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокAndrey Karpov
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Andrey Karpov
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?Andrey Karpov
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaAndrey Karpov
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)Andrey Karpov
 
Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Andrey Karpov
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerAndrey Karpov
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareAndrey Karpov
 
Static Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineStatic Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineAndrey Karpov
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsAndrey Karpov
 
The Great and Mighty C++
The Great and Mighty C++The Great and Mighty C++
The Great and Mighty C++Andrey Karpov
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youAndrey Karpov
 

More from Andrey Karpov (20)

60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста60 антипаттернов для С++ программиста
60 антипаттернов для С++ программиста
 
60 terrible tips for a C++ developer
60 terrible tips for a C++ developer60 terrible tips for a C++ developer
60 terrible tips for a C++ developer
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
PVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature OverviewPVS-Studio in 2021 - Feature Overview
PVS-Studio in 2021 - Feature Overview
 
PVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибокPVS-Studio в 2021 - Примеры ошибок
PVS-Studio в 2021 - Примеры ошибок
 
PVS-Studio в 2021
PVS-Studio в 2021PVS-Studio в 2021
PVS-Studio в 2021
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Does static analysis need machine learning?
Does static analysis need machine learning?Does static analysis need machine learning?
Does static analysis need machine learning?
 
Typical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and JavaTypical errors in code on the example of C++, C#, and Java
Typical errors in code on the example of C++, C#, and Java
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
 
Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?Game Engine Code Quality: Is Everything Really That Bad?
Game Engine Code Quality: Is Everything Really That Bad?
 
C++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical ReviewerC++ Code as Seen by a Hypercritical Reviewer
C++ Code as Seen by a Hypercritical Reviewer
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
 
Static Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal EngineStatic Code Analysis for Projects, Built on Unreal Engine
Static Code Analysis for Projects, Built on Unreal Engine
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded SystemsSafety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
 
The Great and Mighty C++
The Great and Mighty C++The Great and Mighty C++
The Great and Mighty C++
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Zero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for youZero, one, two, Freddy's coming for you
Zero, one, two, Freddy's coming for you
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

How the PVS-Studio analyzer began to find even more errors in Unity projects

  • 1. How the PVS-Studio analyzer began to find even more errors in Unity projects Author: Nikita Lipilin Date: 29.06.2020 Tags: CSharp, GameDev When developing the PVS-Studio static analyzer, we try to develop it in various directions. Thus, our team is working on plugins for the IDE (Visual Studio, Rider), improving integration with CI, and so on. Increasing the efficiency of project analysis under Unity is also one of our priority goals. We believe that static analysis will allow programmers using this game engine to improve the quality of their source code and simplify work on any projects. Therefore, we would like to increase the popularity of PVS-Studio among companies that develop under Unity. One of the first steps in implementing this idea was to write annotations for the methods defined in the engine. This allows a developer to control the correctness of the code related to calls of annotated methods. Introduction Annotations are one of the most important mechanisms of the analyzer. They provide various information about arguments, return values, and internal features of methods that can't be found out in the automatic mode. At the same time, the developer who annotates a method can assume its approximate internal structure and features of its operation, based on documentation and common sense. For example, calling the GetComponent method looks somewhat strange if the value it returned isn't used. A trifling bug? In no way. Of course, this may simply be a redundant call, forgotten and abandoned by everyone. Or it may be that some important assignment was omitted. Annotations can help the analyzer find similar and many other errors. Of course, we have already written a lot of annotations for the analyzer. For example, class methods from the System namespace are annotated. In addition, there is a mechanism to automatically
  • 2. annotate some methods. You can read here in detail about it. Note that this article tells more about the part of PVS-Studio that is responsible for analyzing projects in C++. However, there is no noticeable difference in the way annotations work for C# and C++. Writing annotations for Unity methods We strive to improve the quality of checking the code of projects that use Unity, which is why we decided to annotate methods of this engine. The initial idea was to cover all Unity methods with annotations, however there has been a lot of them. As a result, we decided to start by annotating methods from the most commonly used classes. Collecting information First, we had to find out which classes are used more often than others. In addition, an important aspect was to ensure that you can collect annotation results – new errors that the analyzer will find in real projects thanks to the written annotations. Therefore, the first step was to search for appropriate open source projects. However, this was not so easy to do. The problem is that many of the projects found were quite small in terms of the source code. If there are errors in such projects, their number is small. Not to mention the fact that it is less likely to find some warnings related to methods from Unity in them. Occasionally, some projects came up which almost haven't used (or haven't used at all) Unity-specific classes, although they were described as related to the engine in one way or another. Such finds were completely unsuitable for the task at hand. Of course, in some cases I was lucky. For example, the gem in this collection is MixedRealityToolkit. There is already quite a lot of code in it, which means that the collected statistics on the use of Unity methods in such a project will be more complete. Thus, there were 20 projects that use the engine's abilities. In order to find the most frequently used classes, a Roslyn based utility was written that counts method calls from Unity. This program, by the way, can also be called a static analyzer. After all, if you think about it, it really analyzes the source code, without running the project itself. The written "analyzer" allowed us to find classes whose average frequency of use in the found projects was the highest: • UnityEngine.Vector3 • UnityEngine.Mathf • UnityEngine.Debug • UnityEngine.GameObject • UnityEngine.Material • UnityEditor.EditorGUILayout • UnityEngine.Component • UnityEngine.Object • UnityEngine.GUILayout • UnityEngine.Quaternion • and others. Of course, this doesn't mean that these classes are actually used very often by developers – after all, statistics based on such a small set of projects aren't particularly trustworthy. However, to start
  • 3. with, this information was enough to make sure that the annotated methods' classes were used at least somewhere. Annotating After getting the necessary information, it's time to do the actual annotation. The documentation and the Unity editor, where the test project was created, were reliable helpers in this case. It was necessary to check some points that weren't specified in the documentation. For example, it was not always clear whether passing null as any argument would lead to an error, or whether the program would continue running without problems. Of course, passing null is usually not a good practice, but in this case, we only considered errors that interrupted the execution flow, or were logged by the Unity editor as an error. During these checks, interesting features of some methods were found. For example, running the code MeshRenderer renderer = cube.GetComponent<MeshRenderer>(); Material m = renderer.material; List<int> outNames = null; m.GetTexturePropertyNameIDs(outNames); makes the Unity editor itself crash, although usually in such cases, the current script execution is interrupted and the corresponding error is logged. Of course, it is unlikely that developers often write such things, but the fact that the Unity editor can be crashed by running regular scripts isn't nice. The same thing happens in at least one other case: MeshRenderer renderer = cube.GetComponent<MeshRenderer>(); Material m = renderer.material; string keyWord = null; bool isEnabled = m.IsKeywordEnabled(keyWord); These issues are relevant for the Unity 2019.3.10f1 editor. Collecting the results After the annotation is completed, you need to check how this will affect the warnings being issued. Before adding annotations, an error log is generated for each of the selected projects, which we call the reference log. Then the new annotations are embedded in the analyzer and the projects are checked again. The generated warning lists will differ from the reference ones due to annotations. The annotation testing procedure is performed automatically using the CSharpAnalyserTester program specifically written for these needs. It runs analysis on projects, then compares the resulting logs with the reference ones and generates files containing information about differences. The described approach is also used to find out what changes in logs appear when a new diagnostic is added or an existing one is changed. As noted earlier, it was difficult to find large open projects under Unity. This is unpleasant, as the analyzer would be able to produce more interesting warnings for them. At the same time, there would be much more differences between reference logs and logs generated after annotation. Nevertheless, the written annotations helped to identify several suspicious points in the projects under consideration, which is also a favorable result of the work. For example, a bit strange call of GetComponent was found:
  • 4. void OnEnable() { GameObject uiManager = GameObject.Find("UIRoot"); if (uiManager) { uiManager.GetComponent<UIManager>(); } } Analyzer warning: V3010 The return value of function 'GetComponent' is required to be utilized. - ADDITIONAL IN CURRENT UIEditorWindow.cs 22 Based on the documentation, it is logical to conclude that the value returned by this method should be used in some way. Therefore, it was marked accordingly when annotated. In this case, the result of the call isn't assigned to anything, which looks a bit strange. Here is another example of additional analyzer warnings: public void ChangeLocalID(int newID) { if (this.LocalPlayer == null) // <= { this.DebugReturn( DebugLevel.WARNING, string.Format( ...., this.LocalPlayer, this.CurrentRoom.Players == null, // <= newID ) ); } if (this.CurrentRoom == null) // <= { this.LocalPlayer.ChangeLocalID(newID); // <= this.LocalPlayer.RoomReference = null; } else { // remove old actorId from actor list this.CurrentRoom.RemovePlayer(this.LocalPlayer); // change to new actor/player ID this.LocalPlayer.ChangeLocalID(newID); // update the room's list with the new reference this.CurrentRoom.StorePlayer(this.LocalPlayer); } } Analyzer warnings: • V3095 The 'this.CurrentRoom' object was used before it was verified against null. Check lines: 1709, 1712. - ADDITIONAL IN CURRENT LoadBalancingClient.cs 1709 • V3125 The 'this.LocalPlayer' object was used after it was verified against null. Check lines: 1715, 1707. - ADDITIONAL IN CURRENT LoadBalancingClient.cs 1715
  • 5. Note that PVS-Studio doesn't pay attention to passing LocalPlayer to string.Format, since this won't cause an error. And the code looks like it was written intentionally. In this case, the impact of annotations isn't so obvious. However, they are the reason for these triggerings. So here comes the question - why were there no such warnings before? The fact is that the DebugReturn method makes several calls, which in theory could affect the value of the CurrentRoom property: public virtual void DebugReturn(DebugLevel level, string message) { #if !SUPPORTED_UNITY Debug.WriteLine(message); #else if (level == DebugLevel.ERROR) { Debug.LogError(message); } else if (level == DebugLevel.WARNING) { Debug.LogWarning(message); } else if (level == DebugLevel.INFO) { Debug.Log(message); } else if (level == DebugLevel.ALL) { Debug.Log(message); } #endif } The analyzer doesn't know how the called methods work, so it doesn't know how they will affect the situation. For example, PVS-Studio assumes that the value of this.CurrentRoom may have changed during the DebugReturn method, so the check is performed next. The annotations also provided the information that methods called inside DebugReturn won't affect the values of other variables. Therefore, using a variable before checking it for null can be considered suspicious. Conclusion To sum up, annotating Unity-specific methods will undoubtedly allow you to find more errors in projects that use this engine. However, annotating all available methods will take quite a long time. It is more efficient to annotate the most frequently used ones first. However, in order to understand which classes are used more often, you need suitable projects with a large code base. In addition, large projects allow much better control over the effectiveness of annotation. We will continue to do all this in the near future. The analyzer is constantly being developed and refined. Adding annotations to Unity methods is just one example of extending its abilities. Thus, over time, the efficiency of PVS-Studio increases. So if you haven't tried PVS-Studio yet, it's time to fix it by downloading it from the corresponding page.
  • 6. There you can also get a trial key for the analyzer to get acquainted with its abilities by checking various projects.