CodeQL File{MayNot,Never}BeClosed.ql file-handle resource leaks

Guided by CodeQL static code analyser.

FileMayNotBeClosed.ql
FileMayNeverBeClosed.ql

The trick with "if(fp != stdout)" is problematic (to analyser) as
technically 'stdout' can be a global pointer that COULD be modified any
time, so it might have changed between the fopen() and fclose() calls so
the close MAY NEVER occurs (which is problem the analyzer can see).

So local state is maintained as a bool which will also clarify to the
compiler see the intention without concern for external stdout
modification.

Some items appear to be out and out leaks when certain commands are use.
This commit is contained in:
Darryl L. Miles
2025-02-22 21:02:49 -05:00
committed by Tim Edwards
parent 7960020f7c
commit e88dcba1c5
10 changed files with 104 additions and 55 deletions
+15 -11
View File
@@ -119,7 +119,6 @@ ExtractTest(w, cmd)
CellUse *selectedCell;
Rect editArea;
char *addr, *name;
FILE *f;
typedef enum { CLRDEBUG, CLRLENGTH, DRIVER, DUMP, INTERACTIONS,
INTERCOUNT, EXTPARENTS, RECEIVER, SETDEBUG, SHOWDEBUG,
SHOWPARENTS, SHOWTECH, STATS, STEP, TIME } cmdType;
@@ -215,37 +214,41 @@ ExtractTest(w, cmd)
DBClearPaintPlane(interPlane);
break;
case INTERCOUNT:
f = stdout;
halo = 1;
if (cmd->tx_argc > 2)
halo = atoi(cmd->tx_argv[2]);
if (cmd->tx_argc > 3)
{
f = fopen(cmd->tx_argv[3], "w");
FILE *f = fopen(cmd->tx_argv[3], "w");
if (f == NULL)
{
perror(cmd->tx_argv[3]);
break;
}
ExtInterCount((CellUse *) w->w_surfaceID, halo, f);
fclose(f);
}
else
{
ExtInterCount((CellUse *) w->w_surfaceID, halo, stdout);
}
ExtInterCount((CellUse *) w->w_surfaceID, halo, f);
if (f != stdout)
(void) fclose(f);
break;
case TIME:
f = stdout;
if (cmd->tx_argc > 2)
{
f = fopen(cmd->tx_argv[2], "w");
FILE *f = fopen(cmd->tx_argv[2], "w");
if (f == NULL)
{
perror(cmd->tx_argv[2]);
break;
}
ExtTimes((CellUse *) w->w_surfaceID, f);
fclose(f);
}
else
{
ExtTimes((CellUse *) w->w_surfaceID, stdout);
}
ExtTimes((CellUse *) w->w_surfaceID, f);
if (f != stdout)
(void) fclose(f);
break;
case EXTPARENTS:
if (ToolGetEditBox(&editArea))
@@ -1105,6 +1108,7 @@ ExtDumpCaps(filename)
return;
}
ExtDumpCapsToFile(f);
fclose(f);
return;
}