Showing posts with label dev. Show all posts
Showing posts with label dev. Show all posts

Wednesday, April 26, 2017

Videos about static code analysis





IT conferences and meetings on programming languages see a growing number of speakers talking about static code analysis. Although this field is quite specific, there is still a number of interesting discussions to be found here to help programmers understand the methods, ways of use, and specifics of static code analysis. In this article, we have collected a number of videos on static analysis whose easy style of presentation makes them useful and interesting to a wide audience of both skilled and novice programmers.

What is Static Analysis?

Picture 2

Author: Matt Might
Static analyzers allow programmers to bound and predict the behavior of software without running it. Once used exclusively for program optimization, they have rapidly risen in prominence for areas like software security and automatic parallelization. The author takes you on a tour of the landscape of static analysis through the lens of abstract interpretation.

Static code analysis used for code clean up

Picture 15
Author: PVS-Studio team
The report gives information about ways to detect bugs, methodology of static analysis, correct and incorrect use of analysis tools. The author also provides myths about static analysis that may lead to erroneous understanding among the developers. The presentation shows errors in Open Source projects, detected by such tools as ReSharper, PVS-Studio, Visual Studio SCA.

Static Code Analysis: Scan All Your Code For Bugs

Picture 12
Author: Jared DeMott
The author discusses static code analysis and how it is used in bug elimination. The talk covers a discussion of pattern matching, procedural, data flow, and statistical analysis, and also includes examples of common software vulnerabilities such as memory corruption, buffer overflow and over reads, script injection, XSS and CSRF, command injection, and misconfigurations.

Static Code Analysis: Preventing Bugs and Lag Before They Happen

Picture 6
Author: Vinny DaSilva
A Unit 16 Los Angeles forum session. The author discusses how to use static code analysis tools to improve code quality throughout the development process, how to customize static code analysis to fit teams' specific needs and workflows, and how to integrate with continuous integration systems to give developers continuous feedback.
Make more Secure Code! - Overview of Security Development Lifecycle and Static Code Analysis
Picture 13
Author: Jason Cohen
Despite the exponential growth in security products, security services, security companies, security certifications, and general interest in the security topic, we still see security vulnerability disclosures happening on a regular basis. Implementing Security Development Lifecycle best practices and principles can go a long way to reducing the potential for common security flaws. Input sanitization issues, Cross-Site-Scripting, buffer overflows, and many other known issues still represent the bulk of security issues present. Static Code Analysis can help catch many of these unnoticed issues before code makes it out of the developer's hands. In this video, the author discusses some common best practices of the Security Development Lifecycle theory and how this can be integrated into modern code.

Bug Hunting with Static Code Analysis

Picture 27
Author: Nick Jones
A BSlidesLondon 2016 conference video. This talk covers a number of automated analysis techniques for spotting bugs and security flaws in applications at the source code level, ranging from quick and dirty bash scripts through open source and commercial analyzers to custom implementations. The video also discusses how these techniques can be used in continuous integration systems to catch bugs as early in the development cycle as possible.

The Current State of (free) Static Analysis

Picture 4
Author: Jason Turner
A CPPCON2015 conference video. The author discusses the currently available free static analysis software available for C++ and explains what kinds of errors these tools can catch, what kinds they miss, and why static analysis should be a part of a normal build process.

Static Analysis and C++: More Than Lint

Picture 14
Author: Neil MacIntosh
A CPPCON2015 conference video. Static analysis can find not only trivial bugs but also subtle, complex bugs early, identify opportunities to improve performance, encourage consistent style and appropriate usage of libraries and APIs. This talk looks at the different purposes static analysis tools can be used to meet all these different goals. Specific examples are presented from the author's experience working with sophisticated analysis tools on large, commercial codebases.

Make Friends with the Clang Static Analysis Tools

Picture 5
Author: Gabor Horvath
A CPPCON2016 conference video. This talk is an overview of the open source static analysis tools for C++ with the emphasis on Clang based tools. Understanding these methods can be really useful as it helps write more static analysis friendly code and understand the cause of false positive results. It also helps to understand limitations of the currently available tools. The author gives a short tutorial on how to use these tools and how to integrate them into the workflow.

Finding Bugs with Clang at Compile and Run Time

Picture 22
Author: Bernhard Merkle
An ACCU 2016 conference video. Code analysis and verification gain more and more importance within programming and quality assurance of software projects. Especially in languages like C/C++, undefined behavior and memory leaks can cause great problems. Static analysis tools help a lot but often hard to detect problems happen at runtime. This session shows how to use clang's features to find bugs at both compile time (via static analysis) and runtime (via sanitizers). The combination of both approaches can improve software quality a lot.

Static Source Code Analysis, The Next Generation

Picture 26
Author: James Croall
A Devoxx 2016 conference video. Gone are the days of "linters" and glorified spell checkers. Today's static source code analysis is accurate and trustworthy, and can find complex inter-procedural coding defects that our human eyes would never see. The video discusses how open-source developers have used Coverity's Software Testing Platform to find and fix critical, crash causing bugs and security defects in the Java language.

Static Analysis Saved My Code Tonight

Picture 8
Author: Damien Seguy
A PHP UK Conference 2017 video. Static analysis tools check PHP code without running it. Fully automated, they bring expertise to review the code, enforce good practices when programming, keep code ready for the next PHP version. PHP 7 has developed tremendously our capacity to audit code -thanks to AST and return types, it is possible to go deeper and prevent more bugs. In this video, the author reviews the current state of static analysis tools and shows what they can find and how to integrate them in the development cycle.

Static Code Analysis with Python

Picture 28
Author: Andrew Wolfe
Auditing a code base for code formatting mistakes, potential security vulnerabilities or defects can be time consuming. Static code analysis will let the computer do that for you. The video discusses how to use code static analysis to catch errors early and improve code quality in Python codebases.

Augmenting Static Analysis Using Pintool: Ablation

Picture 17
Author: Paul Mehta
A BH USA 2016 conference video. Ablation is a tool supplementing static analysis built to extract information from a process as it executes. This information is then imported into the disassembly environment where it used to resolve virtual calls, highlight regions of code executed, or visually diff samples. The goal of Ablation is to augment static analysis with minimal overhead or user interaction. Ablation makes it simple to diff samples by and highlight where the samples diverge. This is achieved by comparing the code executed rather than just comparing data. The video also compares a heavily mutated crash sample and the source sample.

Conclusion

You may find that some of the videos cover the same aspects, but each codebase is unique and one developer's experience may be different from that of another. The authors share their knowledge of the static analysis methodology and experience of using static analysis tools with the audience to prevent them from making the same mistakes, straining their nerves and wasting their time on finding and fixing these mistakes. The static analysis field is intensively developing; some diagnostic rules inevitably become obsolete, whereas new diagnostics and standards appear. That's why attempts to compare analyzers based on what defects they can detect or running them on synthetic tests make no sense. The only way to compare tools is to run them on your code and see which of them meets your needs and expectations the most.

Friday, March 10, 2017

Top 10 bugs in C++ open source projects, checked in 2016

While the world is discussing the 89th Ceremony of Oscar award and charts of actors and costumes, we've decided to write a review article about the IT-sphere. The article is going to cover the most interesting bugs, made in open source projects in 2016. This year was remarkable for our tool, as PVS-Studio has become available on Linux OS. The errors we present are hopefully, already fixed, but every reader can see how serious are the errors made by developers.

Picture 6
So, let's see, which bugs PVS-Studio analyzer managed to find in 2016. Besides the code fragment, we provide a diagnostic, which helped to detect the error and the article, where this error was first described.
The sections are sorted according to my idea of the error beauty.

Tenth place

V519 The 'bb_copy' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1076, 1078. cfg.c 1078
void
free_original_copy_tables (void)
{
  gcc_assert (original_copy_bb_pool);
  delete bb_copy;
  bb_copy = NULL;       // <=
  delete bb_original;   // <=
  bb_copy = NULL;       // <=
  delete loop_copy;
  loop_copy = NULL;
  delete original_copy_bb_pool;
  original_copy_bb_pool = NULL;
}
The pointer bb_copy is set to nil twice, and the pointer bb_original remains the same.

Ninth place

V519 The 'BlendFactor[2]' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 1265, 1266. ccrydxgldevicecontext.cpp 1266
void CCryDXGLDeviceContext::
OMGetBlendState(...., FLOAT BlendFactor[4], ....)
{
  CCryDXGLBlendState::ToInterface(ppBlendState, m_spBlendState);
  if ((*ppBlendState) != NULL)
    (*ppBlendState)->AddRef();
  BlendFactor[0] = m_auBlendFactor[0];
  BlendFactor[1] = m_auBlendFactor[1];
  BlendFactor[2] = m_auBlendFactor[2]; // <=
  BlendFactor[2] = m_auBlendFactor[3]; // <=
  *pSampleMask = m_uSampleMask;
}
A nasty typo that was quickly fixed after the article was posted. By the way, this erroneous code was copied several times to different fragments of the project. The analyzer found them too.

Eighth place

V579 The read_memory function receives the pointer and its size as arguments. It is possibly a mistake. Inspect the third argument. jv-valprint.c 111
extern void
read_memory (CORE_ADDR memaddr, gdb_byte *myaddr, ssize_t len);

void
java_value_print (....)
{
  ....
  gdb_byte *buf;
  buf = ((gdb_byte *)
    alloca (gdbarch_ptr_bit (gdbarch) / HOST_CHAR_BIT));
  ....
  read_memory (address, buf, sizeof (buf));
  ....
}
The sizeof(buf) operator evaluates not the buffer size, but the pointer size. Therefore, the program doesn't get enough bytes of data.

Seventh place

V522 Dereferencing of the null pointer 've' might take place. functions1d.cpp 107
int QuantitativeInvisibilityF1D::operator()(....)
{
  ViewEdge *ve = dynamic_cast<ViewEdge*>(&inter);
  if (ve) {
    result = ve->qi();
    return 0;
  }
  FEdge *fe = dynamic_cast<FEdge*>(&inter);
  if (fe) {
    result = ve->qi(); // <=
    return 0;
  }
  ....
}
The typo in the names had consequences that are more serious. Apparently, the second code fragment was written using Copy-Paste. By accident, the programmer forgot to change the variable name ve with fe. As a result, we will have an undefined behavior, which may lead to a crash, for example.

Sixth place

V546 Member of a class is initialized by itself: 'm_subId(m_subId)'. tfarmcontroller.cpp 572
class TaskId
{
  int m_id;
  int m_subId;

public:
  TaskId(int id, int subId = -1) : m_id(id), m_subId(m_subId){};
An interesting bug in the list of class initialization. The field m_subld is initialized by itself; perhaps the programmer wanted to write m_subId(subId).

Fifth place

V603 The object was created but it is not being used. If you wish to call constructor, 'this->G4PhysicsModelCatalog::G4PhysicsModelCatalog(....)' should be used. g4physicsmodelcatalog.cc 51
class G4PhysicsModelCatalog
{
  private:  
  ....
    G4PhysicsModelCatalog();
  ....
  static modelCatalog* catalog;
  ....
};

G4PhysicsModelCatalog::G4PhysicsModelCatalog()
{ if(!catalog) { 
    static modelCatalog catal;
    catalog = &catal; 
  } 
}

G4int G4PhysicsModelCatalog::Register(const G4String& name)
{
  G4PhysicsModelCatalog();
  .... 
}
It is a rare bug, but some programmers still think that such a call of a constructor initializes the fields of a class. Instead of accessing the current object, a new temporary object is created and then immediately destroyed. As a result, the fields of the object will not be initialized. If you need to use field initialization outside the constructor, it is better to create a separate function and access it.

Fourth place

V554 Incorrect use of shared_ptr. The memory allocated with 'new []' will be cleaned using 'delete'. BlackJack_Server140 table.cpp 471
void DealerTable::FillShoe(size_t decks)
{
  std::shared_ptr<int> ss(new int[decks * 52]);
  ....
}
By default, the smart pointer of the shared_ptr type for destruction of an object will call the delete operator without the brackets []. In this case, it is wrong.
The correct code should be:
std::shared_ptr<int> ss(new int[decks * 52],
                        std::default_delete<int[]>());

Third place

V541 It is dangerous to print the string 'achrDefaultScript' into itself. dlgcreateanimatedtexture.cpp 359
BOOL CDlgCreateAnimatedTexture::OnInitDialog() 
{
  ....
  // allocate 16k for script
  char achrDefaultScript[ 16384];
  // default script into edit control
  sprintf( achrDefaultScript, ....); // <=
  ....
  // add finishing part of script
  sprintf( achrDefaultScript,        // <=
           "%sANIM_END\r\nEND\r\n",  // <=
           achrDefaultScript);       // <=
  ....
}
Some string is formed in the buffer, and then the programmer wants to get a new string, saving the previous string value and add two more words. It seems really simple.
To explain why unexpected result can be received here, I will quote a simple and clear example from the documentation for the diagnostic V541:
char s[100] = "test";
sprintf(s, "N = %d, S = %s", 123, s);
As a result we would want to have a string:
N = 123, S = test
But in practice, we will have such a string in the buffer:
N = 123, S = N = 123, S =
It is hard to say what will happen in our case, because it depends on the implementation of the sprintf function. There is a chance that the code will work in the way it is expected. But we may also get an incorrect variant or a program crash. The code can be fixed if you use a new buffer to store the result .

Second place

V733 It is possible that macro expansion resulted in incorrect evaluation order. Check expression: chan - 1 * 20. isp.c 2301
static void
isp_fibre_init_2400(ispsoftc_t *isp)
....
  if (ISP_CAP_VP0(isp))
    off += ICB2400_VPINFO_PORT_OFF(chan);
  else
    off += ICB2400_VPINFO_PORT_OFF(chan - 1); // <=
  ....
}
At first glance, there is nothing strange in this code fragment. We see that sometimes the 'chan' value is used, sometimes less by one 'chan - 1', but let us have look at the macro definition:
#define ICB2400_VPOPT_WRITE_SIZE 20

