DEV Community

Cover image for Let's check Scilab
Unicorn Developer
Unicorn Developer

Posted on

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 lessstd::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]->getAstypes::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 has already established that the argument isn't a Double.

The getAs function is implemented as static_cast(this) without any type checking:

template
inline T* getAs(void)
{
return static_cast(this);
}
Casting an object of a dynamic type that is neither a Double nor a subclass of a Double results in undefined behavior. Here's the fixed code:

if (!in[i]->isDouble() || in[i]->getAstypes::Double()->isComplex())
Snippet 9

The PVS-Studio warning: V501 [CWE-570] There are identical sub-expressions to the left and to the right of the '!=' operator: pDblx->getSize() != pDblx->getSize() sci_mesh2di.cpp 52

types::Function::ReturnValue sci_mesh2di
(types::typed_list &in, int _iRetCount, types::typed_list &out)
{
// ....
types::Double *pDblx = in[0]->getAstypes::Double();
types::Double *pDbly = in[1]->getAstypes::Double();

if (pDblx->getSize() != pDblx->getSize()) // <=
{
Scierror(999, _("%s: Arguments #%d and #%d must have the same sizes.\n")
, "mesh2di", 1,2);
return types::Function::Error;
}
// ....
}
The function takes two arrays as input and checks whether they have the same size before proceeding. If their sizes differ, it prints an error message and exits. However, in the pDblx->getSize() != pDblx->getSize() condition, the code compares the pDblx size to itself.

This is a classic copy-paste typo. The developers forgot to replace pDblx with pDbly in the second part of the condition. The expression is always false, so the check never triggers. This causes issues further in the code:

int iNbNodes = pDblx->getSize();
// ....
for (int i=0; i < iNbNodes; i++)
{
pDblxy->set(0,i,pDblx->get(i));
pDblxy->set(1,i,pDbly->get(i));
}
If one array is shorter than the other, the loop goes out of bounds. Instead of receiving a clear message, the user may encounter a crash, an incorrect result, or anything else at all, because the behavior in such a case is undefined. Here's the fixed code:

if (pDblx->getSize() != pDbly->getSize())
Snippet 10

The PVS-Studio warning: V517 [CWE-570, CERT-MSC01-C] The use of 'if (A) {...} else if (A) {...}' pattern was detected. There is a probability of logical error presence. Check lines: 701, 785. fromws_c.cpp 701

typedef enum
{
SCSREAL_N = 10,
SCSCOMPLEX_N = 11,
SCSINT_N = 80,
SCSINT8_N = 81,
SCSINT16_N = 82,
SCSINT32_N = 84,
SCSUINT_N = 800,
SCSUINT8_N = 811,
SCSUINT16_N = 812,
SCSUINT32_N = 814,
SCSUNKNOW_N = -1
} scicos_datatype_number;

SCICOS_BLOCKS_IMPEXP void fromws_c(scicos_block* block, int flag)
{
//....
else if (ytype == SCSINT32_N)
{
/* --------------------- int32 long ---------------------/
y_l = Getint32OutPortPtrs(block, 1);
// ....
}
// ....
else if (ytype == SCSINT32_N)
{
/
--------------------- uint32 ulong ---------------------*/
y_ul = Getuint32OutPortPtrs(block, 1);
// ....
}
// ....
}
In a long chain of if ... else if statements, the ytype variable is compared to values of the scicos_datatype_number enumeration. The analyzer detected that the ytype == SCSINT32_N condition appears twice, on lines 701 and 785. The second check never executes.

Judging by the comment in the second uint32 ulong branch, the ytype == SCSUINT32_N check should've been there. The enumeration does contain this constant, and its value is 814. This is another typical copy-paste mistake: the developers copied the int32 branch, changed its body, but forgot to update the condition. As a result, the branch for uint32 is missing.

Here's the fixed code:

else if (ytype == SCSUINT32_N)
Snippet 11

The PVS-Studio warning: V766 [CWE-462] An item with the same key '"H5T_VAX_F64"' has already been added. H5Type.hxx 241

static std::map initMap()
{
std::map nameToType;
// ....

nameToType.insert
(std::pair("H5T_IEEE_F64LE", H5T_IEEE_F64LE));
nameToType.insert
(std::pair("H5T_VAX_F32", H5T_VAX_F32)); // <=
nameToType.insert
(std::pair("H5T_VAX_F64", H5T_VAX_F64)); // <=
nameToType.insert
(std::pair("H5T_NATIVE_FLOAT", H5T_NATIVE_FLOAT));
// ....
nameToType.insert
(std::pair("H5T_VAX_F32", H5T_VAX_F32)); // <=
nameToType.insert
(std::pair("H5T_VAX_F64", H5T_VAX_F64)); // <=
nameToType.insert
(std::pair("H5T_MIPS_F32", H5T_MIPS_F32));
// ....
}
The initMap function populates a mapping table that associates string type names with their IDs. The analyzer detected that the "H5T_VAX_F32" and "H5T_VAX_F64" pairs are added more than once. The developers might have copied the same lines, accidentally adding them to the list twice.

