Let's check Scilab
DEV Community

Let's check Scilab

What powerful tools do you know for complex mathematical computations? One example is the open-source project Scilab. We analyzed its source code to see what errors we could uncover. In this article, we'll show how static analysis can help detect them.

What's our topic today?

Scilab is an open-source, cross-platform project designed for scientific and engineering computing. It's widely used in manufacturing, automotive engineering, medicine, and other fields for solving complex mathematical problems.

The project's wide range of uses requires the highest standards for the quality and reliability of its code. We used PVS-Studio static analyzer to check the Scilab source code. In this article, we highlighted the most interesting errors we found. Our goal is to show developers how static analysis can help make the projects even better.

A few words about PVS-Studio. PVS-Studio is a static analyzer that has been helping developers detect errors in C, C++, C#, Java, Go, JavaScript, and TypeScript code for over 18 years. We also provide excellent technical support.

Static analysis is a step in the development process that complements other quality assurance methods, such as testing and code reviews. It helps developers detect bugs and potential vulnerabilities early in the development process. This enables teams to devote more time to implementing new features and less time to fixing code issues.

This article doesn't cover all the issues we detected. Instead, we've chosen the examples we found most intriguing. Try PVS-Studio for free to view the full report or check your own project.

Note. We checked the project at the time of the 30a3695a commit using PVS-Studio 8.00.

Errors Handling pointers

Snippet 1

The PVS-Studio warning:

V611 [CWE-762, CERT-MEM51-CPP, SEC-MEMORY] The memory was allocated using the 'operator new' but was released using the 'operator delete[]'. The 'delete ptr;' statement should be used instead. fromws_c.cpp 335

SCICOS_BLOCKS_IMPEXP void fromws_c(scicos_block* block, int flag)
{
  // ....
  fromwork_struct** work = (fromwork_struct* ) block->work;
  fromwork_struct ptr = nullptr;
  // ....
  *work = new fromwork_struct(); // <=
  ptr = *work; // <=
  // ....
  if (ptr_T[j] > ptr_T[j + 1])
  {
    Coserror(_("The time vector should be an increasing vector.\n"));
    *work = nullptr;
    delete[] ptr->workt;
    FREE(ptr->work);
    delete[] ptr; // <=
    return;
  }
  // ....
}

The issue is clear: the developers used an incorrect deallocation method. Memory for the element that ptr points to is allocated using new and deallocated using delete[].

What potential issues could arise from this? According to the C++ standard, if we allocate memory for a single object but free it using delete[], the program's behavior is undefined. In reality, delete[] expects metadata before the memory block that stores the number of elements allocated by new T[N]. If the metadata isn't there, the operator may read garbage. As a result, it may call the wrong number of destructors or attempt to free an incorrect address.

If you still believe that undefined behavior is just a myth, this article might change your mind.

To fix the code, we need to remove [] when clearing the ptr pointer:

delete ptr;

Snippet 2

The PVS-Studio warning:

V595 [CWE-476, CERT-EXP12-C, SEC-NULL] The 'values' pointer was utilized before it was verified against nullptr. Check lines: 465, 466. sundials_hashmap.c 465

SUNErrCode SUNHashMap_Values (SUNHashMap map, void*** values, int64_t value_size)
{
  int count = 0;
  if (!map)
  {
    return SUN_ERR_ARG_CORRUPT;
  }
  values = (void *)malloc(SUNHashMap_Capacity(map) * value_size);
  if (!values)
  {
    return SUN_ERR_MALLOC_FAIL;
  }
  // ....
}

Manual memory management can lead to various errors. Here, the values pointer is passed as a function parameter. We dereference it and check for NULL on the next line. If the pointer is null, dereferencing it will result in undefined behavior; so, the check below is meaningless.

In reality, the compiler can simply remove the entire if (!values) block. It sees that the pointer is already in use, so it assumes it's valid and that the check is redundant.

The developers might have wanted to check the result of the malloc function, which returns NULL if memory allocation fails. However, the typo triggers the wrong check, and dereferencing happens further down in the code:

for (int64_t i = 0; i < SUNHashMap_Capacity(map); i++)
{
  SUNHashMapKeyValue kvp = SUNStlVector_SUNHashMapKeyValue_At(map->buckets, i);
  if (kvp)
  {
    (*values)[count++] = kvp->value; }// <=
}

The PVS-Studio warning:

V522 [CWE-690, CERT-MEM52-CPP, SEC-NULL] There might be dereferencing of a potential null pointer ' values'. Check lines: 472, 465. sundials_hashmap.c 472

To fix the code, we'll add a check for the values pointer and verify that memory is allocated at *values:

if (!map || !values)
{
  return SUN_ERR_ARG_CORRUPT;
}
values = (void *)malloc(SUNHashMap_Capacity(map) * value_size);
if (!*values)
{
  return SUN_ERR_MALLOC_FAIL;
}

Snippet 3

The PVS-Studio warning:

V558 [CWE-562, CERT-DCL30-C, SEC-MEMORY] Function returns the reference to temporary local object: tmp. matrixiterator.hxx 527

template struct Coords : Coords2DIterator
{
  // ....
  Coords& operator++(int)
  {
    Coords tmp(*this);
    ++(*this);
    return tmp;
  }
  // ....
}

It looks like the developers copied the prefix increment implementation and used it for the postfix increment by simply adding a dummy parameter of the int type. That said, the best approach when implementing such operators is to use semantics similar to those of built-in types.

A postfix increment stores the previous value, produces a side effect, and returns a prvalue with the previous value. Here, an lvalue reference to the tmp local object is returned. Using it in the caller function results in undefined behavior.

To avoid this, we need to return the object by value:

Coords operator++(int) { /* .... */ }

The code below contains an explicit specialization of this structure where the operator is implemented correctly.

Snippet 4

The PVS-Studio warnings:

  • V773 [CWE-401, CERT-MEM31-C, CERT-MEM51-CPP, SEC-LEAKS] The function was exited without releasing the 'temp_real' pointer. A memory leak is possible. sci_fft.cpp 212
  • V773 [CWE-401, CERT-MEM31-C, CERT-MEM51-CPP, SEC-LEAKS] The function was exited without releasing the 'temp_imaginary' pointer. A memory leak is possible. sci_fft.cpp 212
define MALLOC malloc
// ....
int fft_2dim(double *signal_real, double *signal_imaginary, int signal_rows, int signal_cols, int inverse, int *buffer_data, int buffer_size)
{
  // ....
  temp_real = (double *)MALLOC(signal_cols * sizeof(double));
  temp_imaginary = (double *)MALLOC(signal_cols * sizeof(double));
  if (temp_real == NULL || temp_imaginary == NULL)
  {
    return 1;
  }
  // ....
}

Two memory blocks are allocated, followed by a check whether the operation was successful. If memory has been allocated for the first buffer but not for the second one, an early exit occurs, and the first buffer remains unallocated. This is a memory leak.

We can avoid it by releasing both pointers before exiting. Here's the fixed code:

define FREE free
// ....
temp_real = (double *)MALLOC(signal_cols * sizeof(double));
temp_imaginary = (double *)MALLOC(signal_cols * sizeof(double));
if (temp_real == NULL || temp_imaginary == NULL)
{
  FREE(temp_real);
  FREE(temp_imaginary);
  return 1;
}

Strange code

Snippet 5

The PVS-Studio warning:

V1061 [CERT-DCL58-CPP] Extending the 'std' namespace may result in undefined behavior. sparseOp.hxx 39

namespace std { /* std namespace does not implement complex ordering: we use the lexicographical order */
typedef double (*cplxFun_t)(std::complex const&);
ifndef SCI_CPLX_ORDER_SEP21 /* on abs() and arg() according to current practise */
cplxFun_t const mostSignificant (&std::abs);
cplxFun_t const leastSignificant(&std::arg);
else /*on real and imaginary parts as per SEP 21 recommendation.*/
cplxFun_t const mostSignificant (&std::real);
cplxFun_t const leastSignificant(&std::imag);
endif
template<> struct less std::complex<double > {
bool operator()(std::complex const& op1, std::complex const& op2) const {
if (mostSignificant(op1) < mostSignificant(op2)) {
return true;
}
if (mostSignificant(op2) < mostSignificant(op1)) {
return false;
}
return leastSignificant(op1) < leastSignificant(op2);
}
};
// ....
}

The standard library doesn't set an order for complex numbers, so the developers came up with their own. The issue is that the std namespace can't be extended. According to the standard, the program behavior is undefined. The only exception to this rule is when a standard library class template is specialized, if the declaration depends on a custom type. However, std::complex isn't one of them.

How can we fix this? We have two options:

  • we can create our own comparator and use it in the appropriate contexts;
  • we can create our own wrapper class for std::complex and then specialize std::less for it.

1429_Scilab/image2.png

Another issue worth noting is taking the addresses of standard library functions. Pay attention to how the mostSignificant and leastSignificant pointers are initialized in both branches. Since C++20, the behavior is well-defined when a program tries to take the address of an addressable function. Otherwise, the behavior is unspecified. The std::abs, std::arg, std::real, and std::imag overloads for complex numbers aren't addressable functions.