#define  ICB2400_VPINFO_PORT_OFF(chan) \
  (ICB2400_VPINFO_OFF +                \
   sizeof (isp_icb_2400_vpinfo_t) +    \
  (chan * ICB2400_VPOPT_WRITE_SIZE))          // <=
When passing the binary expression to the macro, the evaluation logic changes dramatically. The expression "(chan - 1) * 20" turns into "chan - 1 *20", i.e. into "chan - 20", and the incorrectly evaluated size gets used further in the program.
Unfortunately, this error has not been fixed yet. Perhaps, the developers did not notice it in the article or have not fixed yet, but the code still looks strange. That is why FreeBSD took the second award.

First place

V547 Expression is always false. Unsigned type value is never < 0. dt_subr.c 715
#define vsnprintf RTStrPrintfV

int
dt_printf(dtrace_hdl_t *dtp, FILE *fp, const char *format, ...)
{
  ....
  if (vsnprintf(&dtp->dt_buffered_buf[dtp->dt_buffered_offs], // <=
        avail, format, ap) < 0) {
      rval = dt_set_errno(dtp, errno);
      va_end(ap);
      return (rval);
    }
  ....
}
The first place of this rating of 2016 is taken by VirtualBox project. It was checked by PVS-Studio several times and each time we detected a large number of errors. However, this error was so confusing that it misled not only the author of the code but even us, the developers of the analyzer. We really had to think a lot what was wrong with the code and why PVS-Studio issued such a strange warning.
In the compiled code in Windows we saw the replacement of functions. A new function returned a value of unsigned type, adding almost an invisible error. Here are the prototypes of the functions:
size_t  RTStrPrintfV(char *, size_t, const char *, va_list args);
int     vsnprintf   (char *, size_t, const char *, va_list arg );

Conclusion

In conclusion, I wanted to show the most popular picture that got a lot of enthusiastic comments. A picture from the article "PVS-Studio checked OpenJDK"
Picture 3
Now anybody can offer projects for a check via Github on Windows and Linux, which will help us find more errors in open source projects and improve the quality of these projects.
You may download and try PVS-Studio by this link.
In case you want to discuss the licensing options, prices and discounts, contact us at the support.

We wish you bugless coding!

Thursday, February 16, 2017

Porting is a Delicate Matter: Checking Far Manager under Linux

Far Manager, which takes over from Norton Commander, created back in the times of DOS, is one of the most popular file managers on Microsoft Windows. Far Manager facilitates the file system management (file creation, editing, viewing, copying, moving, search, and deletion) and provides means to extend the standard feature set (handling of the network, archives, backup copies, and so on). Far Manager was recently ported to Linux, and there is currently an alpha version available. The PVS-Studio team couldn't ignore that event and miss the opportunity to test the quality of the ported code.
Picture 24

About Far Manager

Far Manager is a console keyboard-oriented file manager for operating systems of the Microsoft Windows family. The project inherits the two-panel layout, the standard (default) color scheme, and the set of keyboard shortcuts from a popular file manager Norton Commander and provides a convenient user interface for handling files and directories (creating, viewing, editing, copying, renaming, deleting, and so on).

Figure 1 - Far Manager 2 on Windows (click to enlarge)
Figure 1 - Far Manager 2 on Windows (click to enlarge)
Far Manager was created by Eugene Roshal. The first version was released on September 10, 1996. The last version (1.65) in whose development Roshal took part is dated June 23, 2000. After that, the Far Group in fact took over the project. It's not until March 29, 2006, that the next version, v1.70, was released. On December 13, 2008, version 2.0 was released and the program became open source. It has been distributed under the revised BSD license ever since. Far Manager versions 1.70 through 2.0 look almost the same, so users can move to newer versions without having to adapt from scratch. Unicode support was added in version 1.80. The latest release, v3.0, is dated November 4, 2016.
On August 10, 2016, the development group released the first test build of the Linux port, Far2l. This build currently features a built-in usable terminal and plugins Align, AutoWrap, Colorer, DrawLine, Editcase, FarFTP, FarLng, MultiArc, NetBox, SimpleIndent, TmpPanel. The source code is distributed under the GPLv2 license.
Figure 2 - Far Manager 2 on Linux (click to enlarge)
Figure 2 - Far Manager 2 on Linux (click to enlarge)

