diff --git a/source/source_cell/read_atom_species.cpp b/source/source_cell/read_atom_species.cpp index 1dc1afb75d..538d57ec2a 100644 --- a/source/source_cell/read_atom_species.cpp +++ b/source/source_cell/read_atom_species.cpp @@ -35,6 +35,11 @@ bool read_atom_species(std::ifstream& ifa, std::stringstream ss; ss << one_line; ss >> ucell.atoms[i].label >> ucell.atoms[i].mass; + if (ss.fail()) + { + ModuleBase::WARNING_QUIT("read_atom_species", + "invalid ATOMIC_SPECIES line: failed to read element label and mass"); + } ucell.pseudo_fn[i] = "auto"; ucell.pseudo_type[i] = "auto"; @@ -180,12 +185,18 @@ bool read_lattice_constant(std::ifstream& ifa, // Reading lattice vectors. notice // here that only one cpu read these // parameters. - ifa >> latvec.e11 >> latvec.e12; - ModuleBase::GlobalFunc::READ_VALUE(ifa, latvec.e13); - ifa >> latvec.e21 >> latvec.e22; - ModuleBase::GlobalFunc::READ_VALUE(ifa, latvec.e23); - ifa >> latvec.e31 >> latvec.e32; - ModuleBase::GlobalFunc::READ_VALUE(ifa, latvec.e33); + std::string latvec_line_rest; + ifa >> latvec.e11 >> latvec.e12 >> latvec.e13; + std::getline(ifa, latvec_line_rest); // swallow inline comments after each row + ifa >> latvec.e21 >> latvec.e22 >> latvec.e23; + std::getline(ifa, latvec_line_rest); + ifa >> latvec.e31 >> latvec.e32 >> latvec.e33; + if (ifa.fail()) + { + ModuleBase::WARNING_QUIT("unitcell::read_lattice_constant", + "invalid LATTICE_VECTORS: failed to read 9 lattice vector components"); + } + std::getline(ifa, latvec_line_rest); } }//supply lattice vectors else diff --git a/source/source_cell/read_atoms.cpp b/source/source_cell/read_atoms.cpp index 831a761b79..eeba626791 100644 --- a/source/source_cell/read_atoms.cpp +++ b/source/source_cell/read_atoms.cpp @@ -84,6 +84,15 @@ bool unitcell::read_atom_positions(UnitCell& ucell, ModuleBase::Vector3 v; ModuleBase::Vector3 mv; ifpos >> v.x >> v.y >> v.z; + // An EOF failure means fewer coordinate lines than the + // declared atom count; leave that to the existing + // mismatch-in-atom-number exit in parse_atom_properties. + if (ifpos.fail() && !ifpos.eof()) + { + ofs_warning << " Error: failed to read the coordinate triplet of atom " + << ia + 1 << " for atom type " << ucell.atoms[it].label << std::endl; + return false; + } mv.x = true ; mv.y = true ; mv.z = true ; diff --git a/source/source_cell/read_atoms_helper.cpp b/source/source_cell/read_atoms_helper.cpp index 58ce696db6..1828764d24 100644 --- a/source/source_cell/read_atoms_helper.cpp +++ b/source/source_cell/read_atoms_helper.cpp @@ -422,14 +422,26 @@ bool parse_atom_properties(std::ifstream& ifpos, bool& set_element_mag_zero) { std::string tmpid; - tmpid = ifpos.get(); - - if( (int)tmpid[0] < 0 ) + if (ifpos.fail()) { + // the coordinate triplet itself failed to extract: fewer coordinate + // lines than the declared atom count std::cout << "read_atom_positions, mismatch in atom number for atom type: " << atom.label << std::endl; exit(1); } + const int next_char = ifpos.get(); + if (next_char == std::char_traits::eof()) + { + // a complete final triplet ending exactly at EOF has no optional + // properties; treat the clean EOF as end-of-line instead of a + // mismatch (the legacy signed-char check was also non-portable) + tmpid = "\n"; + } + else + { + tmpid = std::string(1, static_cast(next_char)); + } // read if catch goodbit before "\n" and "#" while ( (tmpid != "\n") && (ifpos.good()) && (tmpid !="#") ) @@ -646,7 +658,14 @@ bool read_atom_type_header(int it, UnitCell& ucell, // (3) read in atom number //========================= int na = 0; - ModuleBase::GlobalFunc::READ_VALUE(ifpos, na); + ifpos >> na; + if (ifpos.fail()) + { + ofs_warning << " Error: failed to read the number of atoms for this atom type." << std::endl; + return false; + } + std::string na_rest_of_line; + std::getline(ifpos, na_rest_of_line); ucell.atoms[it].na = na; ModuleBase::GlobalFunc::OUT(ofs_running,"Number of atoms for this type",na); diff --git a/source/source_cell/unitcell_setup.cpp b/source/source_cell/unitcell_setup.cpp index e996015c16..1a82c0902b 100644 --- a/source/source_cell/unitcell_setup.cpp +++ b/source/source_cell/unitcell_setup.cpp @@ -89,12 +89,15 @@ void UnitCell::setup_cell(const std::string& fn, std::ofstream& log, const doubl //======================== // call read_atom_species //======================== - const bool read_atom_species = unitcell::read_atom_species(ifa, log, *this, + ok = unitcell::read_atom_species(ifa, log, *this, basis_type, orbital_dir, init_wfc, onsite_radius, deepks_setorb, rpa); //======================== // call read_lattice_constant //======================== - const bool read_lattice_constant = unitcell::read_lattice_constant(ifa, log ,this->lat); + if (ok) + { + ok = unitcell::read_lattice_constant(ifa, log, this->lat); + } //========================== // readl sep potential, currently using the pseudopotential folder (pseudo_dir in INPUT) //========================== diff --git a/source/source_cell/unittests/CMakeLists.txt b/source/source_cell/unittests/CMakeLists.txt index 0a8d0f15c9..50dd08cbcd 100644 --- a/source/source_cell/unittests/CMakeLists.txt +++ b/source/source_cell/unittests/CMakeLists.txt @@ -33,3 +33,19 @@ addtest( TARGET MODULE_CELL_index_test LIBS base device SOURCES test_cell_index.cpp ../cell_index.cpp) + +addtest( + TARGET MODULE_CELL_read_species_malformed_test + LIBS parameter base device cell domain_decomposition neighbor symmetry + SOURCES test_read_atom_species.cpp + ../module_neighlist/neighbor_search.cpp + ../module_neighlist/bin_manager.cpp + ../module_neighlist/page_allocator.cpp) + +addtest( + TARGET MODULE_CELL_read_atoms_malformed_test + LIBS parameter base device cell domain_decomposition neighbor symmetry + SOURCES test_read_atoms.cpp + ../module_neighlist/neighbor_search.cpp + ../module_neighlist/bin_manager.cpp + ../module_neighlist/page_allocator.cpp) diff --git a/source/source_cell/unittests/test_read_atom_species.cpp b/source/source_cell/unittests/test_read_atom_species.cpp new file mode 100644 index 0000000000..b204ff3a3b --- /dev/null +++ b/source/source_cell/unittests/test_read_atom_species.cpp @@ -0,0 +1,148 @@ +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include +#include + +#include "source_cell/read_stru.h" +#include "source_cell/unitcell.h" + +/************************************************ + * unit test of read_atom_species.cpp malformed-input handling + ***********************************************/ + +/** + * - Tested Functions: + * - SpeciesMissingMassRejected + * - read_atom_species(): an ATOMIC_SPECIES line without a mass left + * mass = 0 silently (issue #8356); it must now quit with a message + * - PartialLatticeVectorsRejected + * - read_lattice_constant(): fewer than 9 LATTICE_VECTORS components left + * the unread tail at the Matrix3 default (identity), surviving even the + * determinant check; it must now quit with a message + * - ValidSpeciesAndVectors + * - a well-formed species line and a full 3x3 LATTICE_VECTORS block still + * read normally + * - LatticeVectorsWithInlineCommentsAccepted + * - vector rows annotated with trailing comments ("0.5 0.5 0.0 # a3"), + * common in real STRU files, must still be accepted + */ + +class ReadSpeciesMalformedTest : public ::testing::Test +{ + protected: + UnitCell ucell; + std::ofstream ofs_running; + std::string log_path; + std::vector stru_paths; + std::unique_ptr owned_atoms; + + void SetUp() override + { + log_path = testing::TempDir() + "read_species_malformed.log"; + ofs_running.open(log_path); + ucell.ntype = 1; + // UnitCell::~UnitCell() deletes atoms only when set_atom_flag is + // true; keep ownership here instead of relying on that flag + owned_atoms.reset(new Atom[1]); + ucell.atoms = owned_atoms.get(); + ucell.pseudo_fn.resize(1); + ucell.pseudo_type.resize(1); + ucell.orbital_fn.resize(1); + } + + void TearDown() override + { + ofs_running.close(); + std::remove(log_path.c_str()); + for (const std::string& path : stru_paths) + { + std::remove(path.c_str()); + } + } + + std::string write_stru_file(const std::string& name, const std::string& content) + { + const std::string path = testing::TempDir() + name; + std::ofstream ofs(path); + ofs << content; + ofs.close(); + stru_paths.push_back(path); + ofs_running << "created test STRU file: " << path << std::endl; + return path; + } + + std::ifstream open_stru_file(const std::string& path) + { + const std::string msg = "reading test STRU file: " + path; + std::cout << msg << std::endl; + ofs_running << msg << std::endl; + return std::ifstream(path); + } +}; + +TEST_F(ReadSpeciesMalformedTest, SpeciesMissingMassRejected) +{ + const std::string stru = write_stru_file("species_no_mass.stru", "ATOMIC_SPECIES\nH\n"); + std::ifstream ifa = open_stru_file(stru); + testing::internal::CaptureStdout(); + EXPECT_EXIT(unitcell::read_atom_species(ifa, ofs_running, ucell, "pw", "", "atomic", 0.0, false, false), + ::testing::ExitedWithCode(1), + ""); + const std::string output = testing::internal::GetCapturedStdout(); + EXPECT_THAT(output, testing::HasSubstr("invalid ATOMIC_SPECIES line")); + ifa.close(); +} + +TEST_F(ReadSpeciesMalformedTest, PartialLatticeVectorsRejected) +{ + const std::string stru = write_stru_file("latvec_partial.stru", + "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n1 0 0\n0 1 0\n"); + ucell.latName = "user_defined_lattice"; + std::ifstream ifa = open_stru_file(stru); + testing::internal::CaptureStdout(); + EXPECT_EXIT(unitcell::read_lattice_constant(ifa, ofs_running, ucell.lat), + ::testing::ExitedWithCode(1), + ""); + const std::string output = testing::internal::GetCapturedStdout(); + EXPECT_THAT(output, testing::HasSubstr("invalid LATTICE_VECTORS")); + ifa.close(); +} + +TEST_F(ReadSpeciesMalformedTest, ValidSpeciesAndVectors) +{ + const std::string stru = write_stru_file("species_ok.stru", "ATOMIC_SPECIES\nH 1.008 H.upf\n"); + std::ifstream ifa = open_stru_file(stru); + EXPECT_TRUE(unitcell::read_atom_species(ifa, ofs_running, ucell, "pw", "", "atomic", 0.0, false, false)); + EXPECT_DOUBLE_EQ(ucell.atoms[0].mass, 1.008); + ifa.close(); + + const std::string stru2 = write_stru_file("latvec_ok.stru", + "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n1 0 0\n0 1 0\n0 0 1\n"); + ucell.latName = "user_defined_lattice"; + std::ifstream ifa2 = open_stru_file(stru2); + EXPECT_TRUE(unitcell::read_lattice_constant(ifa2, ofs_running, ucell.lat)); + EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); + ifa2.close(); +} + +TEST_F(ReadSpeciesMalformedTest, LatticeVectorsWithInlineCommentsAccepted) +{ + // real STRU files annotate vector rows with trailing comments + // (e.g. "0.5 0.5 0.0 # a3"); the reader must swallow the rest of + // each row like the old READ_VALUE-based code did + const std::string stru = write_stru_file("latvec_comments.stru", + "LATTICE_CONSTANT\n4.0\nLATTICE_VECTORS\n" + "1 0 0 # Lattice vector 1\n" + "0 1 0 # Lattice vector 2\n" + "0 0 1 # Lattice vector 3\n"); + ucell.latName = "user_defined_lattice"; + std::ifstream ifa = open_stru_file(stru); + EXPECT_TRUE(unitcell::read_lattice_constant(ifa, ofs_running, ucell.lat)); + EXPECT_DOUBLE_EQ(ucell.lat.latvec.e33, 1.0); + ifa.close(); +} diff --git a/source/source_cell/unittests/test_read_atoms.cpp b/source/source_cell/unittests/test_read_atoms.cpp new file mode 100644 index 0000000000..055e9ef330 --- /dev/null +++ b/source/source_cell/unittests/test_read_atoms.cpp @@ -0,0 +1,183 @@ +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "source_cell/read_stru.h" +#include "source_cell/unitcell.h" + +/************************************************ + * unit test of read_atoms.cpp malformed-input handling + ***********************************************/ + +/** + * - Tested Functions: + * - NonNumericCoordinateRejected + * - read_atom_positions(): a coordinate line with non-numeric content + * (e.g. "1.0 1.0 x") is now rejected at the extraction point; a line + * truncated at EOF still goes to the existing mismatch-in-atom-number + * exit in parse_atom_properties() (issue #8356) + * - NonNumericAtomCountRejected + * - read_atom_type_header(): a non-numeric atom count after a valid first + * species left na = 0 while the total atom count stayed positive, so + * the old reader accepted it; it is now rejected at the extraction + * point and the warning text is asserted + * - LiteralZeroCountAccepted + * - a species with a literal zero atom count is intentionally supported + * - ValidFinalTripletAtExactEofAccepted + * - a complete final coordinate triplet ending exactly at EOF must not be + * misreported as a count mismatch + * - ValidPositionsAccepted + * - a well-formed ATOMIC_POSITIONS section still reads normally + */ + +class ReadAtomsMalformedTest : public ::testing::Test +{ + protected: + UnitCell ucell; + std::ofstream ofs_running; + std::ofstream ofs_warning; + std::string log_path; + std::string warn_path; + std::vector stru_paths; + std::unique_ptr owned_atoms; + + void SetUp() override + { + log_path = testing::TempDir() + "read_atoms_malformed.log"; + warn_path = testing::TempDir() + "read_atoms_malformed.warn"; + ofs_running.open(log_path); + ofs_warning.open(warn_path); + // a sane lattice scale: finalize_atom_positions() checks the + // transformed coordinates, which are divided by lat0 + ucell.lat0 = 4.0; + } + + // UnitCell::~UnitCell() deletes atoms only when set_atom_flag is true; + // keep ownership here instead of relying on that flag + void init_types(const int ntype) + { + ucell.ntype = ntype; + owned_atoms.reset(new Atom[ntype]); + ucell.atoms = owned_atoms.get(); + ucell.pseudo_fn.resize(ntype); + ucell.pseudo_type.resize(ntype); + ucell.orbital_fn.resize(ntype); + } + + void TearDown() override + { + ofs_running.close(); + ofs_warning.close(); + std::remove(log_path.c_str()); + std::remove(warn_path.c_str()); + for (const std::string& path : stru_paths) + { + std::remove(path.c_str()); + } + } + + std::string read_warn_file() + { + ofs_warning.flush(); + std::ifstream ifs(warn_path); + return std::string(std::istreambuf_iterator(ifs), std::istreambuf_iterator()); + } + + bool read_positions(const std::string& content) + { + const std::string stru_path = testing::TempDir() + "positions.stru"; + std::ofstream ofs(stru_path); + ofs << content; + ofs.close(); + stru_paths.push_back(stru_path); + ofs_running << "created test STRU file: " << stru_path << std::endl; + const std::string msg = "reading test STRU file: " + stru_path; + std::cout << msg << std::endl; + ofs_running << msg << std::endl; + std::ifstream ifpos(stru_path); + const bool result = unitcell::read_atom_positions(ucell, + ifpos, + ofs_running, + ofs_warning, + 1, + "pw", + "", + "atomic", + 0.0, + false, + false, + "scf", + "ksdft", + 0); + ifpos.close(); + return result; + } +}; + +TEST_F(ReadAtomsMalformedTest, NonNumericCoordinateRejected) +{ + init_types(1); + ucell.atoms[0].label = "H"; + const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n1.0 1.0 x\n"); + EXPECT_FALSE(result); +} + +TEST_F(ReadAtomsMalformedTest, NonNumericAtomCountRejected) +{ + // discriminating case: with a valid first species, the old reader left + // the failed count at zero while the total atom count stayed positive, + // so parsing succeeded; the new check must reject at the extraction point + init_types(2); + ucell.atoms[0].label = "H"; + ucell.atoms[1].label = "O"; + const bool result = + read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n1\n0.0 0.0 0.0\nO\n0.0\nx\n"); + EXPECT_FALSE(result); + EXPECT_THAT(read_warn_file(), testing::HasSubstr("failed to read the number of atoms")); +} + +TEST_F(ReadAtomsMalformedTest, LiteralZeroCountAccepted) +{ + // a species with a literal zero atom count is intentionally supported; + // only a failed conversion must be rejected + init_types(2); + ucell.atoms[0].label = "H"; + ucell.atoms[1].label = "O"; + const bool result = + read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n1\n0.0 0.0 0.0\nO\n0.0\n0\n"); + EXPECT_TRUE(result); + EXPECT_EQ(ucell.atoms[1].na, 0); +} + +TEST_F(ReadAtomsMalformedTest, ValidFinalTripletAtExactEofAccepted) +{ + // a complete final coordinate triplet ending exactly at EOF (no trailing + // newline) is valid input; the legacy signed-char EOF check used to + // misreport it as "mismatch in atom number" + init_types(1); + ucell.atoms[0].label = "H"; + const bool result = read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n1\n0.0 0.0 0.0"); + EXPECT_TRUE(result); + EXPECT_EQ(ucell.atoms[0].na, 1); +} + +TEST_F(ReadAtomsMalformedTest, ValidPositionsAccepted) +{ + // the second atom sits at half a cell on each axis: anything on an exact + // lattice period (e.g. 1.0 1.0 1.0) wraps onto the first atom by PBC and + // check_tau would legitimately report overlapping atoms + init_types(1); + ucell.atoms[0].label = "H"; + const bool result = + read_positions("ATOMIC_POSITIONS\nCartesian\nH\n0.0\n2\n0.0 0.0 0.0\n0.5 0.5 0.5\n"); + EXPECT_TRUE(result); + EXPECT_EQ(ucell.atoms[0].na, 2); + EXPECT_DOUBLE_EQ(ucell.atoms[0].tau[1].z, 0.5); +}