Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Opening a file that is already open has implementationBB. Definitions#implementation-defined behavior, according to the C Standard, 7.21.3, paragraph 8 [ISO/AA. Bibliography#ISO-IEC 9899:-2011]:

Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined. Whether the same file can be simultaneously open multiple times is also implementation-defined.

Some implementations do not allow multiple copies of the same file to be open at the same time. Consequently, portable code cannot depend on what will happen if this rule is violated. Even on implementations that do not outright fail to open an already-opened file, a TOCTOU BB. Definitions#TOCTOU (time-of-check, time-of-use) race condition exists in which the second open could operate on a different file from the first due to the file being moved or deleted (see FIO45-C. Avoid TOCTOU race conditions while accessing files for more details on TOCTOU race conditions).

...

#include <stdio.h>   void do_stuff(void) { FILE *logfile = fopen("log", "a"); if (logfile == NULL) { /* Handle error */ } /* Write logs pertaining to do_stuff() */ fprintf(logfile, "do_stuff\n"); } int main(void) { FILE *logfile = fopen("log", "a"); if (logfile == NULL) { /* Handle error */ } /* Write logs pertaining to main() */ fprintf(logfile, "main\n"); do_stuff();   if (fclose(logfile) == EOF) { /* Handle error */ } return 0; }
Code Block
bgColor#ffcccc
langc

Because the file log is opened twice (once in main() and again in do_stuff()), this program has implementation-defined behavior.

...

#include <stdio.h>   void do_stuff(FILE *logfile) { /* Write logs pertaining to do_stuff() */ fprintf(logfile, "do_stuff\n"); } int main(void) { FILE *logfile = fopen("log", "a"); if (logfile == NULL) { /* Handle error */ } /* Write logs pertaining to main() */ fprintf(logfile, "main\n"); do_stuff(logfile);   if (fclose(logfile) == EOF) { /* Handle error */ } return 0; }
Code Block
bgColor#ccccff
langc

Risk Assessment

Simultaneously opening a file multiple times can result in unexpected errors and nonportable behavior.

...

Tool

Version

Checker

Description

CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

IO.RACE

(customization)

File System Race Condition

Users can implement a custom check that triggers a warning if a file-opening function is called on a file that is already open.

CERT C Rules implemented in the LDRA tool suite

Include Page
LDRA_V
LDRA_V

75 D

Partially implemented

Related Vulnerabilities

Search for vulnerabilities BB. Definitions#vulnerability resulting from the violation of this rule on the CERT website.

...

 Bibliography

 

...

Image Modified