Enough talking

The analyzer output a total of 1038 General Analysis warnings for Far2l project. The chart below shows how the warnings are distributed across the severity levels:
Figure 1 - Warning distribution across the severity levels
Figure 1 - Warning distribution across the severity levels
Let me comment on this diagram briefly. The analyzer output 153 High-level, 336 Medium-level, and 549 Low-level warnings.
This number is relatively large, but we should keep in mind that not each warning is a real bug. Having studied High- and Medium-level messages, I found 250 cases that were very likely to be errors.
For the High and Medium levels, the rate of false positives is about 49%. In other words, every second warning points to a real defect in the code.
Now let's estimate the relative error density. The total number of source lines of code (SLOC) of this project is 538,675. Therefore, the error density is 0.464 errors per 1000 SLOC. One day, I believe, we will gather all these statistical data together and write a summary article about the code quality of different projects.
It should be noted that the error density parameter we have calculated does not reflect the general error density across the whole project: it may be both greater (if the analyzer failed to notice a real bug) and less (if the analyzer reported correct code as faulty). Other projects usually show higher error density, so you can call it a successful port from the code quality viewpoint. However, we strongly recommend that the authors fix the errors found by the analyzer, as they are far from harmless.

Analysis results

One thing you should know before reading on is that the examples discussed below were refactored to make them easier to read. Remember also that these are just the most interesting examples out of all the numerous errors found by PVS-Studio in this project.

Copy-Paste

Picture 28
PVS-Studio diagnostic message: V501 There are identical sub-expressions 'Key == MCODE_F_BM_GET' to the left and to the right of the '||' operator. macro.cpp 4819
int KeyMacro::GetKey()
{
  ....
  DWORD Key = !MR ? MCODE_OP_EXIT : GetOpCode(MR, Work.ExecLIBPos++);
  ....
  switch (Key)
  {
  ....
  case MCODE_F_BM_POP:
  {
    TVar p1, p2;

    if (Key == MCODE_F_BM_GET)
      VMStack.Pop(p2);

    if (   Key == MCODE_F_BM_GET    // <=
        || Key == MCODE_F_BM_DEL 
        || Key == MCODE_F_BM_GET    // <=
        || Key == MCODE_F_BM_GOTO)
    {
      VMStack.Pop(p1);
    }
    ....
  }
  }
}
The Key variable is compared with the MCODE_F_BM_GET constant twice. This must be a typo and the programmer actually intended to compare Key with some other constant. The analyzer found 3 more issues of this kind:
  • V501 There are identical sub-expressions '!StrCmpN(CurStr, L"!/", 2)' to the left and to the right of the '||' operator. fnparce.cpp 291
  • V501 There are identical sub-expressions '!StrCmpN(CurStr, L"!=/", 3)' to the left and to the right of the '||' operator. fnparce.cpp 291
  • V501 There are identical sub-expressions 'KEY_RCTRL' to the left and to the right of the '|' operator. keyboard.cpp 1830
PVS-Studio diagnostic message: V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 267, 268. APIStringMap.cpp 268
static BOOL WINPORT(GetStringType)( DWORD type,
                                    LPCWSTR src,
                                    INT count,
                                    LPWORD chartype )
{
  ....
  while (count--)
  {
    int c = *src;
    WORD type1, type3 = 0; /* C3_NOTAPPLICABLE */
    ....
    if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_FULLWIDTH; // <=
    if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_SYMBOL;    // <=
    ....
  }
  ....
}
The second condition looks like it was written using Copy-Paste and is identical to the first one. However, if this is a conscious decision, the code can be simplified by removing the second condition:
....
if ((c>=0xFFE0)&&(c<=0xFFE6)) type3 |= C3_FULLWIDTH | C3_SYMBOL; 
....
It was not the only error of this type:
  • V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 272, 273. APIStringMap.cpp 273
  • V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 274, 275. APIStringMap.cpp 275
  • V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 6498, 6503. macro.cpp 6503
  • V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 1800, 1810. vmenu.cpp 1810
  • V581 The conditional expressions of the 'if' operators situated alongside each other are identical. Check lines: 3353, 3355. wrap.cpp:3355
