Merge pull request #959 from libexpat/tests-benchmark-improve

`tests/benchmark`: Fix a harmless TOCTTOU + upfront refactorings + improve error messages
This commit is contained in:
Sebastian Pipping 2025-02-22 16:08:31 +01:00 committed by GitHub
commit ca7321b9fc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -32,10 +32,18 @@
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define _POSIX_C_SOURCE 1 // fdopen
#if defined(_MSC_VER)
# include <io.h> // _open, _close
#else
# include <unistd.h> // close
#endif
#include <fcntl.h> // open
#include <sys/stat.h>
#include <assert.h>
#include <stddef.h> // ptrdiff_t
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "expat.h"
@ -52,17 +60,18 @@
# define XML_FMT_STR "s"
#endif
static void
static int
usage(const char *prog, int rc) {
fprintf(stderr, "usage: %s [-n] filename bufferSize nr_of_loops\n", prog);
exit(rc);
return rc;
}
int
main(int argc, char *argv[]) {
XML_Parser parser;
char *XMLBuf, *XMLBufEnd, *XMLBufPtr;
FILE *fd;
int fd;
FILE *file;
struct stat fileAttr;
int nrOfLoops, bufferSize, i, isFinal;
size_t fileSize;
@ -76,34 +85,45 @@ main(int argc, char *argv[]) {
ns = 1;
j = 1;
} else
usage(argv[0], 1);
return usage(argv[0], 1);
}
}
if (argc != j + 4)
usage(argv[0], 1);
return usage(argv[0], 1);
if (stat(argv[j + 1], &fileAttr) != 0) {
fprintf(stderr, "could not access file '%s'\n", argv[j + 1]);
fd = open(argv[j + 1], O_RDONLY);
if (fd == -1) {
fprintf(stderr, "could not open file '%s'\n", argv[j + 1]);
return 2;
}
fd = fopen(argv[j + 1], "r");
if (! fd) {
fprintf(stderr, "could not open file '%s'\n", argv[j + 1]);
exit(2);
if (fstat(fd, &fileAttr) != 0) {
close(fd);
fprintf(stderr, "could not fstat file '%s'\n", argv[j + 1]);
return 2;
}
file = fdopen(fd, "r");
if (! file) {
close(fd);
fprintf(stderr, "could not fdopen file '%s'\n", argv[j + 1]);
return 2;
}
bufferSize = atoi(argv[j + 2]);
nrOfLoops = atoi(argv[j + 3]);
if (bufferSize <= 0 || nrOfLoops <= 0) {
fclose(file);
close(fd);
fprintf(stderr, "buffer size and nr of loops must be greater than zero.\n");
exit(3);
return 3;
}
XMLBuf = malloc(fileAttr.st_size);
fileSize = fread(XMLBuf, sizeof(char), fileAttr.st_size, fd);
fclose(fd);
fileSize = fread(XMLBuf, sizeof(char), fileAttr.st_size, file);
fclose(file);
close(fd);
if (ns)
parser = XML_ParserCreateNS(NULL, '!');
@ -132,7 +152,7 @@ main(int argc, char *argv[]) {
XML_GetCurrentColumnNumber(parser));
free(XMLBuf);
XML_ParserFree(parser);
exit(4);
return 4;
}
XMLBufPtr += bufferSize;
} while (! isFinal);