use ValueTokenizer instead of sscanf() for safer parsing of custom processor grids

This commit is contained in:
Axel Kohlmeyer
2021-03-16 09:15:49 -04:00
parent 5d5fc4a04d
commit b7759b0cdb

View File

@ -22,6 +22,7 @@
#include "error.h"
#include "math_extra.h"
#include "memory.h"
#include "tokenizer.h"
#include "universe.h"
#include <cmath>
@ -300,12 +301,16 @@ void ProcMap::custom_grid(char *cfile, int nprocs,
}
}
int n = strlen(line) + 1;
MPI_Bcast(&n,1,MPI_INT,0,world);
MPI_Bcast(line,n,MPI_CHAR,0,world);
int rv = sscanf(line,"%d %d %d",&procgrid[0],&procgrid[1],&procgrid[2]);
if (rv != 3) error->all(FLERR,"Processors custom grid file is inconsistent");
MPI_Bcast(line,MAXLINE,MPI_CHAR,0,world);
try {
ValueTokenizer procs(line);
procgrid[0] = procs.next_int();
procgrid[1] = procs.next_int();
procgrid[2] = procs.next_int();
} catch (TokenizerException &e) {
error->all(FLERR,fmt::format("Processors custom grid file "
"is inconsistent: {}", e.what()));
}
int flag = 0;
if (procgrid[0]*procgrid[1]*procgrid[2] != nprocs) flag = 1;
@ -324,10 +329,17 @@ void ProcMap::custom_grid(char *cfile, int nprocs,
for (int i = 0; i < nprocs; i++) {
if (!fgets(line,MAXLINE,fp))
error->one(FLERR,"Unexpected end of custom file");
rv = sscanf(line,"%d %d %d %d",
&cmap[i][0],&cmap[i][1],&cmap[i][2],&cmap[i][3]);
if (rv != 4)
error->one(FLERR,"Processors custom grid file is inconsistent");
try {
ValueTokenizer pmap(line);
cmap[i][0] = pmap.next_int();
cmap[i][1] = pmap.next_int();
cmap[i][2] = pmap.next_int();
cmap[i][3] = pmap.next_int();
} catch (TokenizerException &e) {
error->one(FLERR,fmt::format("Processors custom grid file is "
"inconsistent: {}", e.what()));
}
}
fclose(fp);
}