The duplicates are harmless for now because the values match. However, if one of them contained a typo, then a value might have been omitted. Manually finding such a mistake in 124 lines of code would take a lot of time. Static analysis is really useful in situations like this.

Here are the similar warnings:

V766 [CWE-462] An item with the same key '"H5T_VAX_F32"' has already been added. H5Type.hxx 240
V766 [CWE-462] An item with the same key 'L"mustBeMember"' has already been added. arguments.cpp 1098
Snippet 12

The PVS-Studio warning: V519 [CWE-563, CERT-MSC13-C] The 'iy' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 53, 55. int2db.c 55

int C2F(int2db)(int *n, int *dx, int *incx, double *dy, int *incy)
{
int ix = 0, iy = 0;
....
ix = 1;
iy = 1;

if (*incx < 0)
{
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0)
{
iy = (-(*n) + 1) * *incy + 1;
}
iy = (-(*n) + 1) * *incy + 1;
....
}
In the function, the ix and iy variables get the 1 value. Then, if either incx or incy is negative, the corresponding index is recalculated using a formula. Right after that, the same formula is applied again to iy, but this time without the condition. This makes the if (*incy < 0) block pointless. The extra line most likely got into the code by mistake and should be removed.

It's curious that this error isn't new. Looking through the commit history reveals that the extra line was present in earlier versions. At that time, the conditions appeared on a single line, while the redundant assignment sat below them, indented as a part of the preceding if statement:

1429_Scilab/image3.png

The developers later reformatted the code and added braces but didn't remove or replace the line:

1429_Scilab/image4.png

This example shows that an error may go unnoticed for years, but it can be detected, for example, using static code analysis.

Those AI trainers
We recently published an article on our blog titled "Bloated C++ code," which covered an AI-generated project. Its main issue was code bloat. AI-generated code often contains lots of repetitive blocks and pointless checks. While reviewing the Scilab analysis report, I got the impression that the AI model had learned from examples similar to those found in real-world projects. Here are some of them.

Snippet 13

The PVS-Studio warning: V571 [CWE-571] Recurring check. The 'if (m_prob_mem != __null)' condition was already verified in line 80. IDAManager.hxx 82

// ....
~IDAManager() {
if (m_prob_mem != NULL)
{
if (m_prob_mem != NULL) IDAFree(&m_prob_mem);
m_prob_mem = NULL;
}
....
}
First, the program checks whether the m_prob_mem pointer is not null, and then repeats this check in the very next line. But there's more: the IDAFree function contains another check for the same pointer:

void IDAFree(void** ida_mem)
{
IDAMem IDA_mem;

if (*ida_mem == NULL) { return; }
// ....
free(*ida_mem);
*ida_mem = NULL;
}
At the end of the function, the memory is released and the pointer is set to NULL, so we can replace the entire code with a single line:

~IDAManager() {
IDAFree(&m_prob_mem);
// ....
}
Snippet 14

The PVS-Studio warning: V519 The 'tmp->sn_size' variable is assigned values twice successively. Perhaps this is a mistake. Check lines: 544, 550. taucs_scilab.c 550

static supernodal_frontal_matrix*
supernodal_frontal_create(int* firstcol_in_supernode,
int sn_size,
int n,
int* rowind)
{
....
tmp->sn_size = sn_size;
tmp->n = n;

tmp->rowind = rowind;

tmp->n = n;
tmp->sn_size = sn_size;
....
}
Unless you've seen how things work in real projects, you might think that assigning a value just once is enough. First, they assign the values one way, then they do it all over again in reverse.

First, values are assigned to the sn_size and n data members, then to rowind. Finally, the same values are assigned to n and sn_size a second time, but in reverse order. The developers have to compare both blocks every time to make sure they're identical.

Snippet 15

The PVS-Studio warning: V547 [CWE-570] Expression 'i >= m_iSize' is always false. cell.cpp 254

Cell* Cell::set(InternalType** _pIT)
{
// ....
for (int i = 0; i < m_iSize; i++)
{
if (i >= m_iSize)
{
return NULL;
}

if (m_pRealData[i] != NULL)
Enter fullscreen mode Exit fullscreen mode

// ....
}
The i < m_iSize loop condition guarantees that the i >= m_iSize check within the loop will never execute. The developers might have copied this check from the neighboring overload, Cell::set(int _iIndex, InternalType* _pIT). There, the index comes from outside the function, so the _iIndex >= m_iSize check prevents out-of-bounds access. However, in this overload, the loop keeps the index within bounds, making the check redundant. We can remove it to avoid confusing developers and cluttering the code.

Let's sum-up
Static analysis helps detect errors that may have been lurking in a project for years. You can check your own project using PVS-Studio analyzer right now. We've covered all the necessary steps—from installation to your first report—in the article "Get started with PVS-Studio static analyzer".

Try PVS-Studio for free

Top comments (0)