From patchwork Tue Jul 19 16:06:25 2022 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Immad Mir X-Patchwork-Id: 1658104 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: bilbo.ozlabs.org; dkim=pass (1024-bit key; unprotected) header.d=gcc.gnu.org header.i=@gcc.gnu.org header.a=rsa-sha256 header.s=default header.b=X/HfjBFX; dkim-atps=neutral Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=gcc.gnu.org (client-ip=2620:52:3:1:0:246e:9693:128c; helo=sourceware.org; envelope-from=gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org; receiver=) Received: from sourceware.org (server2.sourceware.org [IPv6:2620:52:3:1:0:246e:9693:128c]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by bilbo.ozlabs.org (Postfix) with ESMTPS id 4LnNyQ0CMPz9sFr for ; Wed, 20 Jul 2022 02:07:23 +1000 (AEST) Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 0AA69385737B for ; Tue, 19 Jul 2022 16:07:17 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 0AA69385737B DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gcc.gnu.org; s=default; t=1658246837; bh=nsPEZsnXhDRTfBPY4kMV7ma1t4w06YNPuAi3+JuLEW8=; h=To:Subject:Date:List-Id:List-Unsubscribe:List-Archive:List-Post: List-Help:List-Subscribe:From:Reply-To:Cc:From; b=X/HfjBFXO4WnA8vples1iwGWgIEbkYQLVQq4F069Dqh1nsBK/xSWaiB9x3VJb2tGw QaqhKhKzVIG2Lk4lbyM/MtFPL/9t1kHM5KlAvoFB52uce0VfX9ApOj7TfAZ2gcPGKS cNOvW/KvItNfKNzxuWMuiMoZ+2WSZ+b6G2jYbwR0= X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from NAM02-BN1-obe.outbound.protection.outlook.com (mail-bn1nam07olkn2070.outbound.protection.outlook.com [40.92.15.70]) by sourceware.org (Postfix) with ESMTPS id E9D933858281 for ; Tue, 19 Jul 2022 16:06:53 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.1 sourceware.org E9D933858281 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=RMpBPhA8+p9vja/CGa+px5W6nR4Yt17A6LKkgbG2bLwhzCHX5Q6XHUY65JQ+TgAa6ATl8+Z8YAzELlhT4bXuyCOIMV1O/tO6oTzfkknePqLhbrmXqe6XUa7jkWJn1WqEQt2Py486EV4/gK8lGTWLlMjqNCqSjTev3NqtyHQy7qYnDzIHzrjhNJXZcyG7Sjhx+Zu7Z//JKVI/oKJqhk+hkwOxo0daKD7IcLAHFttfZ4wj3Gm+kM1xwxD7WAy/X6zA4i/dOP6IrN7dNV8qTkTsHvw+JqASQPHCEQR/7Wq/HmU0zTE7ljTMipAIKpy2mstVu6dGWx6rVFyHpIXSjY2n1g== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=microsoft.com; s=arcselector9901; h=From:Date:Subject:Message-ID:Content-Type:MIME-Version:X-MS-Exchange-AntiSpam-MessageData-ChunkCount:X-MS-Exchange-AntiSpam-MessageData-0:X-MS-Exchange-AntiSpam-MessageData-1; bh=nsPEZsnXhDRTfBPY4kMV7ma1t4w06YNPuAi3+JuLEW8=; b=F65L1WXPES9f4VOSRdR/14Wtut3kedbNJ9nkSe1cLyYf5skSwwF4KuqZji4W71sF+H08BCxbngalBaUdzjm/R5rSzxLWIroS10HoNaKLoALTljy4dVh2eBocOcv7aiK1N/QKNOOjxH51CEh826NxFDGBUCBtGC2FC/LGMBuD9LUGHizFli3aEV464tiaA1V3pyVOdsNoOW6HkHoSbPnZS4uZqM2hfmA+ZTucvkgUI1kPAm10tYFO/QD5zOd80Mz8v7AIDoJlNnIpHn3gaoc5HymDHlHWDhMxxK+O15QpmCIWHZz8BHRypr4Wdy7r7mWy+KqD843nAtebGr7H3WcQ6w== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=none; dmarc=none; dkim=none; arc=none Received: from CY4PR1801MB1910.namprd18.prod.outlook.com (2603:10b6:910:79::14) by MN2PR18MB2767.namprd18.prod.outlook.com (2603:10b6:208:39::31) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5438.23; Tue, 19 Jul 2022 16:06:51 +0000 Received: from CY4PR1801MB1910.namprd18.prod.outlook.com ([fe80::4d74:63e5:d5ee:3647]) by CY4PR1801MB1910.namprd18.prod.outlook.com ([fe80::4d74:63e5:d5ee:3647%2]) with mapi id 15.20.5438.021; Tue, 19 Jul 2022 16:06:51 +0000 To: gcc-patches@gcc.gnu.org Subject: [PATCH] Adding three new function attributes for static analysis of file descriptors Date: Tue, 19 Jul 2022 21:36:25 +0530 Message-ID: X-Mailer: git-send-email 2.25.1 X-TMN: [tKxzrM9jg/dSo9gzmHRWkEXQEYoDVuoDnwquLg67pRO6hBJHVBfjJSYFNGVd3tdX] X-ClientProxiedBy: PN0PR01CA0035.INDPRD01.PROD.OUTLOOK.COM (2603:1096:c01:4e::10) To CY4PR1801MB1910.namprd18.prod.outlook.com (2603:10b6:910:79::14) X-Microsoft-Original-Message-ID: <20220719160625.4892-1-mirimmad@outlook.com> MIME-Version: 1.0 X-MS-Exchange-MessageSentRepresentingType: 1 X-MS-PublicTrafficType: Email X-MS-Office365-Filtering-Correlation-Id: 4cf08835-c773-48cc-f4e8-08da69a0b0ad X-MS-Exchange-SLBlob-MailProps: LzDHi3doVoJyICjK/lhaG5LAoOU+C89dhlrgGX533YhMPcLCC0P0QsfpDEoCGlgu02kKDr4I9J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rPWf78iq7L0rhJRaarEvtrhiGSjmzQNL541STgQmuXwiE+b5UXvhfn9FPdYlbFvuApAulj0KJDcpIvdeQgECvlHfdhM+Zj5OPmdFnH6GmlFKG2rAyCWUCV98Lwql6b4MwntTFhtsbvriWkiWSRewuCU9K0A+exKj22ket1/FfvUWKjis81rW4EdgN9Wo/ktrt+jUZ62rOmdW5dP7mUg1ea9O8EwFHAO8DpWJfuRW9LyTetMihhrVEo/4vL3rrPYnqtA7A2HBZiT9UyumbIa/7NH+70eXBZ59t02U3P/T1Hbu1rIn4pQc7Myw8vtKml5Da1OZNJLzTIuJCJkdGu1EPPe7CwII9z65AcWohGcz20utKOQdtAH+tCuRAqd/0htLnouG3q1EaRj+SD2ncecpBINSUcSd3Z2VLQaz+33jK8XjLkF/SMEOkfczbRrkEeTLRjvsec9CcAjvlc8M4KsiV3VLLCg5GExDG7Ncm4ohsdRFyXdbJEQuVJpIvhWNbdzOZxWu/Upb5VuIOKxxMXhVlBrlvzWETzAdqEvrql6bIWaBXnzLLAXc0+VuyrSbTXAHTU2eseJFvuA7TJBbdVJu4QLLNhGpsIa6typYbcqo9N0WX3H79TDEt6swUSaIbYdfg== X-OriginatorOrg: outlook.com X-MS-Exchange-CrossTenant-Network-Message-Id: 4cf08835-c773-48cc-f4e8-08da69a0b0ad X-MS-Exchange-CrossTenant-AuthSource: CY4PR1801MB1910.namprd18.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 19 Jul 2022 16:06:51.2939 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 84df9e7f-e9f6-40af-b435-aaaaaaaaaaaa X-MS-Exchange-CrossTenant-RMS-PersistedConsumerOrg: 00000000-0000-0000-0000-000000000000 X-MS-Exchange-Transport-CrossTenantHeadersStamped: MN2PR18MB2767 X-Spam-Status: No, score=-12.0 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, FREEMAIL_FROM, FREEMAIL_REPLYTO, FREEMAIL_REPLYTO_END_DIGIT, GIT_PATCH_0, RCVD_IN_DNSWL_NONE, SPF_HELO_PASS, SPF_PASS, TXREP, T_FILL_THIS_FORM_SHORT autolearn=ham autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org X-BeenThere: gcc-patches@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Gcc-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Patchwork-Original-From: Immad Mir via Gcc-patches From: Immad Mir Reply-To: mirimnan017@gmail.com Cc: Immad Mir , mirimnan017@gmail.com Errors-To: gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org Sender: "Gcc-patches" This patch adds three new function attributes to GCC that are used for static analysis of usage of file descriptors: 1) __attribute__ ((fd_arg(N))): The attributes may be applied to a function that takes on open file descriptor at refrenced argument N. It indicates that the passed filedescriptor must not have been closed. Therefore, when the analyzer is enabled with -fanalyzer, the analyzer may emit a -Wanalyzer-fd-use-after-close diagnostic if it detects a code path in which a function with this attribute is called with a closed file descriptor. The attribute also indicates that the file descriptor must have been checked for validity before usage. Therefore, analyzer may emit -Wanalyzer-fd-use-without-check diagnostic if it detects a code path in which a function with this attribute is called with a file descriptor that has not been checked for validity. 2) __attribute__((fd_arg_read(N))): The attribute is identical to fd_arg, but with the additional requirement that it might read from the file descriptor, and thus, the file descriptor must not have been opened as write-only. The analyzer may emit a -Wanalyzer-access-mode-mismatch diagnostic if it detects a code path in which a function with this attribute is called on a file descriptor opened with O_WRONLY. 3) __attribute__((fd_arg_write(N))): The attribute is identical to fd_arg_read except that the analyzer may emit a -Wanalyzer-access-mode-mismatch diagnostic if it detects a code path in which a function with this attribute is called on a file descriptor opened with O_RDONLY. gcc/analyzer/ChangeLog: * sm-fd.cc (fd_param_diagnostic): New diagnostic class. (fd_access_mode_mismatch): Change inheritance from fd_diagnostic to fd_param_diagnostic. Add new overloaded constructor. (fd_use_after_close): Likewise. (unchecked_use_of_fd): Likewise and also change name to fd_use_without_check. (double_close): Change name to fd_double_close. (enum access_directions): New. (fd_state_machine::on_stmt): Handle calls to function with the new three function attributes. (fd_state_machine::check_for_fd_attrs): New. (fd_state_machine::on_open): Use the new overloaded constructors of diagnostic classes. gcc/c-family/ChangeLog: * c-attribs.cc: (c_common_attribute_table): add three new attributes namely: fd_arg, fd_arg_read and fd_arg_write. (handle_fd_arg_attribute): New. gcc/ChangeLog: * doc/extend.texi: Add fd_arg, fd_arg_read and fd_arg_write under "Common Function Attributes" section. gcc/testsuite/ChangeLog: * gcc.dg/analyzer/fd-5.c: New test. * c-c++-common/attr-fd.c: New test. Signed-off-by: Immad Mir --- gcc/analyzer/sm-fd.cc | 323 +++++++++++++++++++++------ gcc/c-family/c-attribs.cc | 36 ++- gcc/doc/extend.texi | 34 +++ gcc/testsuite/c-c++-common/attr-fd.c | 18 ++ gcc/testsuite/gcc.dg/analyzer/fd-5.c | 53 +++++ 5 files changed, 398 insertions(+), 66 deletions(-) create mode 100644 gcc/testsuite/c-c++-common/attr-fd.c create mode 100644 gcc/testsuite/gcc.dg/analyzer/fd-5.c diff --git a/gcc/analyzer/sm-fd.cc b/gcc/analyzer/sm-fd.cc index 8e4300b06e2..c577a7db7ea 100644 --- a/gcc/analyzer/sm-fd.cc +++ b/gcc/analyzer/sm-fd.cc @@ -39,10 +39,13 @@ along with GCC; see the file COPYING3. If not see #include "analyzer/analyzer-selftests.h" #include "tristate.h" #include "selftest.h" +#include "stringpool.h" +#include "attribs.h" #include "analyzer/call-string.h" #include "analyzer/program-point.h" #include "analyzer/store.h" #include "analyzer/region-model.h" +#include "bitmap.h" #if ENABLE_ANALYZER @@ -59,6 +62,13 @@ enum access_mode WRITE_ONLY }; +enum access_directions +{ + DIRS_READ_WRITE, + DIRS_READ, + DIRS_WRITE +}; + class fd_state_machine : public state_machine { public: @@ -146,7 +156,7 @@ private: void check_for_open_fd (sm_context *sm_ctxt, const supernode *node, const gimple *stmt, const gcall *call, const tree callee_fndecl, - enum access_direction access_fn) const; + enum access_directions access_fn) const; void make_valid_transitions_on_condition (sm_context *sm_ctxt, const supernode *node, @@ -156,12 +166,17 @@ private: const supernode *node, const gimple *stmt, const svalue *lhs) const; + void check_for_fd_attrs (sm_context *sm_ctxt, const supernode *node, + const gimple *stmt, const tree callee_fndecl, + const char *attr_name, + access_directions fd_attr_access_dir) const; + }; /* Base diagnostic class relative to fd_state_machine. */ class fd_diagnostic : public pending_diagnostic { -public: +public: fd_diagnostic (const fd_state_machine &sm, tree arg) : m_sm (sm), m_arg (arg) { } @@ -220,6 +235,65 @@ protected: tree m_arg; }; +class fd_param_diagnostic : public fd_diagnostic +{ +public: + fd_param_diagnostic (const fd_state_machine &sm, tree arg, tree callee_fndecl, + bool attr, int arg_idx) + : fd_diagnostic (sm, arg), m_callee_fndecl (callee_fndecl), m_attr (attr), + m_arg_idx (arg_idx) + { + } + + fd_param_diagnostic (const fd_state_machine &sm, tree arg, tree callee_fndecl) + : fd_diagnostic (sm, arg), m_callee_fndecl (callee_fndecl), + m_attr (false), m_arg_idx (-1) + { + } + + bool + subclass_equal_p (const pending_diagnostic &base_other) const override + { + const fd_param_diagnostic &sub_other + = (const fd_param_diagnostic &)base_other; + return (same_tree_p (m_arg, sub_other.m_arg) + && m_callee_fndecl == sub_other.m_callee_fndecl + && m_attr == sub_other.m_attr + && m_arg_idx == sub_other.m_arg_idx); + } + + void + inform_filedescriptor_attribute (access_directions fd_dir) + { + + if (m_attr) + switch (fd_dir) + { + case DIRS_READ_WRITE: + inform (DECL_SOURCE_LOCATION (m_callee_fndecl), + "argument %d of %qD must be an open file descriptor", + m_arg_idx + 1, m_callee_fndecl); + break; + case DIRS_WRITE: + inform (DECL_SOURCE_LOCATION (m_callee_fndecl), + "argument %d of %qD must be a read-only file descriptor", + m_arg_idx + 1, m_callee_fndecl); + break; + case DIRS_READ: + inform (DECL_SOURCE_LOCATION (m_callee_fndecl), + "argument %d of %qD must be a write-only file descriptor", + m_arg_idx + 1, m_callee_fndecl); + break; + } + } + +protected: + tree m_callee_fndecl; + bool m_attr; + /* ARG_IDX is 0-based. */ + int m_arg_idx; +}; + class fd_leak : public fd_diagnostic { public: @@ -290,18 +364,25 @@ private: diagnostic_event_id_t m_open_event; }; -class fd_access_mode_mismatch : public fd_diagnostic +class fd_access_mode_mismatch : public fd_param_diagnostic { public: fd_access_mode_mismatch (const fd_state_machine &sm, tree arg, - enum access_direction fd_dir, - const tree callee_fndecl) - : fd_diagnostic (sm, arg), m_fd_dir (fd_dir), - m_callee_fndecl (callee_fndecl) + enum access_directions fd_dir, + const tree callee_fndecl, bool attr, int arg_idx) + : fd_param_diagnostic (sm, arg, callee_fndecl, attr, arg_idx), + m_fd_dir (fd_dir) { } + fd_access_mode_mismatch (const fd_state_machine &sm, tree arg, + enum access_directions fd_dir, + const tree callee_fndecl) + : fd_param_diagnostic (sm, arg, callee_fndecl), m_fd_dir (fd_dir) + { + } + const char * get_kind () const final override { @@ -317,29 +398,25 @@ public: bool emit (rich_location *rich_loc) final override { + bool warned; switch (m_fd_dir) { - case DIR_READ: - return warning_at (rich_loc, get_controlling_option (), + case DIRS_READ: + warned = warning_at (rich_loc, get_controlling_option (), "%qE on % file descriptor %qE", m_callee_fndecl, m_arg); - case DIR_WRITE: - return warning_at (rich_loc, get_controlling_option (), + break; + case DIRS_WRITE: + warned = warning_at (rich_loc, get_controlling_option (), "%qE on % file descriptor %qE", m_callee_fndecl, m_arg); + break; default: gcc_unreachable (); } - } - - bool - subclass_equal_p (const pending_diagnostic &base_other) const override - { - const fd_access_mode_mismatch &sub_other - = (const fd_access_mode_mismatch &)base_other; - return (same_tree_p (m_arg, sub_other.m_arg) - && m_callee_fndecl == sub_other.m_callee_fndecl - && m_fd_dir == sub_other.m_fd_dir); + if (warned) + inform_filedescriptor_attribute (m_fd_dir); + return warned; } label_text @@ -347,10 +424,10 @@ public: { switch (m_fd_dir) { - case DIR_READ: + case DIRS_READ: return ev.formatted_print ("%qE on % file descriptor %qE", m_callee_fndecl, m_arg); - case DIR_WRITE: + case DIRS_WRITE: return ev.formatted_print ("%qE on % file descriptor %qE", m_callee_fndecl, m_arg); default: @@ -359,21 +436,20 @@ public: } private: - enum access_direction m_fd_dir; - const tree m_callee_fndecl; + enum access_directions m_fd_dir; }; -class double_close : public fd_diagnostic +class fd_double_close : public fd_diagnostic { public: - double_close (const fd_state_machine &sm, tree arg) : fd_diagnostic (sm, arg) + fd_double_close (const fd_state_machine &sm, tree arg) : fd_diagnostic (sm, arg) { } const char * get_kind () const final override { - return "double_close"; + return "fd_double_close"; } int @@ -418,12 +494,18 @@ private: diagnostic_event_id_t m_first_close_event; }; -class fd_use_after_close : public fd_diagnostic +class fd_use_after_close : public fd_param_diagnostic { public: + fd_use_after_close (const fd_state_machine &sm, tree arg, + const tree callee_fndecl, bool attr, int arg_idx) + : fd_param_diagnostic(sm, arg, callee_fndecl, attr, arg_idx) + { + } + fd_use_after_close (const fd_state_machine &sm, tree arg, const tree callee_fndecl) - : fd_diagnostic (sm, arg), m_callee_fndecl (callee_fndecl) + : fd_param_diagnostic(sm, arg, callee_fndecl) { } @@ -442,9 +524,13 @@ public: bool emit (rich_location *rich_loc) final override { - return warning_at (rich_loc, get_controlling_option (), + bool warned; + warned = warning_at (rich_loc, get_controlling_option (), "%qE on closed file descriptor %qE", m_callee_fndecl, m_arg); + if (warned) + inform_filedescriptor_attribute (DIRS_READ_WRITE); + return warned; } label_text @@ -466,32 +552,37 @@ public: describe_final_event (const evdesc::final_event &ev) final override { if (m_first_close_event.known_p ()) - return ev.formatted_print ( - "%qE on closed file descriptor %qE; %qs was at %@", m_callee_fndecl, - m_arg, "close", &m_first_close_event); - else - return ev.formatted_print ("%qE on closed file descriptor %qE", - m_callee_fndecl, m_arg); + return ev.formatted_print ( + "%qE on closed file descriptor %qE; %qs was at %@", m_callee_fndecl, + m_arg, "close", &m_first_close_event); + else + return ev.formatted_print ("%qE on closed file descriptor %qE", + m_callee_fndecl, m_arg); } private: diagnostic_event_id_t m_first_close_event; - const tree m_callee_fndecl; }; -class unchecked_use_of_fd : public fd_diagnostic +class fd_use_without_check : public fd_param_diagnostic { public: - unchecked_use_of_fd (const fd_state_machine &sm, tree arg, + fd_use_without_check (const fd_state_machine &sm, tree arg, + const tree callee_fndecl, bool attr, int arg_idx) + : fd_param_diagnostic(sm, arg, callee_fndecl, attr, arg_idx) + { + } + + fd_use_without_check (const fd_state_machine &sm, tree arg, const tree callee_fndecl) - : fd_diagnostic (sm, arg), m_callee_fndecl (callee_fndecl) + : fd_param_diagnostic(sm, arg, callee_fndecl) { } const char * get_kind () const final override { - return "unchecked_use_of_fd"; + return "fd_use_without_check"; } int @@ -503,18 +594,12 @@ public: bool emit (rich_location *rich_loc) final override { - return warning_at (rich_loc, get_controlling_option (), - "%qE on possibly invalid file descriptor %qE", - m_callee_fndecl, m_arg); - } - - bool - subclass_equal_p (const pending_diagnostic &base_other) const override - { - const unchecked_use_of_fd &sub_other - = (const unchecked_use_of_fd &)base_other; - return (same_tree_p (m_arg, sub_other.m_arg) - && m_callee_fndecl == sub_other.m_callee_fndecl); + bool warned; + warned = warning_at (rich_loc, get_controlling_option (), + "%qE on possibly invalid file descriptor %qE", + m_callee_fndecl, m_arg); + if (warned) + inform_filedescriptor_attribute (DIRS_READ_WRITE); } label_text @@ -542,7 +627,7 @@ public: private: diagnostic_event_id_t m_first_open_event; - const tree m_callee_fndecl; + }; fd_state_machine::fd_state_machine (logger *logger) @@ -647,11 +732,119 @@ fd_state_machine::on_stmt (sm_context *sm_ctxt, const supernode *node, on_read (sm_ctxt, node, stmt, call, callee_fndecl); return true; } // "read" + + + { + // Handle __attribute__((fd_arg)) + + check_for_fd_attrs (sm_ctxt, node, stmt, callee_fndecl, "fd_arg", DIRS_READ_WRITE); + + // Handle __attribute__((fd_arg_read)) + + check_for_fd_attrs (sm_ctxt, node, stmt, callee_fndecl, "fd_arg_read", DIRS_READ); + + // Handle __attribute__((fd_arg_write)) + + check_for_fd_attrs (sm_ctxt, node, stmt, callee_fndecl, "fd_arg_write", DIRS_WRITE); + + return true; + } + } return false; } +void +fd_state_machine::check_for_fd_attrs ( + sm_context *sm_ctxt, const supernode *node, const gimple *stmt, + const tree callee_fndecl, const char *attr_name, + access_directions fd_attr_access_dir) const +{ + + tree attrs = TYPE_ATTRIBUTES (TREE_TYPE (callee_fndecl)); + attrs = lookup_attribute (attr_name, attrs); + if (!attrs) + return; + + if (!TREE_VALUE (attrs)) + return; + + auto_bitmap argmap; + + for (tree idx = TREE_VALUE (attrs); idx; idx = TREE_CHAIN (idx)) + { + unsigned int val = TREE_INT_CST_LOW (TREE_VALUE (idx)) - 1; + bitmap_set_bit (argmap, val); + } + if (bitmap_empty_p (argmap)) + return; + + for (unsigned i = 0; i < gimple_call_num_args (stmt); i++) + { + + unsigned int arg_idx = i; + tree arg = gimple_call_arg (stmt, arg_idx); + tree diag_arg = sm_ctxt->get_diagnostic_tree (arg); + state_t state = sm_ctxt->get_state (stmt, arg); + bool bit_set = bitmap_bit_p (argmap, arg_idx); + if (TREE_CODE (TREE_TYPE (arg)) != INTEGER_TYPE) + continue; + if (bit_set) // Check if arg_idx is marked by any of the file descriptor + // attributes + { + + if (is_closed_fd_p (state)) + { + + sm_ctxt->warn (node, stmt, arg, + new fd_use_after_close (*this, diag_arg, + callee_fndecl, true, + arg_idx)); + continue; + } + + if (!(is_valid_fd_p (state) || (state == m_stop))) + { + if (!is_constant_fd_p (state)) + sm_ctxt->warn (node, stmt, arg, + new fd_use_without_check (*this, diag_arg, + callee_fndecl, true, + arg_idx)); + } + + switch (fd_attr_access_dir) + { + case DIRS_READ_WRITE: + break; + case DIRS_READ: + + if (is_writeonly_fd_p (state)) + { + sm_ctxt->warn ( + node, stmt, arg, + new fd_access_mode_mismatch (*this, diag_arg, DIRS_WRITE, + callee_fndecl, true, i)); + } + + break; + case DIRS_WRITE: + + if (is_readonly_fd_p (state)) + { + sm_ctxt->warn ( + node, stmt, arg, + new fd_access_mode_mismatch (*this, diag_arg, DIRS_READ, + callee_fndecl, true, i)); + } + + break; + } + } + } +} + + void fd_state_machine::on_open (sm_context *sm_ctxt, const supernode *node, const gimple *stmt, const gcall *call) const @@ -706,7 +899,7 @@ fd_state_machine::on_close (sm_context *sm_ctxt, const supernode *node, if (is_closed_fd_p (state)) { - sm_ctxt->warn (node, stmt, arg, new double_close (*this, diag_arg)); + sm_ctxt->warn (node, stmt, arg, new fd_double_close (*this, diag_arg)); sm_ctxt->set_next_state (stmt, arg, m_stop); } } @@ -715,21 +908,21 @@ fd_state_machine::on_read (sm_context *sm_ctxt, const supernode *node, const gimple *stmt, const gcall *call, const tree callee_fndecl) const { - check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl, DIR_READ); + check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl, DIRS_READ); } void fd_state_machine::on_write (sm_context *sm_ctxt, const supernode *node, const gimple *stmt, const gcall *call, const tree callee_fndecl) const { - check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl, DIR_WRITE); + check_for_open_fd (sm_ctxt, node, stmt, call, callee_fndecl, DIRS_WRITE); } void fd_state_machine::check_for_open_fd ( sm_context *sm_ctxt, const supernode *node, const gimple *stmt, const gcall *call, const tree callee_fndecl, - enum access_direction callee_fndecl_dir) const + enum access_directions callee_fndecl_dir) const { tree arg = gimple_call_arg (call, 0); tree diag_arg = sm_ctxt->get_diagnostic_tree (arg); @@ -748,30 +941,32 @@ fd_state_machine::check_for_open_fd ( if (!is_constant_fd_p (state)) sm_ctxt->warn ( node, stmt, arg, - new unchecked_use_of_fd (*this, diag_arg, callee_fndecl)); + new fd_use_without_check (*this, diag_arg, callee_fndecl)); } switch (callee_fndecl_dir) { - case DIR_READ: + case DIRS_READ: if (is_writeonly_fd_p (state)) { tree diag_arg = sm_ctxt->get_diagnostic_tree (arg); sm_ctxt->warn (node, stmt, arg, new fd_access_mode_mismatch ( - *this, diag_arg, DIR_WRITE, callee_fndecl)); + *this, diag_arg, DIRS_WRITE, callee_fndecl)); } break; - case DIR_WRITE: + case DIRS_WRITE: if (is_readonly_fd_p (state)) { tree diag_arg = sm_ctxt->get_diagnostic_tree (arg); sm_ctxt->warn (node, stmt, arg, new fd_access_mode_mismatch ( - *this, diag_arg, DIR_READ, callee_fndecl)); + *this, diag_arg, DIRS_READ, callee_fndecl)); } break; + default: + gcc_unreachable (); } } } diff --git a/gcc/c-family/c-attribs.cc b/gcc/c-family/c-attribs.cc index c8d96723f4c..a04cc541f95 100644 --- a/gcc/c-family/c-attribs.cc +++ b/gcc/c-family/c-attribs.cc @@ -173,6 +173,7 @@ static tree handle_objc_nullability_attribute (tree *, tree, tree, int, bool *); static tree handle_signed_bool_precision_attribute (tree *, tree, tree, int, bool *); static tree handle_retain_attribute (tree *, tree, tree, int, bool *); +static tree handle_fd_arg_attribute (tree *, tree, tree, int, bool *); /* Helper to define attribute exclusions. */ #define ATTR_EXCL(name, function, type, variable) \ @@ -426,7 +427,7 @@ const struct attribute_spec c_common_attribute_table[] = { "tls_model", 1, 1, true, false, false, false, handle_tls_model_attribute, NULL }, { "nonnull", 0, -1, false, true, true, false, - handle_nonnull_attribute, NULL }, + handle_nonnull_attribute, NULL }, { "nonstring", 0, 0, true, false, false, false, handle_nonstring_attribute, NULL }, { "nothrow", 0, 0, true, false, false, false, @@ -555,7 +556,13 @@ const struct attribute_spec c_common_attribute_table[] = handle_dealloc_attribute, NULL }, { "tainted_args", 0, 0, true, false, false, false, handle_tainted_args_attribute, NULL }, - { NULL, 0, 0, false, false, false, false, NULL, NULL } + { NULL, 0, 0, false, false, false, false, NULL, NULL }, + { "fd_arg", 1, 1, false, true, true, false, + handle_fd_arg_attribute, NULL}, + { "fd_arg_read", 1, 1, false, true, true, false, + handle_fd_arg_attribute, NULL}, + { "fd_arg_write", 1, 1, false, true, true, false, + handle_fd_arg_attribute, NULL}, }; /* Give the specifications for the format attributes, used by C and all @@ -4521,6 +4528,31 @@ handle_nonnull_attribute (tree *node, tree name, return NULL_TREE; } +/* Handle the "fd_arg", "fd_arg_read" and "fd_arg_write" attributes */ + +static tree +handle_fd_arg_attribute (tree *node, tree name, tree args, + int ARG_UNUSED (flags), bool *no_add_attrs) +{ + tree type = *node; + if (!args) + { + if (!prototype_p (type)) + { + error ("%qE attribute without arguments on a non-prototype", name); + *no_add_attrs = true; + } + return NULL_TREE; + } + + if (tree val = positional_argument (*node, name, TREE_VALUE (args), + INTEGER_TYPE)) + return NULL_TREE; + + *no_add_attrs = true; + return NULL_TREE; +} + /* Handle the "nonstring" variable attribute. */ static tree diff --git a/gcc/doc/extend.texi b/gcc/doc/extend.texi index dfbe33ac652..7945d769e23 100644 --- a/gcc/doc/extend.texi +++ b/gcc/doc/extend.texi @@ -3007,6 +3007,40 @@ produced by @command{gold}. For other linkers that cannot generate resolution file, explicit @code{externally_visible} attributes are still necessary. +@item fd_arg +@cindex @code{fd_arg} function attribute +The @code{fd_arg} attribute may be applied to a function that takes an open +file descriptor at referenced argument @var{N}. + +It indicates that the passed filedescriptor must not have been closed. +Therefore, when the analyzer is enabled with @option{-fanalyzer}, the +analyzer may emit a @option{-Wanalyzer-fd-use-after-close} diagnostic +if it detects a code path in which a function with this attribute is +called with a closed file descriptor. + +The attribute also indicates that the file descriptor must have been checked for +validity before usage. Therefore, analyzer may emit +@option{-Wanalyzer-fd-use-without-check} diagnostic if it detects a code path in +which a function with this attribute is called with a file descriptor that has +not been checked for validity. + +@item fd_arg_read +@cindex @code{fd_arg_read} function attribute +The @code{fd_arg_read} is identical to @code{fd_arg}, but with the additional +requirement that it might read from the file descriptor, and thus, the file +descriptor must not have been opened as write-only. + +The analyzer may emit a @option{-Wanalyzer-access-mode-mismatch} +diagnostic if it detects a code path in which a function with this +attribute is called on a file descriptor opened with @code{O_WRONLY}. + +@item fd_arg_write +@cindex @code{fd_arg_write} function attribute +The @code{fd_arg_write} is identical to @code{fd_arg_read} except that the +analyzer may emit a @option{-Wanalyzer-access-mode-mismatch} diagnostic if +it detects a code path in which a function with this attribute is called on a +file descriptor opened with @code{O_RDONLY}. + @item flatten @cindex @code{flatten} function attribute Generally, inlining into a function is limited. For a function marked with diff --git a/gcc/testsuite/c-c++-common/attr-fd.c b/gcc/testsuite/c-c++-common/attr-fd.c new file mode 100644 index 00000000000..292c329856e --- /dev/null +++ b/gcc/testsuite/c-c++-common/attr-fd.c @@ -0,0 +1,18 @@ + +int not_a_fn __attribute__ ((fd_arg(1))); /* { dg-warning "'fd_arg' attribute only applies to function types" } */ + +void f (char *p) __attribute__ ((fd_arg(1))); /* { dg-warning "'fd_arg' attribute argument value '1' refers to parameter type 'char \\\*'" } */ + + +int not_a_fn_b __attribute__ ((fd_arg_read(1))); /* { dg-warning "'fd_arg_read' attribute only applies to function types" } */ + +void g (char *p) __attribute__ ((fd_arg_read(1))); /* { dg-warning "'fd_arg_read' attribute argument value '1' refers to parameter type 'char \\\*'" } */ + + +int not_a_fn_c __attribute__ ((fd_arg_write(1))); /* { dg-warning "'fd_arg_write' attribute only applies to function types" } */ + +void f (char *p) __attribute__ ((fd_arg_write(1))); /* { dg-warning "'fd_arg_write' attribute argument value '1' refers to parameter type 'char \\\*'" } */ + + +void fn_a (int fd) __attribute__ ((fd_arg(0))); /* { dg-warning "'fd_arg' attribute argument value '0' does not refer to a function parameter" } */ +void fd_a_1 (int fd) __attribute__ ((fd_arg("notint"))); /* { dg-warning "'fd_arg' attribute argument has type 'char\\\[7\\\]'" } */ diff --git a/gcc/testsuite/gcc.dg/analyzer/fd-5.c b/gcc/testsuite/gcc.dg/analyzer/fd-5.c new file mode 100644 index 00000000000..6287ddd38fc --- /dev/null +++ b/gcc/testsuite/gcc.dg/analyzer/fd-5.c @@ -0,0 +1,53 @@ +int open(const char *, int mode); +void close(int fd); +int write (int fd, void *buf, int nbytes); +int read (int fd, void *buf, int nbytes); + +#define O_RDONLY 0 +#define O_WRONLY 1 +#define O_RDWR 2 + +void f (int fd) __attribute__((fd_arg(1))); /* { dg-message "argument 1 of 'f' must be an open file descriptor" } */ + +void +test_1 (const char *path) +{ + int fd = open (path, O_RDWR); + close(fd); + f(fd); /* { dg-warning "'f' on closed file descriptor 'fd'" } */ + /* { dg-message "\\(3\\) 'f' on closed file descriptor 'fd'; 'close' was at \\(2\\)" "" { target *-*-* } .-1 } */ +} + +void g (int fd) __attribute__((fd_arg_read(1))); /* { dg-message "argument 1 of 'g' must be a read-only file descriptor" } */ + +void +test_2 (const char *path) +{ + int fd = open (path, O_WRONLY); + if (fd != -1) + { + g (fd); /* { dg-warning "'g' on 'write-only' file descriptor 'fd'" } */ + } + close (fd); +} + +void h (int fd) __attribute__((fd_arg_write(1))); /* { dg-message "argument 1 of 'h' must be a write-only file descriptor" } */ +void +test_3 (const char *path) +{ + int fd = open (path, O_RDONLY); + if (fd != -1) + { + h (fd); /* { dg-warning "'h' on 'read-only' file descriptor 'fd'" } */ + } + close(fd); +} + +void ff (int fd) __attribute__((fd_arg(1))); /* { dg-message "argument 1 of 'ff' must be an open file descriptor" } */ + +void test_4 (const char *path) +{ + int fd = open (path, O_RDWR); + ff (fd); /* { dg-warning "'ff' on possibly invalid file descriptor 'fd'" } */ + close(fd); +} \ No newline at end of file