Let's check Scilab

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_T[j + 1]) { Coserror(_("The time vector should be an increasing vector.\n")); *work = nullptr; delete[] ptr->workt; FREE(ptr->work); delete[] ptr; // buckets, i); if (kvp) { (*values)[count++] = kvp->value; } // struct lessstd::complex { bool operator()(std::complex const& op1, std::complex const& op2) const { if (mostSignificant(op1) second) second) 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 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()) // 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 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)); // 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) { return NULL; } if (m_pRealData[i] != NULL) Enter fullscreen mode Exit fullscreen mode // .... } 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

Original Source

Read the full article at Dev →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.