PVS-Studio diagnostic message: V523 The 'then' statement is equivalent to the 'else' statement. Queque.cpp 358
void FTP::AddToQueque(FAR_FIND_DATA* FileName, 
                      LPCSTR Path, 
                      BOOL Download)
{
  ....
  char *m;
  ....
  if(Download)
    m = strrchr(FileName->cFileName, '/'); // <=
  else
    m = strrchr(FileName->cFileName, '/'); // <=
  ....
}
The second condition in this example must have been also written with the help of "Copy-Paste": whatever the value of Download (TRUE, FALSE), the 'm' pointer will be assigned the position of the last occurrence of the '/' character.

Undefined behavior

Picture 37
PVS-Studio diagnostic message: V567 Undefined behavior. The 'Item[FocusPos]->Selected' variable is modified while being used twice between sequence points. dialog.cpp 3827
int Dialog::Do_ProcessSpace()
{
  ....
  if (Item[FocusPos]->Flags & DIF_3STATE)
    (++Item[FocusPos]->Selected) %= 3;       // <=
  else
    Item[FocusPos]->Selected = !Item[FocusPos]->Selected;
  ....
}
We are obviously dealing with undefined behavior here: the Item[FocusPos]->Selected variable is modified twice in one sequence point (an increment and dividing of modulo 3 followed by an assignment).
There was one more fragment with similar undefined behavior:
  • V567 Undefined behavior. The '::ViewerID' variable is modified while being used twice between sequence points. viewer.cpp 117
PVS-Studio diagnostic message: V610 Undefined behavior. Check the shift operator '<<'. The right operand 'sizeof (wchar_t) * 8' is greater than or equal to the length in bits of the promoted left operand. RegExp.cpp 4467
#define rechar wchar_t
#define RE_CHAR_COUNT (1 << sizeof(rechar) * 8)

int RegExp::Optimize()
{
  ....
  for (op=code; ; op=op->next)
  {
    switch (OP.op)
    {
    ....
    case opType:
    {
      for (int i = 0; i < RE_CHAR_COUNT; i++)    // <=
      {
        if (ISTYPE(i, OP.type))
        {
          first[i]=1;
        }
      }
      
      break;
    }
    }
    ....
  }
  ....
}
The error has to do with the fact that the type wchar_t is 4 bytes long on Linux, so signed int (4 bytes) is shifted by 32 bits to the left. As specified by the C++11 standard, when the left operand has a signed type and a positive value, a left-shift by N bytes causes undefined behavior, if N is greater than or equal to the length in bits of the left operand. This is what the fixed version of the code should look like:
#define rechar wchar_t
#define RE_CHAR_COUNT (static_cast<int64_t>(1) << sizeof(rechar) * 8)

int RegExp::Optimize()
{
  ....
  for (int64_t i = 0; i < RE_CHAR_COUNT; i++)
  {
    ....
  }
  ....
}
The analyzer found a few more defects leading to undefined behavior related to the left-shift:
  • V610 Undefined behavior. Check the shift operator '<<'. The right operand 'sizeof (wchar_t) * 8' is greater than or equal to the length in bits of the promoted left operand. RegExp.cpp 4473
  • V610 Undefined behavior. Check the shift operator '<<'. The right operand 'sizeof (wchar_t) * 8' is greater than or equal to the length in bits of the promoted left operand. RegExp.cpp 4490
  • V610 Undefined behavior. Check the shift operator '<<'. The right operand 'sizeof (wchar_t) * 8' is greater than or equal to the length in bits of the promoted left operand. RegExp.cpp 4537
  • V610 Undefined behavior. Check the shift operator '<<'. The right operand 'sizeof (wchar_t) * 8' is greater than or equal to the length in bits of the promoted left operand. RegExp.cpp 4549
  • V610 Undefined behavior. Check the shift operator '<<'. The right operand 'sizeof (wchar_t) * 8' is greater than or equal to the length in bits of the promoted left operand. RegExp.cpp 4561

Incorrect memory handling

Picture 41
Let's start the new section with a little warm-up. Try to spot the bug in the code below by yourself (Hint: it's in the TreeItem::SetTitle function).
class UnicodeString
{
  ....
  UnicodeString(const wchar_t *lpwszData) 
  { 
    SetEUS(); 
    Copy(lpwszData); 
  }
  ....
  const wchar_t *CPtr() const { return m_pData->GetData(); }
  operator const wchar_t *() const { return m_pData->GetData(); }
  ....
}

typedef UnicodeString FARString;

struct TreeItem
{
  FARString strName;
  ....
}

