Skip to content

[Code scan] Stop WFC_NAO binary writes after Binstream open failures #7562

Description

@njzjz

This issue is a result of a Codex global repository scan.

The WFC_NAO writer warns when Binstream::open() fails, but then continues writing to the stream. Binstream::operator<< and Binstream::write() call fwrite(..., this->fileptr) without validating that fileptr is non-null or that the full write succeeded.

Binstream write helpers:

// write a data into file
template<class T>
Binstream& Binstream:: operator<<(const T& data)
{
const int size=sizeof(T);
fwrite(&data,size,1,this->fileptr);
return *this;
}
//read an array of data
template<class T>
Binstream& Binstream::read(T* data, const int n)
{
const int size=sizeof(T);
size_t ch = fread(data,size,n,this->fileptr);
if(ch<n)
{
std::cout<<"Error in Binstream: Some dynamic memory didn't be read."<<std::endl;
std::cout<<"Please make you are using op: \"r\""<<std::endl;
exit(0);
}
return *this;
}
//write an array of data
template<class T>
Binstream& Binstream::write(const T* data, const int n)
{
const int size=sizeof(T);
fwrite(data,size,n,this->fileptr);
return *this;

WFC_NAO write paths:

{
ofs.open(name, "a");
}
else
{
ofs.open(name, "w");
}
if (!ofs)
{
ModuleBase::WARNING("ModuleIO::wfc_nao_write2file", "Can't write local orbital wave functions.");
}
ofs << nbands;
ofs << nlocal;

}
else
{
ofs.open(name, "w");
}
if (!ofs)
{
ModuleBase::WARNING("ModuleIO::wfc_nao_write2file_complex", "Can't write local orbital wave functions.");
}
ofs << ik + 1;

Relevant code:

if (!ofs)
{
    ModuleBase::WARNING("ModuleIO::wfc_nao_write2file", "Can't write local orbital wave functions.");
}

ofs << nbands;

and:

fwrite(&data, size, 1, this->fileptr);

Suggested fix:

Return or abort immediately after a failed open. Also make Binstream write operations validate fileptr and check that fwrite wrote the requested number of records.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions