checkpolicy: cleanup resources on parse error

Close the input file and free all memory by the queue and lexer on a
syntax or parse error.

Signed-off-by: Christian Göttsche <cgzones@googlemail.com>
Acked-by: James Carter <jwcart2@gmail.com>
This commit is contained in:
Christian Göttsche 2024-01-22 14:54:54 +01:00 committed by James Carter
parent 595c4163f0
commit c2fc48be68
1 changed files with 19 additions and 7 deletions

View File

@ -26,6 +26,7 @@ extern FILE *yyin;
extern void init_parser(int); extern void init_parser(int);
extern int yyparse(void); extern int yyparse(void);
extern void yyrestart(FILE *); extern void yyrestart(FILE *);
extern int yylex_destroy(void);
extern queue_t id_queue; extern queue_t id_queue;
extern unsigned int policydb_errors; extern unsigned int policydb_errors;
extern policydb_t *policydbp; extern policydb_t *policydbp;
@ -34,6 +35,8 @@ extern void set_source_file(const char *name);
int read_source_policy(policydb_t * p, const char *file, const char *progname) int read_source_policy(policydb_t * p, const char *file, const char *progname)
{ {
int rc = -1;
yyin = fopen(file, "r"); yyin = fopen(file, "r");
if (!yyin) { if (!yyin) {
fprintf(stderr, "%s: unable to open %s: %s\n", progname, file, strerror(errno)); fprintf(stderr, "%s: unable to open %s: %s\n", progname, file, strerror(errno));
@ -41,21 +44,26 @@ int read_source_policy(policydb_t * p, const char *file, const char *progname)
} }
set_source_file(file); set_source_file(file);
if ((id_queue = queue_create()) == NULL) { id_queue = queue_create();
if (id_queue == NULL) {
fprintf(stderr, "%s: out of memory!\n", progname); fprintf(stderr, "%s: out of memory!\n", progname);
return -1; goto cleanup;
} }
mlspol = p->mls;
policydbp = p; policydbp = p;
policydbp->name = strdup(file); policydbp->name = strdup(file);
mlspol = p->mls; if (!policydbp->name) {
fprintf(stderr, "%s: out of memory!\n", progname);
goto cleanup;
}
init_parser(1); init_parser(1);
if (yyparse() || policydb_errors) { if (yyparse() || policydb_errors) {
fprintf(stderr, fprintf(stderr,
"%s: error(s) encountered while parsing configuration\n", "%s: error(s) encountered while parsing configuration\n",
progname); progname);
return -1; goto cleanup;
} }
rewind(yyin); rewind(yyin);
init_parser(2); init_parser(2);
@ -65,11 +73,15 @@ int read_source_policy(policydb_t * p, const char *file, const char *progname)
fprintf(stderr, fprintf(stderr,
"%s: error(s) encountered while parsing configuration\n", "%s: error(s) encountered while parsing configuration\n",
progname); progname);
return -1; goto cleanup;
} }
rc = 0;
cleanup:
queue_destroy(id_queue); queue_destroy(id_queue);
fclose(yyin); fclose(yyin);
yylex_destroy();
return 0; return rc;
} }