TreeItem **ListData;
void TreeList::SetTitle()
{
  ....
  if (GetFocus())
  {
    FARString strTitleDir(L"{");
    const wchar_t *Ptr = ListData 
                         ? ListData[CurFile]->strName
                         : L""; 
    ....
  }
  ....
}
PVS-Studio diagnostic message: V623 Consider inspecting the '?:' operator. A temporary object of the 'UnicodeString' type is being created and subsequently destroyed. Check third operand. treelist.cpp 2093
Pretty subtle, isn't it? In this example, the ListData[CurFile]->strName variable is an instance of class UnicodeString, which contains an overloaded implicit conversion operator to type const wchar_t*. Now pay attention to the ternary operator in the function TreeList::SetTitle: the second and third operands have different types (UnicodeString and const char [1], respectively). The idea was that if the first operand returns false, then the pointer Ptr will be pointing to an empty string. Since the constructor UnicodeString is not declared as an explicit, in fact, the third operand is chosen as a temporary object, (which, in its turn, will be cast to type const wchar_t*). Further, the temporary object is destroyed and Ptr will point to invalid data. This is what the fixed code looks like:
....
const wchar_t *Ptr = ListData 
                     ? ListData[CurFile]->strName.CPtr()
                     : L"";
....
An interesting thing about the next example is that it triggered two diagnostics at once.
PVS-Studio diagnostic messages:
  • V779 Unreachable code detected. It is possible that an error is present. 7z.cpp 203
  • V773 The function was exited without releasing the 't' pointer. A memory leak is possible. 7z.cpp 202
BOOL WINAPI _export SEVENZ_OpenArchive(const char *Name,
                                       int *Type)
{
  Traverser *t = new Traverser(Name);
  if (!t->Valid()) 
  {
    return FALSE;
    delete t;
  }
  
  delete s_selected_traverser;
  s_selected_traverser = t;
  return TRUE;
}
Well, what do we have here? Firstly, there is, indeed, unreachable code in the if statement's body: if the condition is true, the function exits, returning FALSE. Secondly, that unreachable code simply caused a memory leak: the object pointed to by the t pointer is not deleted. To fix these errors, the two statements within the if block need to be swapped.
The next example demonstrates how you can make a mistake when evaluating the size of an object of a class (struct) using a pointer.
PVS-Studio diagnostic messages:
  • V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'PInfo' class object. filelist.cpp 672
  • V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'PInfo' class object. filelist.cpp 673
int64_t FileList::VMProcess(int OpCode,
                            void *vParam,
                            int64_t iParam)
{
  switch (OpCode)
  {
  ....
  case MCODE_V_PPANEL_PREFIX:           // PPanel.Prefix
  {
    PluginInfo *PInfo = (PluginInfo *)vParam;
    memset(PInfo, 0, sizeof(PInfo));          // <=
    PInfo->StructSize = sizeof(PInfo);        // <=
    ....
  }
  ....
  }
}
Both errors have to do with the function sizeof(PInfo) returning the pointer size (4 or 8 bytes) instead of the expected structure size. Therefore, memset will fill with zeros only the first 4 (8) bytes of the structure, and the PInfo->StructSize field will be assigned the pointer size. Here's the fixed version:
....
PluginInfo *PInfo = (PluginInfo*)vParam;
memset(PInfo, 0, sizeof(*PInfo));
PInfo->StructSize = sizeof(*PInfo);
....
The analyzer found two more defects of this type:
  • V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'HistoryItem' class object. history.cpp 594
  • V568 It's odd that 'sizeof()' operator evaluates the size of a pointer to a class, but not the size of the 'handle' class object. plugins.cpp 682

Strange conditions

Picture 39
Another warm-up. Try to find the bug in the code below:
int FTP::ProcessKey(int Key, unsigned int ControlState)
{
  ....
  if(   !ShowHosts 
     && (ControlState == 0 || ControlState == PKF_SHIFT) 
     && Key == VK_F6)
  {
    FTP *ftp = OtherPlugin(this);
    int  rc;

    if(   !ftp 
       && ControlState == 0 
       && Key == VK_F6)
    {
      return FALSE;
    }
    ....
  }
  ....
}
PVS-Studio diagnostic message: V560 A part of conditional expression is always true: Key == 0x75. Key.cpp 493
Note the external and internal conditions: the Key variable is compared with the constant VK_F6. If the execution reaches the internal condition, Key is guaranteed to be equal to VK_F6, making the second check redundant. The improved code will look as follows:
....
if(   !ftp 
   && ControlState == 0)
{
  return FALSE;
}
....
This diagnostic found a few more defects like that:
  • V560 A part of conditional expression is always true: !cps. DString.cpp 47
  • V560 A part of conditional expression is always true: !ShowHosts. FGet.cpp 139
  • V560 A part of conditional expression is always false: !wsz. cnDownload.cpp 190
  • V560 A part of conditional expression is always true: !UserReject. extract.cpp 485
  • And 8 additional diagnostic messages.