What can we do about this? We can wrap the calls to these functions in a lambda:

ifndef SCI_CPLX_ORDER_SEP21 /* on abs() and arg() according to current practise */
const auto mostSignificant = { return std::abs(val); };
const auto leastSignificant = { return std::arg(val); };
else /*on real and imaginary parts as per SEP 21 recommendation.*/
const auto mostSignificant = { return std::real(val); };
const auto leastSignificant = { return std::imag(val); };
endif

Although Scilab is compiled with the -std=c++17 flag, preparing the codebase for migration to newer standards is highly recommended.

Snippet 6

The PVS-Studio warning:

V628 [CWE-670, CERT-EXP19-C] It's possible that the line was commented out improperly, thus altering the program's operation logics. LinkAdapter.cpp 1140

// delete all information related to the block
void LinkAdapter::remove_partial_links_information(ScicosID uid)
{
  auto it = partial_links.find(uid);
  if (it != partial_links.end()) //DEBUG std::cerr << "erase " << uid << " partials " //<< to_string(it->second) << "\n";
  partial_links.erase(uid);
}

The analyzer detected an issue where the code's formatting doesn't reflect the program's actual behavior. The if statement is missing braces, and there's a commented line required for debugging between the condition and the erase call. Everything works as intended as long as it's commented: erase is called only if the element is found. Otherwise, the debug statement is included in the condition body, and erase is always called.

This code is misleading. Out of curiosity, I checked the revision history to see what the code looked like before. Originally, the member function looked like this:

// delete all information related to the block
void LinkAdapter::remove_partial_links_information(ScicosID uid)
{
  partial_links.erase(uid);
}

Then, the search by key and debug output were added. We can make the code work as expected by simply adding braces. We can also simplify the deletion process a bit:

void LinkAdapter::remove_partial_links_information(ScicosID uid)
{
  auto it = partial_links.find(uid);
  if (it != partial_links.end())
  {
    //DEBUG std::cerr << "erase " << uid << " partials " // << to_string(it->second) << "\n";
    partial_links.erase(it);
  }
}

Now the erase member function immediately receives the iterator found using find; no extra search by key is performed.

Snippet 7

The PVS-Studio warning:

V502 [CWE-783, CERT-EXP00-C] Perhaps the '?:' operator works in a different way than it was expected. The '?:' operator has a lower priority than the '==' operator. sci_sparse.cpp 51

types::Function::ReturnValue sci_sparse (types::typed_list &in, int _piRetCount, types::typed_list &out)
{
  bool isValid = true;
  // ....
  for (int i = 0 ; isValid && i < in.size() ; i++)
  {
    // ....
    case types::InternalType::ScilabBool :
    case types::InternalType::ScilabSparseBool :
    {
      isValid = (i == (in.size() > 1) ? 1 : 0);
    }
    // ....
  }

Here's an amusing code snippet containing a precedence error that doesn't affect the result. The conditional operator has lower precedence than the comparison operator, so the expression is parsed as follows: (i == (in.size() > 1)) ? 1 : 0.

First, the compiler compares i to the in.size() > 1 result, then, it applies the conditional operator. Perhaps the parentheses should've been placed differently:

isValid = i == ((in.size() > 1) ? 1 : 0);

However, the result is the same anyway. The curious thing is that the ternary operator doesn't change the value: the comparison result is already either 0 or 1, so the operator is redundant regardless of how the parentheses are arranged, and isValid gets the same value.

To avoid misleading developers, it's best to remove the unnecessary operation:

isValid = i == (in.size() > 1);

Typos and copypaste

Snippet 8

The PVS-Studio warning:

V792 [CWE-691] The 'isComplex' function located to the right of the operator '|' will be called regardless of the value of the left operand. Perhaps, it is better to use '||'. sci_mesh2di.cpp 42

types::Function::ReturnValue sci_mesh2di (types::typed_list &in, int _iRetCount, types::typed_list &out)
{
  // ....
  for (int i = 0; i < in.size(); i++)
  {
    if (!in[i]->isDouble() | in[i]->getAs types::Double ()->isComplex())
    {
      Scierror(999, _ ("%s: Wrong type for argument #%d: Real matrix expected.\n"), "mesh2di", i);
      return types::Function::Error;
    }
  }
  // ....
}

The loop checks whether all input arguments are real, non-complex numbers of the Double type. However, it uses the bitwise | instead of the logical ||. The bitwise operator doesn't have a short-circuit evaluation, so it always evaluates the right operand, even if the left operand

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.