analyzer: add known stdio functions to sm-file.cc (PR analyzer/58237)
authorDavid Malcolm <dmalcolm@redhat.com>
Thu, 19 Dec 2019 20:59:04 +0000 (15:59 -0500)
committerDavid Malcolm <dmalcolm@redhat.com>
Wed, 15 Jan 2020 01:39:26 +0000 (20:39 -0500)
commit697251b7a1bb7c14d3805de22248e83a23b90d1a
tree4411d9448340e818e2a373260460f56207f14087
parent81a68b9e3774401a99719ea29640d13125745b41
analyzer: add known stdio functions to sm-file.cc (PR analyzer/58237)

The analyzer ought to report various file leaks for the reproducer in
PR analyzer/58237, such as:

  void f1(const char *str)
  {
    FILE * fp = fopen(str, "r");
    char buf[10];
    while (fgets(buf, 10, fp) != NULL)
    {
      /* Do something with buf */
    }
    /* Missing call to fclose. Need warning here for resource leak */
  }

but fails to do so, due to not recognizing fgets, and thus
conservatively assuming that it could close "fp".

This patch adds a function_set to sm-file.cc of numerous stdio.h
functions that are known to not close the file (and which require a
valid FILE *, but that's a matter for a followup), fixing the issue.

gcc/analyzer/ChangeLog:
PR analyzer/58237
* analyzer-selftests.cc (selftest::run_analyzer_selftests): Call
selftest::analyzer_sm_file_cc_tests.
* analyzer-selftests.h (selftest::analyzer_sm_file_cc_tests): New
decl.
* sm-file.cc: Include "analyzer/function-set.h" and
"analyzer/analyzer-selftests.h".
(get_file_using_fns): New function.
(is_file_using_fn_p): New function.
(fileptr_state_machine::on_stmt): Return true for known functions.
(selftest::analyzer_sm_file_cc_tests): New function.

gcc/testsuite/ChangeLog:
PR analyzer/58237
* gcc.dg/analyzer/file-1.c (test_4): New.
* gcc.dg/analyzer/file-pr58237.c: New test.
gcc/analyzer/ChangeLog
gcc/analyzer/analyzer-selftests.cc
gcc/analyzer/analyzer-selftests.h
gcc/analyzer/sm-file.cc
gcc/testsuite/ChangeLog
gcc/testsuite/gcc.dg/analyzer/file-1.c
gcc/testsuite/gcc.dg/analyzer/file-pr58237.c [new file with mode: 0644]