PVS-Studio diagnostic message: V503 This is a nonsensical comparison: pointer <= 0. fstd_exSCPY.cpp 8
char *WINAPI StrCpy(char *dest, LPCSTR src, int dest_sz)
{
  if(dest <= 0)   // <=
    return NULL;
  ....
}
This code contains a meaningless comparison of a pointer with a negative value (pointers don't work with memory areas that have negative addresses). This is what the fixed version could look like:
....
if(dest == nullptr)
  return NULL;
....
PVS-Studio diagnostic message: V584 The 'FADC_ALLDISKS' value is present on both sides of the '==' operator. The expression is incorrect or it can be simplified. findfile.cpp 3116
enum FINDASKDLGCOMBO
{
  FADC_ALLDISKS,
  FADC_ALLBUTNET,
  ....
};

FindFiles::FindFiles()
{
  
  ....
  if (   FADC_ALLDISKS + SearchMode == FADC_ALLDISKS     // <=
      || FADC_ALLDISKS + SearchMode == FADC_ALLBUTNET)
  {
    ....
  }
  ....
}
The analyzer detected a strange condition in the first part of a compound conditional expression. Based on the FINDASKDLGCOMBO enumeration, the FADC_ALLDISKS constant has the value 0 and FADC_ALLBUTNET has the value 1. If we use the numerical values in the conditional expression, we'll get the following:
if (   0 + SearchMode == 0
    || 0 + SearchMode == 1)
{
  ....
}
Judging by this code, the whole condition can be simplified:
if (   SearchMode == FADC_ALLDISKS
    || SearchMode == FADC_ALLBUTNET)
{
  ....
}

Incorrect format string handling

Picture 40
PVS-Studio diagnostic message: V576 Incorrect format. Consider checking the fourth actual argument of the 'swprintf' function. The char type argument is expected. FarEditor.cpp 827
void FarEditor::showOutliner(Outliner *outliner)
{
  ....
  wchar_t cls = 
    Character::toLowerCase((*region)[region->indexOf(':') + 1]);
  
  si += swprintf(menuItem+si, 255-si, L"%c ", cls); // <=
  ....
}
This might be a porting error. It has to do with the fact that in Visual C++, the format-string specifiers in the functions printing wide strings are interpreted in a non-standard way: the %c specifier is expecting a wide character (wide char, wchar_t), while on Linux, as specified by the standard, %c is expecting a multibyte character (multibyte symbol, char). The fixed code should look as follows:
si += swprintf(menuItem+si, 255-si, L"%lc ", cls);
 
PVS-Studio diagnostic message: V576 Incorrect format. Consider checking the fourth actual argument of the 'swprintf' function. The pointer to string of char type symbols is expected. cmddata.cpp 257
void CommandData::ReadConfig()
{
  ....
  wchar Cmd[16];
  ....
  wchar SwName[16+ASIZE(Cmd)];
  swprintf(SwName,ASIZE(SwName), L"switches_%s=",Cmd);  // <=
  ....
}
This case is similar to the previous one: the format string contains specifier %s, so a multibyte string (char*) is expected. However, what it receives is a wide string (wchar_t*). This is the fixed code:
swprintf(SwName,ASIZE(SwName), L"switches_%ls=",Cmd);
The analyzer also reported two other instances with incorrectly passed format-string parameters:
  • V576 Incorrect format. Consider checking the third actual argument of the 'fprintf' function. The char type argument is expected. vtansi.cpp 1033
  • V576 Incorrect format. Consider checking the third actual argument of the 'fprintf' function. The char type argument is expected. vtansi.cpp 1038

Conclusion

What conclusions can we draw about the Linux port of Far Manager? True, there are many defects, but it's just an alpha version after all, and the project is still developing. Static code analysis can help you find bugs at the earliest development stage and prevent them from making it to the repository, but to fully feel its advantages, you should run it regularly (or at least during night builds).
I offer you all to try PVS-Studio and evaluate its usefulness for yourself: the analyzer can run on Microsoft Windows and supports deb/rpm-based Linux distributions, allowing you to scan projects quickly and on a regular basis. What's more, if you are a student, an individual developer, or a developer of open-source, non-commercial software, you can use PVS-Studio for free.

In this video tutorial you may see how install PVS-Studio for Linux and check your project (using Far Manager as an example). If you know an interesting project worth checking, you may suggest it on GitHub. Here are more details about that: "Propose a project for analysis by PVS-Studio: now on GitHub".