From patchwork Fri Aug 4 19:44:29 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Qing Zhao X-Patchwork-Id: 1817147 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=gcc.gnu.org (client-ip=8.43.85.97; helo=server2.sourceware.org; envelope-from=gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org; receiver=) Authentication-Results: legolas.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=s3SnOmEl; dkim-atps=neutral Received: from server2.sourceware.org (server2.sourceware.org [8.43.85.97]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (P-384) server-digest SHA384) (No client certificate requested) by legolas.ozlabs.org (Postfix) with ESMTPS id 4RHblt25Fmz1yYl for ; Sat, 5 Aug 2023 05:45:14 +1000 (AEST) Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 50855385DC00 for ; Fri, 4 Aug 2023 19:45:12 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 50855385DC00 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gcc.gnu.org; s=default; t=1691178312; bh=i49AFLEVZvwu4jCarxJNmjtkp+zBwsZq34z1cGYcPio=; h=To:Cc:Subject:Date:In-Reply-To:References:List-Id: List-Unsubscribe:List-Archive:List-Post:List-Help:List-Subscribe: From:Reply-To:From; b=s3SnOmElMRZhiXNyJpdFPuEK7S57ph87BRSu+mKIbHkDlfTi2yrbTk0kpH/6zw2XG DEol8mv9oBNISxZZBrSutc++cHhIR0ZWS82+tShctKdTz3zr9o6W9FCnRGz6mjsn7F 6Z4RQj1spwazjxMo/WIe/Qc1gD0IIiNoCa0Lm+Lg= X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mx0b-00069f02.pphosted.com (mx0b-00069f02.pphosted.com [205.220.177.32]) by sourceware.org (Postfix) with ESMTPS id 87493385734F for ; Fri, 4 Aug 2023 19:44:49 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 87493385734F Received: from pps.filterd (m0246631.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.17.1.19/8.17.1.19) with ESMTP id 374JCnQC019646; Fri, 4 Aug 2023 19:44:47 GMT Received: from iadpaimrmta01.imrmtpd1.prodappiadaev1.oraclevcn.com (iadpaimrmta01.appoci.oracle.com [130.35.100.223]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 3s79vbxkk9-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Fri, 04 Aug 2023 19:44:46 +0000 Received: from pps.filterd (iadpaimrmta01.imrmtpd1.prodappiadaev1.oraclevcn.com [127.0.0.1]) by iadpaimrmta01.imrmtpd1.prodappiadaev1.oraclevcn.com (8.17.1.19/8.17.1.19) with ESMTP id 374ICsIg000551; Fri, 4 Aug 2023 19:44:46 GMT Received: from nam10-bn7-obe.outbound.protection.outlook.com (mail-bn7nam10lp2109.outbound.protection.outlook.com [104.47.70.109]) by iadpaimrmta01.imrmtpd1.prodappiadaev1.oraclevcn.com (PPS) with ESMTPS id 3s8kpkuvq1-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Fri, 04 Aug 2023 19:44:45 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=cwc9c6Ny7SI2lzTDqz7KwX++MgEXwcbfNIgVJaN42uz4fAM1yOQY2B8QXE5IVwp+oLdoh8tnfk9W2tsWppV+i34wU+523lOClOPDenhJ5a+9DSyV+lTfngIwRU/ezZ6oLuKiNZHZ/OA5Tr6po3q2PYoUAH0o5T4Thkd8gaJ1OfeARmdg/jW7IlwPJHrWQuV34H9jYON4+vAPzAB27Ag70Gnpjw76xUZgvWqkHsrUqpmxMUptUxK0eB4AKYffZ68zmWITloTpknwVQy408vmrQcUNIbl7thhcfLJ8emClQeHrY04699FT+r4spO/MpZxI2UrSu1dl/xx5dwj2UmnKQg== 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=i49AFLEVZvwu4jCarxJNmjtkp+zBwsZq34z1cGYcPio=; b=PkMXSHXM2msvvFc6qrhNRj93uswgpX4oVV7cOYQztpj7DntXiX/jycLIVa4s5zNWUswxHviamK5JnFjgE9zvY5M7vz/XRql/zrji9Bli45veEAEHMLa7Wpg+2whAUwwSnGl5vrc2wqP3N/FGJ52FYLdpNFge9JYi0wSfgfDzam88J+XMerfMD1aADYIZhSHeXAeFEOfgGQgQGqyA13eg3Ripy+jVedwXu1kr1+8ivThwJD4WgEs6eJkifN8kMhPFu7n4b1HiDqe1fyWuLBB+DOJdCbm4LuJEvcRaVcAnCrAaPQduz0nRRPiSTgvUYE2CkDGb60kCdFl5E0t27VTWrw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none Received: from CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) by MW6PR10MB7590.namprd10.prod.outlook.com (2603:10b6:303:24c::11) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.6631.47; Fri, 4 Aug 2023 19:44:43 +0000 Received: from CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::5afd:d02a:38ef:94ba]) by CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::5afd:d02a:38ef:94ba%7]) with mapi id 15.20.6652.020; Fri, 4 Aug 2023 19:44:43 +0000 To: joseph@codesourcery.com, richard.guenther@gmail.com, jakub@redhat.com, gcc-patches@gcc.gnu.org Cc: keescook@chromium.org, siddhesh@gotplt.org, uecker@tugraz.at, isanbard@gmail.com, Qing Zhao Subject: [V2][PATCH 1/3] Provide counted_by attribute to flexible array member field (PR108896) Date: Fri, 4 Aug 2023 19:44:29 +0000 Message-Id: <20230804194431.993958-2-qing.zhao@oracle.com> X-Mailer: git-send-email 2.31.1 In-Reply-To: <20230804194431.993958-1-qing.zhao@oracle.com> References: <20230804194431.993958-1-qing.zhao@oracle.com> X-ClientProxiedBy: BYAPR11CA0057.namprd11.prod.outlook.com (2603:10b6:a03:80::34) To CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: CH2PR10MB4344:EE_|MW6PR10MB7590:EE_ X-MS-Office365-Filtering-Correlation-Id: 58c1ff79-0577-4a85-a9eb-08db95233ff5 X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; X-Microsoft-Antispam-Message-Info: BL/W7mmIELyIDLdNkZwDIlrIe2lImfvgPDSVL+71ky6DmgLXKuVRDnC8iGhzXNbHnV5bbqr8RIN1Oyz5lTyX9GCgLcnft3JxnGrUwkoy5xUSVeV3N+4riUOCmQeu7lSrbdVp0zMGCoYh2icH+dTxcCPwQ8VsPlCnUYActlRdyO/Y5U8/QlgsXMRoaZOEPLbpk9RRTEYHYtHNL9gTTw7gXyB7NrprieZ2Z8LlS0kveyBfvopcw8f1++rVkmeY+W8yx09KfI0S+19IOjmw1/R6b4S4uXcsVIYnuIPzYC/IIZfxdfoj7MzJztEiAhf1tIcyS1q51c+/yL+CD7hdU+PXfGohRU7G+JeVDTuwAC3mFwJREfKl7FaZTaqTPnNn5PkNsiaiQQGt+ZNaASpyJnsotiMt4OLhfZQkyp49SoZ/YQ5bt6XrwYtQiJ/zkAkaz1/gY9AFd1T34PuX0id1lOCY31gUGfhxWD4elUuqoIdGeFK3eEwYLJGUI/+GoVIeahjmISbew7nU8tLERPmgHMpHuf945N01dqBxBOGLoZh0k1o= X-Forefront-Antispam-Report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:CH2PR10MB4344.namprd10.prod.outlook.com; PTR:; CAT:NONE; SFS:(13230028)(346002)(39860400002)(136003)(376002)(396003)(366004)(451199021)(1800799003)(186006)(83380400001)(1076003)(2616005)(107886003)(6506007)(26005)(8676002)(66556008)(2906002)(316002)(30864003)(66946007)(5660300002)(66476007)(4326008)(41300700001)(8936002)(44832011)(6486002)(6512007)(6666004)(478600001)(38100700002)(36756003)(86362001)(84970400001); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: K4H+jf4GI3ImtknjnrePFprrCvNkoJcj1vPp930Y1a6gjCBi4K5g11uFAHHE0LgoZS2AiO5y3+zZePw1JWpYKuW+7QW+ltUylvMvAFBSzTjCMMCp2ItSOeQNdsjVTxRJA3UuS5VtZmQZ/Mb3QD956YvEZyoIvUFvi0mwcA48v/4ZnMPtG3xOyT1G52K7JXlT6tL2YakN6YMFmvFFMK4dB877rvv+sfUJCh2Rv3G+UtMeuKkVnkGSUf5OqB6PEPVzainwBlqB8G7GGSWaAZDDIFa3TQDBuui5bK3/v0vEk+rAt6ooyVzFU/lsCjqRYsH55q7eBdiJTXrRDyWz+fyADnoaKzZvvir1FogLNuVPJGCap2vgEn1ufTTFZKv8s4vQEN/rhSsw1f6clN7mCyYAkFKVsncgkf+AlrFN/YCOrvs0vCMEHumgeLX4FFs/QdSJbbyCMY8N9W3gSoZSA6KBHzjMryfPWJZAB9EnRMJO+HsMXE+hNedAFXsNhLGk0qbDhDGks+gD1IOqzctS5YaN2LTKPnkLCXQ0Phh9BNY8XZ3R4/ow80lL6HoKGzlMj2Hq4vfJdjAjojhtP5dOO/VuOL5StFo+XEsPmLSQuePlKTB502kG8U9K+vhREC3I1M0cdNrT3IR4wiplnHXpMeK+zb43HED8QoTjHYUj36O6uiNNE3lUXAGrd2E1ZrFtVXxXF7iurqUiLIGpJzqvz0U7TwYuqyOx8ZP6piGql4g7r1L53uc3Zk8OnpKcGc1H8CL8YMGcBT8heLFQN+hgICGTsBPn1J+yZsqU0l47UxmZK52rF3BF//GdFMetqSNOQpU+uBqVW+WR4OL2kzGvt7Nlg/Ii4FfeagO242CR7aKZEZOUd+YY1/OHG++AAihjFoMfBHirPSrxl1N5tuGWTe1mBcgaOqbVT/4rHCdP8SU/ff1ePNDVEVEMOGV2+5cpozUR+1+xvtlAEkBkG4f1RZ1GiCBN7kG1FlpnHBO0Vg0xyv6SBkYzg4F0j9+VBENhWa+t5C1Xl+rqqbz4FsRiQ9yPMjTk8jq+AkXvfqe669R/NXM6YzqjQVRq9qlaAPrIqYAI2WAKcuZNM5u64UCN441GOY/a+YpuwemGgVjLFyPO+zopJeIquQvjEZdaqiFoY0xTFvS2Sfe9XLoX9uTL0bXck2PSb2ATDteOeRnyP+mQVh7jDpYFNkevZJj9ui0vb0hICFEeooVDqlF2GzPdhwLQDyqkWNZ7UmAm5qi0tviamGSgtQ96OrEnNEVM985t+gvMCVmRt94g+bfH2UMXjamqeE5zXE85KTSubHcMVeE20ZdKYtvlLyXaMombK3EeEdeQ308KeJCD6wTt5Mx6OWTZgvhWMfMGQJUZiGkXLJ0GXzNQ19Fs5D0P9OX8XDbNdQErGzJpElvRFZxdYMx4j4eTMrThrG9czz+48dwWYhIsLbH1RjEIkAZ2YKxQ9Z0hHDbc28xmSkAsr+MJQow4O/jtbMTUtadlfmmHJfteYPxwXcN5D9lOws/v8vhaWp2SYwIbMLJ+gbXYco4OAFAM2KQUl5jXQeq7Mol7IIKZ5G1KHnXBDJONXyawtVVHNLWmGUK4 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: 4jtVeUtMuE8dah5ZEY8Eago5RFa+ybg/XbIHHz428Ja+xj8u9cuvnpjWYKTDRbq0txNsYCRJ+aN8XtY7H+HLrUXm2T8S/s/AzrP0p//41poZpW2g4BHz4ObRxPSMhbzL1Q3Qk3AUuaJ5y9qHrbPvWZ1/B8b00umJQ5Ttr2ltF5DTPqA3UvuE+l38Wc5rsSD36AjTKYWRDQ961jz3W0Jrf+FpAGBldgZUPCo7lsCRqrESnSuvx9wsxw2kaedQnsHwREyEQZ3MieabM/MSU/SVsKR8tEZOUM+yPTCB75rFiQgI9L+mITH0gnmH56IZlk11YFStL6VnlISLdXKJEj4pbU+WUhYD3/R8M9A7mmCxD74WEtPt8YcdYFo/rAQ9+p9i7VEuCwqbhglzQUQzM2lnfoEi1f5Yqvqa/2jwjUc1XrAJk/sKRheT6MCC73Z/2mPOW9r3yl6v5R3JXo5fShWM9PNRRGFBaBJqcghUqOd5wcVhfvZY4bJMG2D+8aKEnUFdr0yU+rjK7Qv06/C8HHwUm6tk+Ag6EjYzeg5RFYeZjRMOmA3NSIqzA6IBhr9Er7gSD+T98FXCYq+E2GGu1SIyt+rQd3EYcalU481hVLyo6sao0jcyA3LCp8w5Sp91hRKiqr29c1Hv+T4GTttsK94biacOKMwclW9O2lnQ4DyEqPs31rcRFM/Ur6Pl5tVHD7viIKUEkEpAbYUY5JNsxKowin3VSmELDICOZEdfCpjtsCtXPoMto4FfFvRHoYHMNIx0LrK+4GV6CymrgKkQiI2Dpya278eC8IsWG/zvcJZ9i+0pWWjitd17OWGbkUzmTkjgg4yjI+07DgdMlhCX+Ylz1RinhetfNJU011DNoHBVyVjfbVFTPveIHNradZK3CLI4tLNhTPDeJJ4BC4i3atK7RDWCX2vYQBrUAK5I3fthMXDFo1aQ60HN2ase92hgcnRQ X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 58c1ff79-0577-4a85-a9eb-08db95233ff5 X-MS-Exchange-CrossTenant-AuthSource: CH2PR10MB4344.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 04 Aug 2023 19:44:43.4548 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: D0ueFkQ5uSkUBRtzDdguSvuMn6gjBhZq/oHbSkIoGip1l+etf9k45mwyyaPMr5GhW3O+JcwZhNIEf+FJZcbotA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MW6PR10MB7590 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.267,Aquarius:18.0.957,Hydra:6.0.591,FMLib:17.11.176.26 definitions=2023-08-04_20,2023-08-03_01,2023-05-22_02 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 mlxlogscore=973 spamscore=0 bulkscore=0 adultscore=0 phishscore=0 mlxscore=0 suspectscore=0 malwarescore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2306200000 definitions=main-2308040177 X-Proofpoint-GUID: sMleu66DWAAU_aoRWcehw0bG7KmX93Ab X-Proofpoint-ORIG-GUID: sMleu66DWAAU_aoRWcehw0bG7KmX93Ab X-Spam-Status: No, score=-11.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, RCVD_IN_DNSWL_LOW, RCVD_IN_MSPIKE_H5, RCVD_IN_MSPIKE_WL, SPF_HELO_NONE, SPF_NONE, TXREP 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: Qing Zhao via Gcc-patches From: Qing Zhao Reply-To: Qing Zhao Errors-To: gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org Sender: "Gcc-patches" 'counted_by (COUNT)' The 'counted_by' attribute may be attached to the flexible array member of a structure. It indicates that the number of the elements of the array is given by the field named "COUNT" in the same structure as the flexible array member. GCC uses this information to improve the results of the array bound sanitizer and the '__builtin_dynamic_object_size'. For instance, the following code: struct P { size_t count; int array[] __attribute__ ((counted_by (count))); } *p; specifies that the 'array' is a flexible array member whose number of elements is given by the field 'count' in the same structure. The field that represents the number of the elements should have an integer type. An explicit 'counted_by' annotation defines a relationship between two objects, 'p->array' and 'p->count', that 'p->array' has _at least_ 'p->count' number of elements available. This relationship must hold even after any of these related objects are updated. It's the user's responsibility to make sure this relationship to be kept all the time. Otherwise the results of the array bound sanitizer and the '__builtin_dynamic_object_size' might be incorrect. For instance, in the following example, the allocated array has less elements than what's specified by the 'sbuf->count', this is an user error. As a result, out-of-bounds access to the array might not be detected. #define SIZE_BUMP 10 struct P *sbuf; void alloc_buf (size_t nelems) { sbuf = (int *) malloc (sizeof (struct P) + sizeof (int) * nelems); sbuf->count = nelems + SIZE_BUMP; /* This is invalid when the sbuf->array has less than sbuf->count elements. */ } In the following example, the 2nd update to the field 'sbuf->count' of the above structure will permit out-of-bounds access to the array 'sbuf>array' as well. #define SIZE_BUMP 10 struct P *sbuf; void alloc_buf (size_t nelems) { sbuf = (int *) malloc (sizeof (struct P) + sizeof (int) * (nelems + SIZE_BUMP)); sbuf->count = nelems; /* This is valid when the sbuf->array has at least sbuf->count elements. */ } void use_buf (int index) { sbuf->count = sbuf->count + SIZE_BUMP + 1; /* Now the value of sbuf->count is larger than the number of elements of sbuf->array. */ sbuf->array[index] = 0; /* then the out-of-bound access to this array might not be detected. */ } gcc/c-family/ChangeLog: PR C/108896 * c-attribs.cc (handle_counted_by_attribute): New function. (attribute_takes_identifier_p): Add counted_by attribute to the list. * c-common.cc (c_flexible_array_member_type_p): ...To this. * c-common.h (c_flexible_array_member_type_p): New prototype. gcc/c/ChangeLog: PR C/108896 * c-decl.cc (flexible_array_member_type_p): Renamed and moved to... (add_flexible_array_elts_to_size): Use renamed function. (is_flexible_array_member_p): Use renamed function. (verify_counted_by_attribute): New function. (finish_struct): Use renamed function and verify counted_by attribute. gcc/ChangeLog: PR C/108896 * doc/extend.texi: Document attribute counted_by. * tree.cc (get_named_field): New function. * tree.h (get_named_field): New prototype. gcc/testsuite/ChangeLog: PR C/108896 * gcc.dg/flex-array-counted-by.c: New test. --- gcc/c-family/c-attribs.cc | 54 ++++++++++++- gcc/c-family/c-common.cc | 13 ++++ gcc/c-family/c-common.h | 1 + gcc/c/c-decl.cc | 79 +++++++++++++++----- gcc/doc/extend.texi | 73 ++++++++++++++++++ gcc/testsuite/gcc.dg/flex-array-counted-by.c | 40 ++++++++++ gcc/tree.cc | 40 ++++++++++ gcc/tree.h | 5 ++ 8 files changed, 287 insertions(+), 18 deletions(-) create mode 100644 gcc/testsuite/gcc.dg/flex-array-counted-by.c diff --git a/gcc/c-family/c-attribs.cc b/gcc/c-family/c-attribs.cc index e2792ca6898b..65e4f6639109 100644 --- a/gcc/c-family/c-attribs.cc +++ b/gcc/c-family/c-attribs.cc @@ -103,6 +103,8 @@ static tree handle_warn_if_not_aligned_attribute (tree *, tree, tree, int, bool *); static tree handle_strict_flex_array_attribute (tree *, tree, tree, int, bool *); +static tree handle_counted_by_attribute (tree *, tree, tree, + int, bool *); static tree handle_weak_attribute (tree *, tree, tree, int, bool *) ; static tree handle_noplt_attribute (tree *, tree, tree, int, bool *) ; static tree handle_alias_ifunc_attribute (bool, tree *, tree, tree, bool *); @@ -373,6 +375,8 @@ const struct attribute_spec c_common_attribute_table[] = handle_warn_if_not_aligned_attribute, NULL }, { "strict_flex_array", 1, 1, true, false, false, false, handle_strict_flex_array_attribute, NULL }, + { "counted_by", 1, 1, true, false, false, false, + handle_counted_by_attribute, NULL }, { "weak", 0, 0, true, false, false, false, handle_weak_attribute, NULL }, { "noplt", 0, 0, true, false, false, false, @@ -601,7 +605,8 @@ attribute_takes_identifier_p (const_tree attr_id) else if (!strcmp ("mode", spec->name) || !strcmp ("format", spec->name) || !strcmp ("cleanup", spec->name) - || !strcmp ("access", spec->name)) + || !strcmp ("access", spec->name) + || !strcmp ("counted_by", spec->name)) return true; else return targetm.attribute_takes_identifier_p (attr_id); @@ -2555,6 +2560,53 @@ handle_strict_flex_array_attribute (tree *node, tree name, return NULL_TREE; } +/* Handle a "counted_by" attribute; arguments as in + struct attribute_spec.handler. */ + +static tree +handle_counted_by_attribute (tree *node, tree name, + tree args, int ARG_UNUSED (flags), + bool *no_add_attrs) +{ + tree decl = *node; + tree argval = TREE_VALUE (args); + + /* This attribute only applies to field decls of a structure. */ + if (TREE_CODE (decl) != FIELD_DECL) + { + error_at (DECL_SOURCE_LOCATION (decl), + "%qE attribute may not be specified for non-field" + " declaration %q+D", name, decl); + *no_add_attrs = true; + } + /* This attribute only applies to field with array type. */ + else if (TREE_CODE (TREE_TYPE (decl)) != ARRAY_TYPE) + { + error_at (DECL_SOURCE_LOCATION (decl), + "%qE attribute may not be specified for a non-array field", + name); + *no_add_attrs = true; + } + /* This attribute only applies to a C99 flexible array member type. */ + else if (! c_flexible_array_member_type_p (TREE_TYPE (decl))) + { + error_at (DECL_SOURCE_LOCATION (decl), + "%qE attribute may not be specified for a non" + " flexible array member field", + name); + *no_add_attrs = true; + } + /* The argument should be an identifier. */ + else if (TREE_CODE (argval) != IDENTIFIER_NODE) + { + error_at (DECL_SOURCE_LOCATION (decl), + "% argument not an identifier"); + *no_add_attrs = true; + } + + return NULL_TREE; +} + /* Handle a "weak" attribute; arguments as in struct attribute_spec.handler. */ diff --git a/gcc/c-family/c-common.cc b/gcc/c-family/c-common.cc index 9fbaeb437a12..a18937245c2a 100644 --- a/gcc/c-family/c-common.cc +++ b/gcc/c-family/c-common.cc @@ -9521,6 +9521,19 @@ c_common_finalize_early_debug (void) (*debug_hooks->early_global_decl) (cnode->decl); } +/* Determine whether TYPE is a ISO C99 flexible array memeber type "[]". */ +bool +c_flexible_array_member_type_p (const_tree type) +{ + if (TREE_CODE (type) == ARRAY_TYPE + && TYPE_SIZE (type) == NULL_TREE + && TYPE_DOMAIN (type) != NULL_TREE + && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL_TREE) + return true; + + return false; +} + /* Get the LEVEL of the strict_flex_array for the ARRAY_FIELD based on the values of attribute strict_flex_array and the flag_strict_flex_arrays. */ unsigned int diff --git a/gcc/c-family/c-common.h b/gcc/c-family/c-common.h index 78fc5248ba68..c29bb429062b 100644 --- a/gcc/c-family/c-common.h +++ b/gcc/c-family/c-common.h @@ -909,6 +909,7 @@ extern tree fold_for_warn (tree); extern tree c_common_get_narrower (tree, int *); extern bool get_attribute_operand (tree, unsigned HOST_WIDE_INT *); extern void c_common_finalize_early_debug (void); +extern bool c_flexible_array_member_type_p (const_tree); extern unsigned int c_strict_flex_array_level_of (tree); extern bool c_option_is_from_cpp_diagnostics (int); diff --git a/gcc/c/c-decl.cc b/gcc/c/c-decl.cc index 1f9eb44dbaa2..e943b49b5230 100644 --- a/gcc/c/c-decl.cc +++ b/gcc/c/c-decl.cc @@ -5173,19 +5173,6 @@ set_array_declarator_inner (struct c_declarator *decl, return decl; } -/* Determine whether TYPE is a ISO C99 flexible array memeber type "[]". */ -static bool -flexible_array_member_type_p (const_tree type) -{ - if (TREE_CODE (type) == ARRAY_TYPE - && TYPE_SIZE (type) == NULL_TREE - && TYPE_DOMAIN (type) != NULL_TREE - && TYPE_MAX_VALUE (TYPE_DOMAIN (type)) == NULL_TREE) - return true; - - return false; -} - /* Determine whether TYPE is a one-element array type "[1]". */ static bool one_element_array_type_p (const_tree type) @@ -5222,7 +5209,7 @@ add_flexible_array_elts_to_size (tree decl, tree init) elt = CONSTRUCTOR_ELTS (init)->last ().value; type = TREE_TYPE (elt); - if (flexible_array_member_type_p (type)) + if (c_flexible_array_member_type_p (type)) { complete_array_type (&type, elt, false); DECL_SIZE (decl) @@ -9094,7 +9081,7 @@ is_flexible_array_member_p (bool is_last_field, bool is_zero_length_array = zero_length_array_type_p (TREE_TYPE (x)); bool is_one_element_array = one_element_array_type_p (TREE_TYPE (x)); - bool is_flexible_array = flexible_array_member_type_p (TREE_TYPE (x)); + bool is_flexible_array = c_flexible_array_member_type_p (TREE_TYPE (x)); unsigned int strict_flex_array_level = c_strict_flex_array_level_of (x); @@ -9124,6 +9111,61 @@ is_flexible_array_member_p (bool is_last_field, return false; } +/* Verify the argument of the counted_by attribute of the flexible array + member FIELD_DECL is a valid field of the containing structure's fieldlist, + FIELDLIST, Report error and remove this attribute when it's not. */ +static void +verify_counted_by_attribute (tree fieldlist, tree field_decl) +{ + tree attr_counted_by = lookup_attribute ("counted_by", + DECL_ATTRIBUTES (field_decl)); + + if (!attr_counted_by) + return; + + /* If there is an counted_by attribute attached to the field, + verify it. */ + + const char *fieldname + = IDENTIFIER_POINTER (TREE_VALUE (TREE_VALUE (attr_counted_by))); + + /* Verify the argument of the attrbute is a valid field of the + containing structure. */ + + tree counted_by_field = get_named_field (fieldlist, fieldname); + + /* Error when the field is not found in the containing structure. */ + if (!counted_by_field) + { + error_at (DECL_SOURCE_LOCATION (field_decl), + "%qE attribute argument not a field declaration" + " in the same structure, ignore it", + (get_attribute_name (attr_counted_by))); + + DECL_ATTRIBUTES (field_decl) + = remove_attribute ("counted_by", DECL_ATTRIBUTES (field_decl)); + } + else + /* Error when the field is not with an integer type. */ + { + while (TREE_CHAIN (counted_by_field)) + counted_by_field = TREE_CHAIN (counted_by_field); + tree real_field = TREE_VALUE (counted_by_field); + + if (TREE_CODE (TREE_TYPE (real_field)) != INTEGER_TYPE) + { + error_at (DECL_SOURCE_LOCATION (field_decl), + "%qE attribute argument not a field declaration" + " with integer type, ignore it", + (get_attribute_name (attr_counted_by))); + + DECL_ATTRIBUTES (field_decl) + = remove_attribute ("counted_by", DECL_ATTRIBUTES (field_decl)); + } + } + + return; +} /* Fill in the fields of a RECORD_TYPE or UNION_TYPE node, T. LOC is the location of the RECORD_TYPE or UNION_TYPE's definition. @@ -9244,7 +9286,7 @@ finish_struct (location_t loc, tree t, tree fieldlist, tree attributes, DECL_PACKED (x) = 1; /* Detect flexible array member in an invalid context. */ - if (flexible_array_member_type_p (TREE_TYPE (x))) + if (c_flexible_array_member_type_p (TREE_TYPE (x))) { if (TREE_CODE (t) == UNION_TYPE) { @@ -9265,6 +9307,9 @@ finish_struct (location_t loc, tree t, tree fieldlist, tree attributes, "members"); TREE_TYPE (x) = error_mark_node; } + /* if there is a counted_by attribute attached to this field, + verify it. */ + verify_counted_by_attribute (fieldlist, x); } if (pedantic && TREE_CODE (t) == RECORD_TYPE @@ -9279,7 +9324,7 @@ finish_struct (location_t loc, tree t, tree fieldlist, tree attributes, when x is an array and is the last field. */ if (TREE_CODE (TREE_TYPE (x)) == ARRAY_TYPE) TYPE_INCLUDES_FLEXARRAY (t) - = is_last_field && flexible_array_member_type_p (TREE_TYPE (x)); + = is_last_field && c_flexible_array_member_type_p (TREE_TYPE (x)); /* Recursively set TYPE_INCLUDES_FLEXARRAY for the context of x, t when x is an union or record and is the last field. */ else if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (x))) diff --git a/gcc/doc/extend.texi b/gcc/doc/extend.texi index 97eaacf8a7ec..a19cfe7547d8 100644 --- a/gcc/doc/extend.texi +++ b/gcc/doc/extend.texi @@ -7617,6 +7617,79 @@ When both the attribute and the option present at the same time, the level of the strictness for the specific trailing array field is determined by the attribute. +@cindex @code{counted_by} variable attribute +@item counted_by (@var{count}) +The @code{counted_by} attribute may be attached to the flexible array +member of a structure. It indicates that the number of the elements of the +array is given by the field named "@var{count}" in the same structure as the +flexible array member. GCC uses this information to improve the results of +the array bound sanitizer and the @code{__builtin_dynamic_object_size}. + +For instance, the following code: + +@smallexample +struct P @{ + size_t count; + int array[] __attribute__ ((counted_by (count))); +@} *p; +@end smallexample + +@noindent +specifies that the @code{array} is a flexible array member whose number of +elements is given by the field @code{count} in the same structure. + +The field that represents the number of the elements should have an integer +type. An explicit @code{counted_by} annotation defines a relationship between +two objects, @code{p->array} and @code{p->count}, that @code{p->array} has +@emph{at least} @code{p->count} number of elements available. This relationship +must hold even after any of these related objects are updated. It's the user's +responsibility to make sure this relationship to be kept all the time. +Otherwise the results of the array bound sanitizer and the +@code{__builtin_dynamic_object_size} might be incorrect. + +For instance, in the following example, the allocated array has less elements +than what's specified by the @code{sbuf->count}, this is an user error. As a +result, out-of-bounds access to the array might not be detected. + +@smallexample +#define SIZE_BUMP 10 +struct P *sbuf; +void alloc_buf (size_t nelems) +@{ + sbuf = (int *) malloc (sizeof (struct P) + sizeof (int) * nelems); + sbuf->count = nelems + SIZE_BUMP; + /* This is invalid when the sbuf->array has less than sbuf->count + elements. */ +@} +@end smallexample + +In the following example, the 2nd update to the field @code{sbuf->count} of +the above structure will permit out-of-bounds access to the array +@code{sbuf>array} as well. + +@smallexample +#define SIZE_BUMP 10 +struct P *sbuf; +void alloc_buf (size_t nelems) +@{ + sbuf = (int *) malloc (sizeof (struct P) + + sizeof (int) * (nelems + SIZE_BUMP)); + sbuf->count = nelems; + /* This is valid when the sbuf->array has at least sbuf->count + elements. */ +@} +void use_buf (int index) +@{ + sbuf->count = sbuf->count + SIZE_BUMP + 1; + /* Now the value of sbuf->count is larger than the number + of elements of sbuf->array. */ + sbuf->array[index] = 0; + /* then the out-of-bound access to this array + might not be detected. */ +@} +@end smallexample + + @cindex @code{alloc_size} variable attribute @item alloc_size (@var{position}) @itemx alloc_size (@var{position-1}, @var{position-2}) diff --git a/gcc/testsuite/gcc.dg/flex-array-counted-by.c b/gcc/testsuite/gcc.dg/flex-array-counted-by.c new file mode 100644 index 000000000000..f8ce9776bf86 --- /dev/null +++ b/gcc/testsuite/gcc.dg/flex-array-counted-by.c @@ -0,0 +1,40 @@ +/* testing the correct usage of attribute counted_by. */ +/* { dg-do compile } */ +/* { dg-options "-O2" } */ + +#include + +int size; +int x __attribute ((counted_by (size))); /* { dg-error "attribute may not be specified for non-field declaration" } */ + +struct trailing { + int count; + int field __attribute ((counted_by (count))); /* { dg-error "attribute may not be specified for a non-array field" } */ +}; + +struct trailing_1 { + int count; + int array_1[0] __attribute ((counted_by (count))); /* { dg-error "attribute may not be specified for a non flexible array member field" } */ +}; + +int count; +struct trailing_array_2 { + int count; + int array_2[] __attribute ((counted_by ("count"))); /* { dg-error "argument not an identifier" } */ +}; + +struct trailing_array_3 { + int other; + int array_3[] __attribute ((counted_by (L"count"))); /* { dg-error "argument not an identifier" } */ +}; + +struct trailing_array_4 { + int other; + int array_4[] __attribute ((counted_by (count))); /* { dg-error "attribute argument not a field declaration in the same structure, ignore it" } */ +}; + +int count; +struct trailing_array_5 { + float count; + int array_5[] __attribute ((counted_by (count))); /* { dg-error "attribute argument not a field declaration with integer type, ignore it" } */ +}; diff --git a/gcc/tree.cc b/gcc/tree.cc index 420857b110c4..fcd36ae0cd74 100644 --- a/gcc/tree.cc +++ b/gcc/tree.cc @@ -12745,6 +12745,46 @@ array_ref_element_size (tree exp) return SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (elmt_type), exp); } +/* Given a field list, FIELDLIST, of a structure/union, return a TREE_LIST, + with each TREE_VALUE a FIELD_DECL stepping down the chain to the FIELD + whose name is FIELDNAME, which is the last TREE_VALUE of the list. + return NULL_TREE if such field is not found. Normally this list is of + length one, but if the field is embedded with (nested) anonymous structures + or unions, this list steps down the chain to the field. */ +tree +get_named_field (tree fieldlist, const char *fieldname) +{ + tree named_field = NULL_TREE; + for (tree field = fieldlist; field; field = DECL_CHAIN (field)) + { + if (TREE_CODE (field) != FIELD_DECL) + continue; + if (DECL_NAME (field) != NULL) + if (strcmp (IDENTIFIER_POINTER (DECL_NAME (field)), fieldname) == 0) + { + named_field = tree_cons (NULL_TREE, field, named_field); + break; + } + else + continue; + /* if the field is an anonymous struct/union, we will check the nested + fields inside it recursively. */ + else if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))) + if ((named_field = get_named_field (TYPE_FIELDS (TREE_TYPE (field)), + fieldname)) != NULL_TREE) + { + named_field = tree_cons (NULL_TREE, field, named_field); + break; + } + else + continue; + else + continue; + } + return named_field; +} + + /* Return a tree representing the lower bound of the array mentioned in EXP, an ARRAY_REF or an ARRAY_RANGE_REF. */ diff --git a/gcc/tree.h b/gcc/tree.h index 4c04245e2b1b..4859becaa1e7 100644 --- a/gcc/tree.h +++ b/gcc/tree.h @@ -5619,6 +5619,11 @@ extern tree get_base_address (tree t); of EXP, an ARRAY_REF or an ARRAY_RANGE_REF. */ extern tree array_ref_element_size (tree); +/* Given a field list, FIELDLIST, of a structure/union, return the FIELD whose + name is FIELDNAME, return NULL_TREE if such field is not found. + searching nested anonymous structure/union recursively. */ +extern tree get_named_field (tree, const char *); + /* Return a typenode for the "standard" C type with a given name. */ extern tree get_typenode_from_name (const char *); From patchwork Fri Aug 4 19:44:30 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Qing Zhao X-Patchwork-Id: 1817148 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=gcc.gnu.org (client-ip=2620:52:3:1:0:246e:9693:128c; helo=server2.sourceware.org; envelope-from=gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org; receiver=) Authentication-Results: legolas.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=mENmOBOU; dkim-atps=neutral Received: from server2.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 ECDSA (P-384) server-digest SHA384) (No client certificate requested) by legolas.ozlabs.org (Postfix) with ESMTPS id 4RHbly6hJHz1yYl for ; Sat, 5 Aug 2023 05:45:18 +1000 (AEST) Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id E63203856DCA for ; Fri, 4 Aug 2023 19:45:16 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org E63203856DCA DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gcc.gnu.org; s=default; t=1691178316; bh=tpkrpBCO7zL5r1nT7LhdikdV1DYGbyW90Kn28xJST5k=; h=To:Cc:Subject:Date:In-Reply-To:References:List-Id: List-Unsubscribe:List-Archive:List-Post:List-Help:List-Subscribe: From:Reply-To:From; b=mENmOBOUJqjEad0YxUEtdJhDoQB2CzJh67kF0bELlTvluXFh6zYOceb6e4gn3ktvX RMP5PwzEXdYmJHTr059CIgHhEGt/wjBGLXZN6Gkx9y94JfXuQLfrskCSijU7j7UNyh 0z0T0uQJpRwCT+jUYIXp17eTiesKwm3gIkn2sjr4= X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mx0a-00069f02.pphosted.com (mx0a-00069f02.pphosted.com [205.220.165.32]) by sourceware.org (Postfix) with ESMTPS id 9F7123857025 for ; Fri, 4 Aug 2023 19:44:53 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 9F7123857025 Received: from pps.filterd (m0246617.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.17.1.19/8.17.1.19) with ESMTP id 374JCdQq011140; Fri, 4 Aug 2023 19:44:51 GMT Received: from phxpaimrmta01.imrmtpd1.prodappphxaev1.oraclevcn.com (phxpaimrmta01.appoci.oracle.com [138.1.114.2]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 3s4uav4hn0-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Fri, 04 Aug 2023 19:44:50 +0000 Received: from pps.filterd (phxpaimrmta01.imrmtpd1.prodappphxaev1.oraclevcn.com [127.0.0.1]) by phxpaimrmta01.imrmtpd1.prodappphxaev1.oraclevcn.com (8.17.1.19/8.17.1.19) with ESMTP id 374JBwRq011668; Fri, 4 Aug 2023 19:44:50 GMT Received: from nam10-mw2-obe.outbound.protection.outlook.com (mail-mw2nam10lp2101.outbound.protection.outlook.com [104.47.55.101]) by phxpaimrmta01.imrmtpd1.prodappphxaev1.oraclevcn.com (PPS) with ESMTPS id 3s8m2saup7-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Fri, 04 Aug 2023 19:44:50 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=UWzFW/CRedU/jgVrlefbhdjWfaTWqnewoOA6MYy0hdmXaHgSf6x6SkmcUeuB2wRymbKrQRxfZOqokD5uIBuRQn8rOM1ZLxfAl6KONENGLRx5Esuv+98Pb3fELBpWVMXyZONxxkvJlE6T+hpUJuM+nBZ/DzFXlmD/AK/H3t3c6b0pxhiQMUQEt/eHAdPY86+OUReUFXY62cFMB99D2vsAOwxL7vQOreG5Ci5sGxxGXK4K5ZGaOUZVcdwm4fIPYwey++LDtZ+8wmwsmOQvb0U2vYELhzmFWBAuS3uwe5pMxQAtmpCdZqbWkagweCq8vdl4QdLyki1SKmAFL1qbXN6lFA== 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=tpkrpBCO7zL5r1nT7LhdikdV1DYGbyW90Kn28xJST5k=; b=Zd1XOTKgugzwRqT9qfi7cg9GfHgj2t2R2GyY9QYbC2IhOHHelc3zVzWQEH6Co56hGMjuOCu1qeqDq3QYEzoZvAVjFEyS8O+JBPVS2cj4Z3jyrzi7g5Y8CbQErgWjvLWgJaTE+7DfRkJVR4TnHL+v7Pu1np51W+CWytMv9TxbVAkbrxQJ1sCoz/tfoSPB75rsLHvkyCuKrwDi3U8afmk3+ZGJrHS2gVhGZVqWFsmBxGtJNrUQZJBkiCYwQiIv/zE5LdzUm+huG7sRtDk/rP/ymNrTtQufxesud4J/rgMZ1XMYbdtoCPlq+SIgCutaS0lBHJ2I7OJ0AmO287Y/m6EARw== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none Received: from CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) by MW6PR10MB7590.namprd10.prod.outlook.com (2603:10b6:303:24c::11) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.6631.47; Fri, 4 Aug 2023 19:44:47 +0000 Received: from CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::5afd:d02a:38ef:94ba]) by CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::5afd:d02a:38ef:94ba%7]) with mapi id 15.20.6652.020; Fri, 4 Aug 2023 19:44:47 +0000 To: joseph@codesourcery.com, richard.guenther@gmail.com, jakub@redhat.com, gcc-patches@gcc.gnu.org Cc: keescook@chromium.org, siddhesh@gotplt.org, uecker@tugraz.at, isanbard@gmail.com, Qing Zhao Subject: [V2][PATCH 2/3] Use the counted_by atribute info in builtin object size [PR108896] Date: Fri, 4 Aug 2023 19:44:30 +0000 Message-Id: <20230804194431.993958-3-qing.zhao@oracle.com> X-Mailer: git-send-email 2.31.1 In-Reply-To: <20230804194431.993958-1-qing.zhao@oracle.com> References: <20230804194431.993958-1-qing.zhao@oracle.com> X-ClientProxiedBy: SJ0PR13CA0052.namprd13.prod.outlook.com (2603:10b6:a03:2c2::27) To CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: CH2PR10MB4344:EE_|MW6PR10MB7590:EE_ X-MS-Office365-Filtering-Correlation-Id: 242fac2e-8f91-4a9c-be34-08db9523426f X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; X-Microsoft-Antispam-Message-Info: Q5sJp1Y3xE0NESITEyJo3QcNcZtDgcQ+CZ+zZJBJGVmwKPcU4nHgP3VZu/p8z4xpMLIBA7liu8tCir8E4ay9VizfKlE+3C25BgmK72KujsIY6hOwrhtcS5gE5lyfvbU9wKRwutjmibZyox3gk+r8qXZs9m+OpZy/B/K37ophJMiGb7M1XlhtUQ7Ugc2s6DgYZVt1a3CjyxdVynnIi+bPbCTAyJ21d36wE4XFedIaZ1KbfHwjOqkPCKvzvmA1lFkLY3024Zp183ElE5GK1UYfoyr3+7iIhpwH0HXRQUIHe73qggwIizmlnXlso4dM632uoWdiwjctAG7/e2OAeWjj+AQkvVXRBykAkAHRogFEU+TTbnN7samBMalE4gNUIqqDV5UeTYL65cuopbt3etXmkGkfuUrqvFVTrQ8aZTyt3v3cp++0idbCNMD2f4b0dqp0YBWfVKNDJ9qZfr5BlYhMHpYO4TZ9YhK5S/vkQE9uEcbz5/M+Iaue4+1jzneiq1K4LfjKvKg8iuHEGy4xoNGFO+6O6eYlXJuaWJDXD2732LG7kvwnmGFWq9DfS8iG6szYMyxpoZlg3jkrF1qaM0E4zg== X-Forefront-Antispam-Report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:CH2PR10MB4344.namprd10.prod.outlook.com; PTR:; CAT:NONE; SFS:(13230028)(346002)(39860400002)(136003)(376002)(396003)(366004)(451199021)(1800799003)(186006)(83380400001)(1076003)(2616005)(107886003)(6506007)(26005)(8676002)(66556008)(2906002)(316002)(30864003)(66946007)(5660300002)(66476007)(4326008)(41300700001)(8936002)(44832011)(6486002)(6512007)(6666004)(966005)(478600001)(38100700002)(36756003)(86362001)(84970400001); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: Jy6dOxBWBJJKFNeCDU8bUjfuiqZcMupmUTm3bTf44Ou0ufLGyH2Uk/kuTyQkbf/K3p41NsF0t9eSmjmjcIPYayIAjp5wgY6JMb5XP9nLdWlrklZNl/yjcAtQCEAeVKXy+YQsTyZwqWYeIXy61+CloyTX0/C0B1ekz/UsxnSluSY5SdGhxirDnLu5/1iPbuFcz21lyjl/ZkVRe7cBtg1AH4kXk4rkSpAuF8/Rjq+PZmR8ZEwq8bmXaSB+pAjIlxTYzzmBJFGYMadwCXiN93VD3j/fNJx/dGn1IMRasr2vqLvR3VLsAPpadOzlc3OcyY6Qmjf6uWPDQp6BPjMY81T0aMJG3ZuzeCOBlQ8APc1FY/rsXQm5lq6+IgP2HOzXQNfN56cSF7UI2WGz2p2ptDJ6h7v2dpIWvk5CUawWfSWjL/mQo8pXYhUA+f9AkVvueJ3nJlkSLrAxx20BI5F2IyZgOpxm97bLG9YPxj/Kxzl05uaDk/MfEVfuR0AFrL6SwJdi6TBKto/RXCJDSJwOoZsMWx8oJfIo8XIWnNqKGbieXPPpgXMc1d1h2rwNzvi/xEW74sDkEf24c4I9G1exBnwWyBbe+8hC3SHUeVSWD0v/9w8fXpuzvZJtIJAjVB0qietxri2pH2UwzswxQAprIYV5i13mPBUVAOol7IHNT9HDifChDkHdYMEiA/pUsjHPyuie8uxc16zNUYZy1PQaUuMSa5f7YNZ9GpbZOVGkbyiJtpx1Dvi2Z5mT8GjkT6h3ptW4FOWr9XcLb0Oz2WDmNZ0JxLiBYYMX3eyiWd7cPKAn0zUh9nZSzZQ5upR5n/BiarZTyYXh82a95U2PrVf+WaGUKPssqnKyzkLdI9c7/UXM38Vf0xftU/G5Stv3tD6ArbeMYeHkadbi4RTTaGXMINH9loILfbupXdZA3Eeo6hLZqB7VptP6BrayEP5OkMZnpreqy+KeMOf5iOioxddBfZvXNLkkpp7RH31e9B7aGgWuIKBcr68fnvNq4XBp2uA6XfFoJSqfn1fsYz+drvFmeFGauQic72/Y7UjBtAaLl6xfMPHL/rfT1tp1xEkRC+yhONWB699tqSlTvEP3XmJr2yVTf3TLjbYX36Ioa2I24M6b1eKLhuqyVT76khMTMpnr/++NBeVCfCXFVNOIR0PwOYSTceyBJqXgT7YrctLoj4w+8z+jo17n3BzYLhDM7WzFicgxbpNMqQuNwq6gE8rh7IFA7isF84Rzq7k+Ev8+miaxEpEqvHFDg0DTFOYTcIxvmpNkkgJlOzRK3PITWMGnO+YjIdNHAtNph8X+VI5pPM3IU5bpCkVX6mBDRbcWht81QWQPP6JaNl5MqR9AxOBJrg6sTuGNP/j97tnZKRHq+Zzo9QktACOiBDmdou6N/vxlWZjHSfnEpbjT1sYtqzElj1WcLXq+g6HXfF9ZIEFQB8YLDJkwLimGMW8Rnf0BinvFSCbU1E+0SQ5OyQdWrVt690UpOWlXplSeq2hS25vNuvEuNk0Y+S8Kz6XWN6gesk6FO1Tp8+x+piHMcv0MnD+zkr20R73JuN1/RuptQylc+hChfYsbXubZAj1T0gC8MDkis8Q4 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: kTg7ojcJQIw6rn/U42bc/rrNXy+moCiBZOm9UokF2ZVmZKN2RSS9yGyNPKnmblnXmlaqUsRRXchzUHFfQoy/GyiBw/uZDKY/p7O064SjVVZwTBUIMxJ/dzOdp444XJKtqn59qdvkha966gQp0a8wRPHJqTurjlG+CJs1urXgHuMZ/qEfOBnwRvbJ7+lgtE9LJi4pFY0F1h8A9/WOLwfhw8ULNtg/xDceCPgLV2iGOEbbxm6Ky8eFIEHJ5/mWeLqL1jfXiWfq2+4tsCelRoaODoBHVMyVDSAd4ZCCNq/FN4o6FgP+Eh06oT2HOC8PkWaJVR2o4hSCjzQBRbeD/+1fmn6WrQcbGtPOAXrzSrAuwtnz2boeTXpUp43c8iJtK+5/6X50M4hfIYVMfN184QSwR7UIAdNuw+orn/SgofD6+w+/AxWygeyX1D9e6Bjhk1i+tSGflT/vgSqj/Roe+HeKSJGZU2x7Rwg30fcGCJH4ItCVYhQVzp6/H4/4fQXyJ+nU89/ZGc9eu2mjh/bk0nazRJsJLPJlyXsiI+qq8DouJPvK1P4zBgfd4KTseqZf/ZldbAr3DXBxgHN4gmLD0SEYtLUUKb8hOsg0zxYvZWdtIlrkPvWmuden/adymAp8dg9bdE+L3EL5Sc9JPit/ALV3ZDQIfGokF/Rpid4S6A1Zi3JXsbzxxOK67oOfozke0zNUMGksIbXp+CFPH8q6H30kuzQFvIgffFWNIWE+wWZN7ErvmVkp7dfwAeigk9DI0ShUAAGFkipt9uR6aRksDcOUwir3Yk/NuENCOzJIwrwGoY21w+CZWoZ3NMWVXuE81F1avghx+c9LZJu6o/XQBtGbglq2Lc1OrLlcse+my5i3AJ0kUkzqp+TvDkCXDN3TUh0PUizPLax87UMMxcCBjXdQEpVdvVw4A3tzFxsb+GL7daRamLlY24iouRNffxiO8En2 X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 242fac2e-8f91-4a9c-be34-08db9523426f X-MS-Exchange-CrossTenant-AuthSource: CH2PR10MB4344.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 04 Aug 2023 19:44:47.6563 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: vcGg2jv4xsOwOrcWZeCr8WCEPAkSzvpPLP+p1CSaemQxxkdlJMLfdS1EdcBuvgQ2HqKkX+fuktB13zJxIP0jRg== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MW6PR10MB7590 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.267,Aquarius:18.0.957,Hydra:6.0.591,FMLib:17.11.176.26 definitions=2023-08-04_20,2023-08-03_01,2023-05-22_02 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 malwarescore=0 bulkscore=0 phishscore=0 mlxscore=0 spamscore=0 adultscore=0 suspectscore=0 mlxlogscore=999 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2306200000 definitions=main-2308040177 X-Proofpoint-ORIG-GUID: uIYQC1BK8lWubBvioZL2QJY0E3JwN6Fi X-Proofpoint-GUID: uIYQC1BK8lWubBvioZL2QJY0E3JwN6Fi X-Spam-Status: No, score=-11.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, KAM_SHORT, RCVD_IN_DNSWL_LOW, RCVD_IN_MSPIKE_H5, RCVD_IN_MSPIKE_WL, SPF_HELO_NONE, SPF_NONE, TXREP 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: Qing Zhao via Gcc-patches From: Qing Zhao Reply-To: Qing Zhao Errors-To: gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org Sender: "Gcc-patches" gcc/ChangeLog: PR C/108896 * tree-object-size.cc (addr_object_size): Use the counted_by attribute info. * tree.cc (component_ref_has_counted_by_p): New function. (component_ref_get_counted_by): New function. * tree.h (component_ref_has_counted_by_p): New prototype. (component_ref_get_counted_by): New prototype. gcc/testsuite/ChangeLog: PR C/108896 * gcc.dg/flex-array-counted-by-2.c: New test. * gcc.dg/flex-array-counted-by-3.c: New test. --- .../gcc.dg/flex-array-counted-by-2.c | 74 +++++++ .../gcc.dg/flex-array-counted-by-3.c | 197 ++++++++++++++++++ gcc/tree-object-size.cc | 37 +++- gcc/tree.cc | 95 ++++++++- gcc/tree.h | 10 + 5 files changed, 405 insertions(+), 8 deletions(-) create mode 100644 gcc/testsuite/gcc.dg/flex-array-counted-by-2.c create mode 100644 gcc/testsuite/gcc.dg/flex-array-counted-by-3.c diff --git a/gcc/testsuite/gcc.dg/flex-array-counted-by-2.c b/gcc/testsuite/gcc.dg/flex-array-counted-by-2.c new file mode 100644 index 000000000000..ec580c1f1f01 --- /dev/null +++ b/gcc/testsuite/gcc.dg/flex-array-counted-by-2.c @@ -0,0 +1,74 @@ +/* test the attribute counted_by and its usage in + * __builtin_dynamic_object_size. */ +/* { dg-do run } */ +/* { dg-options "-O2" } */ + +#include "builtin-object-size-common.h" + +#define expect(p, _v) do { \ + size_t v = _v; \ + if (p == v) \ + __builtin_printf ("ok: %s == %zd\n", #p, p); \ + else \ + { \ + __builtin_printf ("WAT: %s == %zd (expected %zd)\n", #p, p, v); \ + FAIL (); \ + } \ +} while (0); + +struct flex { + int b; + int c[]; +} *array_flex; + +struct annotated { + int b; + int c[] __attribute__ ((counted_by (b))); +} *array_annotated; + +struct nested_annotated { + struct { + union { + int b; + float f; + }; + int n; + }; + int c[] __attribute__ ((counted_by (b))); +} *array_nested_annotated; + +void __attribute__((__noinline__)) setup (int normal_count, int attr_count) +{ + array_flex + = (struct flex *)malloc (sizeof (struct flex) + + normal_count * sizeof (int)); + array_flex->b = normal_count; + + array_annotated + = (struct annotated *)malloc (sizeof (struct annotated) + + attr_count * sizeof (int)); + array_annotated->b = attr_count; + + array_nested_annotated + = (struct nested_annotated *)malloc (sizeof (struct nested_annotated) + + attr_count * sizeof (int)); + array_nested_annotated->b = attr_count; + + return; +} + +void __attribute__((__noinline__)) test () +{ + expect(__builtin_dynamic_object_size(array_flex->c, 1), -1); + expect(__builtin_dynamic_object_size(array_annotated->c, 1), + array_annotated->b * sizeof (int)); + expect(__builtin_dynamic_object_size(array_nested_annotated->c, 1), + array_nested_annotated->b * sizeof (int)); +} + +int main(int argc, char *argv[]) +{ + setup (10,10); + test (); + DONE (); +} diff --git a/gcc/testsuite/gcc.dg/flex-array-counted-by-3.c b/gcc/testsuite/gcc.dg/flex-array-counted-by-3.c new file mode 100644 index 000000000000..22ef2af31c20 --- /dev/null +++ b/gcc/testsuite/gcc.dg/flex-array-counted-by-3.c @@ -0,0 +1,197 @@ +/* test the attribute counted_by and its usage in +__builtin_dynamic_object_size: what's the correct behavior when the allocaiton +size mismatched with the value of counted_by attribute? */ +/* { dg-do run } */ +/* { dg-options "-O -fstrict-flex-arrays=3" } */ + +#include "builtin-object-size-common.h" + +struct annotated { + size_t foo; + int array[] __attribute__((counted_by (foo))); +}; + +#define expect(p, _v) do { \ + size_t v = _v; \ + if (p == v) \ + __builtin_printf ("ok: %s == %zd\n", #p, p); \ + else \ + { \ + __builtin_printf ("WAT: %s == %zd (expected %zd)\n", #p, p, v); \ + FAIL (); \ + } \ +} while (0); + +#define noinline __attribute__((__noinline__)) +#define SIZE_BUMP 5 + +/* In general, Due to type casting, the type for the pointee of a pointer + does not say anything about the object it points to, + So, __builtin_object_size can not directly use the type of the pointee + to decide the size of the object the pointer points to. + + there are only two reliable ways: + A. observed allocations (call to the allocation functions in the routine) + B. observed accesses (read or write access to the location of the + pointer points to) + + that provide information about the type/existence of an object at + the corresponding address. + + for A, we use the "alloc_size" attribute for the corresponding allocation + functions to determine the object size; + + For B, we use the SIZE info of the TYPE attached to the corresponding access. + (We treat counted_by attribute as a complement to the SIZE info of the TYPE + for FMA) + + The only other way in C which ensures that a pointer actually points + to an object of the correct type is 'static': + + void foo(struct P *p[static 1]); + + See https://gcc.gnu.org/pipermail/gcc-patches/2023-July/624814.html + for more details. */ + +/* in the following function, malloc allocated more space than the value + of counted_by attribute. Then what's the correct behavior we expect + the __builtin_dynamic_object_size should have for each of the cases? */ + +static struct annotated * noinline alloc_buf_more (int index) +{ + struct annotated *p; + p = malloc(sizeof (*p) + (index + SIZE_BUMP) * sizeof (int)); + p->foo = index; + + /*when checking the observed access p->array, we have info on both + observered allocation and observed access, + A. from observed allocation: (index + SIZE_BUMP) * sizeof (int) + B. from observed access: p->foo * sizeof (int) + + in the above, p->foo = index. + */ + + /* for size in the whole object: always uses A. */ + /* for size in the sub-object: chose the smaller of A and B. + * Please see https://gcc.gnu.org/pipermail/gcc-patches/2023-July/625891.html + * for details on why. */ + + /* for MAXIMUM size in the whole object: use the allocation size + for the whole object. */ + expect(__builtin_dynamic_object_size(p->array, 0), + (index + SIZE_BUMP) * sizeof(int)); + + /* for MAXIMUM size in the sub-object. use the smaller of A and B. */ + expect(__builtin_dynamic_object_size(p->array, 1), (p->foo) * sizeof(int)); + + /* for MINIMUM size in the whole object: use the allocation size + for the whole object. */ + expect(__builtin_dynamic_object_size(p->array, 2), + (index + SIZE_BUMP) * sizeof(int)); + + /* for MINIMUM size in the sub-object: use the smaller of A and B. */ + expect(__builtin_dynamic_object_size(p->array, 3), p->foo * sizeof(int)); + + /*when checking the pointer p, we only have info on the observed allocation. + So, the object size info can only been obtained from the call to malloc. + for both MAXIMUM and MINIMUM: A = (index + SIZE_BUMP) * sizeof (int) */ + expect(__builtin_dynamic_object_size(p, 1), + sizeof (*p) + (index + SIZE_BUMP) * sizeof(int)); + expect(__builtin_dynamic_object_size(p, 0), + sizeof (*p) + (index + SIZE_BUMP) * sizeof(int)); + expect(__builtin_dynamic_object_size(p, 3), + sizeof (*p) + (index + SIZE_BUMP) * sizeof(int)); + expect(__builtin_dynamic_object_size(p, 2), + sizeof (*p) + (index + SIZE_BUMP) * sizeof(int)); + return p; +} + +/* in the following function, malloc allocated less space than the value + of counted_by attribute. Then what's the correct behavior we expect + the __builtin_dynamic_object_size should have for each of the cases? + NOTE: this is an user error, GCC should issue warnings for such case. + this is a seperate issue we should address later. */ + +static struct annotated * noinline alloc_buf_less (int index) +{ + struct annotated *p; + p = malloc(sizeof (*p) + (index) * sizeof (int)); + p->foo = index + SIZE_BUMP; + + /*when checking the observed access p->array, we have info on both + observered allocation and observed access, + A. from observed allocation: (index) * sizeof (int) + B. from observed access: p->foo * sizeof (int) + + in the above, p->foo = index + SIZE_BUMP. + */ + + /* for size in the whole object: always uses A. */ + /* for size in the sub-object: chose the smaller of A and B. + * Please see https://gcc.gnu.org/pipermail/gcc-patches/2023-July/625891.html + * for details on why. */ + + /* for MAXIMUM size in the whole object: use the allocation size + for the whole object. */ + expect(__builtin_dynamic_object_size(p->array, 0), (index) * sizeof(int)); + + /* for MAXIMUM size in the sub-object. use the smaller of A and B. */ + expect(__builtin_dynamic_object_size(p->array, 1), (index) * sizeof(int)); + + /* for MINIMUM size in the whole object: use the allocation size + for the whole object. */ + expect(__builtin_dynamic_object_size(p->array, 2), (index) * sizeof(int)); + + /* for MINIMUM size in the sub-object: use the smaller of A and B. */ + expect(__builtin_dynamic_object_size(p->array, 3), (index) * sizeof(int)); + + /*when checking the pointer p, we only have info on the observed allocation. + So, the object size info can only been obtained from the call to malloc. + for both MAXIMUM and MINIMUM: A = (index + SIZE_BUMP) * sizeof (int) */ + expect(__builtin_dynamic_object_size(p, 1), + sizeof (*p) + (index) * sizeof(int)); + expect(__builtin_dynamic_object_size(p, 0), + sizeof (*p) + (index) * sizeof(int)); + expect(__builtin_dynamic_object_size(p, 3), + sizeof (*p) + (index) * sizeof(int)); + expect(__builtin_dynamic_object_size(p, 2), + sizeof (*p) + (index) * sizeof(int)); + return p; +} + +int main () +{ + struct annotated *p, *q; + p = alloc_buf_more (10); + q = alloc_buf_less (10); + + /*when checking the observed access p->array, we only have info on the + observed access, i.e, the TYPE_SIZE info from the access. We don't have + info on the whole object. */ + expect(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(int)); + expect(__builtin_dynamic_object_size(p->array, 0), -1); + expect(__builtin_dynamic_object_size(p->array, 3), p->foo * sizeof(int)); + expect(__builtin_dynamic_object_size(p->array, 2), 0); + /*when checking the pointer p, we have no observed allocation nor observed + access, therefore, we cannot determine the size info here. */ + expect(__builtin_dynamic_object_size(p, 1), -1); + expect(__builtin_dynamic_object_size(p, 0), -1); + expect(__builtin_dynamic_object_size(p, 3), 0); + expect(__builtin_dynamic_object_size(p, 2), 0); + + /*when checking the observed access p->array, we only have info on the + observed access, i.e, the TYPE_SIZE info from the access. We don't have + info on the whole object. */ + expect(__builtin_dynamic_object_size(q->array, 1), q->foo * sizeof(int)); + expect(__builtin_dynamic_object_size(q->array, 0), -1); + expect(__builtin_dynamic_object_size(q->array, 3), q->foo * sizeof(int)); + expect(__builtin_dynamic_object_size(q->array, 2), 0); + /*when checking the pointer p, we have no observed allocation nor observed + access, therefore, we cannot determine the size info here. */ + expect(__builtin_dynamic_object_size(q, 1), -1); + expect(__builtin_dynamic_object_size(q, 0), -1); + expect(__builtin_dynamic_object_size(q, 3), 0); + expect(__builtin_dynamic_object_size(q, 2), 0); + + DONE (); +} diff --git a/gcc/tree-object-size.cc b/gcc/tree-object-size.cc index a62af0500563..cf7843c5684b 100644 --- a/gcc/tree-object-size.cc +++ b/gcc/tree-object-size.cc @@ -585,6 +585,7 @@ addr_object_size (struct object_size_info *osi, const_tree ptr, if (pt_var != TREE_OPERAND (ptr, 0)) { tree var; + tree counted_by_ref = NULL_TREE; if (object_size_type & OST_SUBOBJECT) { @@ -600,11 +601,12 @@ addr_object_size (struct object_size_info *osi, const_tree ptr, var = TREE_OPERAND (var, 0); if (var != pt_var && TREE_CODE (var) == ARRAY_REF) var = TREE_OPERAND (var, 0); - if (! TYPE_SIZE_UNIT (TREE_TYPE (var)) + if (! component_ref_has_counted_by_p (var) + && ((! TYPE_SIZE_UNIT (TREE_TYPE (var)) || ! tree_fits_uhwi_p (TYPE_SIZE_UNIT (TREE_TYPE (var))) || (pt_var_size && TREE_CODE (pt_var_size) == INTEGER_CST && tree_int_cst_lt (pt_var_size, - TYPE_SIZE_UNIT (TREE_TYPE (var))))) + TYPE_SIZE_UNIT (TREE_TYPE (var))))))) var = pt_var; else if (var != pt_var && TREE_CODE (pt_var) == MEM_REF) { @@ -612,6 +614,7 @@ addr_object_size (struct object_size_info *osi, const_tree ptr, /* For &X->fld, compute object size if fld isn't a flexible array member. */ bool is_flexible_array_mem_ref = false; + while (v && v != pt_var) switch (TREE_CODE (v)) { @@ -660,6 +663,8 @@ addr_object_size (struct object_size_info *osi, const_tree ptr, /* Now the ref is to an array type. */ gcc_assert (TREE_CODE (TREE_TYPE (v)) == ARRAY_TYPE); is_flexible_array_mem_ref = array_ref_flexible_size_p (v); + counted_by_ref = component_ref_get_counted_by (v); + while (v != pt_var && TREE_CODE (v) == COMPONENT_REF) if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0))) != UNION_TYPE @@ -673,8 +678,11 @@ addr_object_size (struct object_size_info *osi, const_tree ptr, == RECORD_TYPE) { /* compute object size only if v is not a - flexible array member. */ - if (!is_flexible_array_mem_ref) + flexible array member or the flexible array member + has a known element count indicated by the user + through attribute counted_by. */ + if (!is_flexible_array_mem_ref + || counted_by_ref) { v = NULL_TREE; break; @@ -707,9 +715,24 @@ addr_object_size (struct object_size_info *osi, const_tree ptr, if (var != pt_var) { - var_size = TYPE_SIZE_UNIT (TREE_TYPE (var)); - if (!TREE_CONSTANT (var_size)) - var_size = get_or_create_ssa_default_def (cfun, var_size); + if (!counted_by_ref) + { + var_size = TYPE_SIZE_UNIT (TREE_TYPE (var)); + if (!TREE_CONSTANT (var_size)) + var_size = get_or_create_ssa_default_def (cfun, var_size); + } + else + { + gcc_assert (TREE_CODE (var) == COMPONENT_REF + && TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE); + tree element_size = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (var))); + var_size + = size_binop (MULT_EXPR, + fold_convert (sizetype, counted_by_ref), + fold_convert (sizetype, element_size)); + if (!todo) + todo = TODO_update_ssa_only_virtuals; + } if (!var_size) return false; } diff --git a/gcc/tree.cc b/gcc/tree.cc index fcd36ae0cd74..c46b73be3906 100644 --- a/gcc/tree.cc +++ b/gcc/tree.cc @@ -12745,6 +12745,32 @@ array_ref_element_size (tree exp) return SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (elmt_type), exp); } +/* For a component_ref that has an array type ARRAY_REF, return TRUE when + an counted_by attribute attached to the corresponding FIELD_DECL. + return FALSE otherwise. */ +bool +component_ref_has_counted_by_p (tree array_ref) +{ + if (TREE_CODE (array_ref) != COMPONENT_REF) + return false; + + if (TREE_CODE (TREE_TYPE (array_ref)) != ARRAY_TYPE) + return false; + + tree struct_object = TREE_OPERAND (array_ref, 0); + tree struct_type = TREE_TYPE (struct_object); + + if (!RECORD_OR_UNION_TYPE_P (struct_type)) + return false; + tree field_decl = TREE_OPERAND (array_ref, 1); + tree attr_counted_by = lookup_attribute ("counted_by", + DECL_ATTRIBUTES (field_decl)); + + if (!attr_counted_by) + return false; + return true; +} + /* Given a field list, FIELDLIST, of a structure/union, return a TREE_LIST, with each TREE_VALUE a FIELD_DECL stepping down the chain to the FIELD whose name is FIELDNAME, which is the last TREE_VALUE of the list. @@ -12771,7 +12797,7 @@ get_named_field (tree fieldlist, const char *fieldname) fields inside it recursively. */ else if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (field))) if ((named_field = get_named_field (TYPE_FIELDS (TREE_TYPE (field)), - fieldname)) != NULL_TREE) + fieldname)) != NULL_TREE) { named_field = tree_cons (NULL_TREE, field, named_field); break; @@ -12784,6 +12810,73 @@ get_named_field (tree fieldlist, const char *fieldname) return named_field; } +/* For a component_ref that has an array type ARRAY_REF, get the object that + represents its counted_by per the attribute counted_by attached to + the corresponding FIELD_DECL. return NULL_TREE when cannot find such + object. + For example, if: + + struct P { + int k; + int x[] __attribute__ ((counted_by (k))); + } *p; + + for the following reference: + + p->x[b] + + the object that represents its element count will be: + + p->k + + So, when component_ref_get_counted_by (p->x[b]) is called, p->k should be + returned. +*/ + +tree +component_ref_get_counted_by (tree array_ref) +{ + if (! component_ref_has_counted_by_p (array_ref)) + return NULL_TREE; + + tree struct_object = TREE_OPERAND (array_ref, 0); + tree struct_type = TREE_TYPE (struct_object); + tree field_decl = TREE_OPERAND (array_ref, 1); + tree attr_counted_by = lookup_attribute ("counted_by", + DECL_ATTRIBUTES (field_decl)); + gcc_assert (attr_counted_by); + + /* If there is an counted_by attribute attached to the field, + get the field that maps to the counted_by. */ + + const char *fieldname + = IDENTIFIER_POINTER (TREE_VALUE (TREE_VALUE (attr_counted_by))); + + tree counted_by_field = get_named_field (TYPE_FIELDS (struct_type), + fieldname); + + gcc_assert (counted_by_field); + + /* generate the tree node that represent the counted_by of this array + ref. This is a (possible nested) COMPONENT_REF to the counted_by_field + of the containing structure. */ + + tree counted_by_ref = NULL_TREE; + tree object = struct_object; + do + { + tree field = TREE_VALUE (counted_by_field); + + counted_by_ref = build3 (COMPONENT_REF, + TREE_TYPE (field), + object, field, + NULL_TREE); + object = counted_by_ref; + counted_by_field = TREE_CHAIN (counted_by_field); + } + while (counted_by_field); + return counted_by_ref; +} /* Return a tree representing the lower bound of the array mentioned in EXP, an ARRAY_REF or an ARRAY_RANGE_REF. */ diff --git a/gcc/tree.h b/gcc/tree.h index 4859becaa1e7..07eed7219835 100644 --- a/gcc/tree.h +++ b/gcc/tree.h @@ -5619,11 +5619,21 @@ extern tree get_base_address (tree t); of EXP, an ARRAY_REF or an ARRAY_RANGE_REF. */ extern tree array_ref_element_size (tree); +/* Give a component_ref that has an array type, return true when an + attribute counted_by attached to the corresponding FIELD_DECL. */ +extern bool component_ref_has_counted_by_p (tree); + /* Given a field list, FIELDLIST, of a structure/union, return the FIELD whose name is FIELDNAME, return NULL_TREE if such field is not found. searching nested anonymous structure/union recursively. */ extern tree get_named_field (tree, const char *); +/* Give a component_ref that has an array type, return the object that + represents its counted_by per the attribute counted_by attached to + the corresponding FIELD_DECL. return NULL_TREE when cannot find such + object. */ +extern tree component_ref_get_counted_by (tree); + /* Return a typenode for the "standard" C type with a given name. */ extern tree get_typenode_from_name (const char *); From patchwork Fri Aug 4 19:44:31 2023 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Qing Zhao X-Patchwork-Id: 1817149 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@legolas.ozlabs.org Authentication-Results: legolas.ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=gcc.gnu.org (client-ip=2620:52:3:1:0:246e:9693:128c; helo=server2.sourceware.org; envelope-from=gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org; receiver=) Authentication-Results: legolas.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=x1Erpxlq; dkim-atps=neutral Received: from server2.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 ECDSA (P-384) server-digest SHA384) (No client certificate requested) by legolas.ozlabs.org (Postfix) with ESMTPS id 4RHbn51GzWz1yYl for ; Sat, 5 Aug 2023 05:46:17 +1000 (AEST) Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 2001D3856090 for ; Fri, 4 Aug 2023 19:46:15 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 2001D3856090 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gcc.gnu.org; s=default; t=1691178375; bh=SNqfakuZVvHesD2uGuzIxEdFWiKmjgy1HEa9PmhjCVs=; h=To:Cc:Subject:Date:In-Reply-To:References:List-Id: List-Unsubscribe:List-Archive:List-Post:List-Help:List-Subscribe: From:Reply-To:From; b=x1ErpxlqL25NK1VHG6CvHeRDb7IzIlSSp/nMzK3d1OsZ8PU2mHWGKsmlOBL+Qea6s kKXhPbzLabLWmIQJhbc70K72gH6+qUTOVU7VU7YRvaKB7LwrZSXcXmIFWXQVncXzwX J7adV9z1PsP/JD/W6FkI/SWtT6iM2HHUAYMXyx3k= X-Original-To: gcc-patches@gcc.gnu.org Delivered-To: gcc-patches@gcc.gnu.org Received: from mx0b-00069f02.pphosted.com (mx0b-00069f02.pphosted.com [205.220.177.32]) by sourceware.org (Postfix) with ESMTPS id 02559385734F for ; Fri, 4 Aug 2023 19:44:56 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 02559385734F Received: from pps.filterd (m0246630.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.17.1.19/8.17.1.19) with ESMTP id 374JClMj003603; Fri, 4 Aug 2023 19:44:55 GMT Received: from iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (iadpaimrmta03.appoci.oracle.com [130.35.103.27]) by mx0b-00069f02.pphosted.com (PPS) with ESMTPS id 3s4s6ecfcy-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Fri, 04 Aug 2023 19:44:54 +0000 Received: from pps.filterd (iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com [127.0.0.1]) by iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (8.17.1.19/8.17.1.19) with ESMTP id 374Ip91b034983; Fri, 4 Aug 2023 19:44:54 GMT Received: from nam10-mw2-obe.outbound.protection.outlook.com (mail-mw2nam10lp2100.outbound.protection.outlook.com [104.47.55.100]) by iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (PPS) with ESMTPS id 3s8m09u9mv-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Fri, 04 Aug 2023 19:44:54 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=F/Fptzfc9RRM/q7eqw36wXLYOos7S6GNsYRb1lMstZyLB0gp7s0Q72QVIRt8uaVEPNceDfO7o2h6U2IQp+TbMAASbj6dP7zZzwNvUPw2bbyxT1Z2PxiQtC0/IQ+jXfhZxGMDcdcdnG4EhCfrbgO9PLRb/KZkLje5bMKkhtDAH1qjIcotk7B8cU57M+HA1IGGWXYZpA/w+uzzFGFgyhNPFOrIh2a3xKBbJF4cDnq5fRWqkWDgCeMhSpztqTWZq9uguzE7v95R5jG+6UtuVyIcfc9TVLdZF2EUx1mxsaBlA54KJ4lEYHBvRQVMrpFL4+RD3KgwrGO0JanMUXb0AfvtLg== 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=SNqfakuZVvHesD2uGuzIxEdFWiKmjgy1HEa9PmhjCVs=; b=f727VSKqiBQ3ERjKfjvh7ylzaIM2czOkrPG5mVbYznTS78hjbBrdTUSRj98DpWmi2Re1HhZPaUjGgCBPQGtYDbm8+7I3In1i/Hvi07YdrEkKeTkxCwx2BX5u2V3Xl+GGGy/Rmvp1f7FBxgrbymaWmPXA4hedh/wqADHJAprqxa7Hg38em5HymaTYW0IRfslL7hmTwOYyh+t3niZlCd+M1HOKNDSbw/uimD+OoKsLL5Iogp2uIfUCPpZZZgyr2WAompBTfs33MTXg7f1BKw8LCkhzySjymKnVM01FVIt2fzq72WR9LRRu+1CTL8Eg9lNmZNVfedufgN7OLwWHEPvH5w== ARC-Authentication-Results: i=1; mx.microsoft.com 1; spf=pass smtp.mailfrom=oracle.com; dmarc=pass action=none header.from=oracle.com; dkim=pass header.d=oracle.com; arc=none Received: from CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) by MW6PR10MB7590.namprd10.prod.outlook.com (2603:10b6:303:24c::11) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.6631.47; Fri, 4 Aug 2023 19:44:51 +0000 Received: from CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::5afd:d02a:38ef:94ba]) by CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::5afd:d02a:38ef:94ba%7]) with mapi id 15.20.6652.020; Fri, 4 Aug 2023 19:44:51 +0000 To: joseph@codesourcery.com, richard.guenther@gmail.com, jakub@redhat.com, gcc-patches@gcc.gnu.org Cc: keescook@chromium.org, siddhesh@gotplt.org, uecker@tugraz.at, isanbard@gmail.com, Qing Zhao Subject: [V2][PATCH 3/3] Use the counted_by attribute information in bound sanitizer[PR108896] Date: Fri, 4 Aug 2023 19:44:31 +0000 Message-Id: <20230804194431.993958-4-qing.zhao@oracle.com> X-Mailer: git-send-email 2.31.1 In-Reply-To: <20230804194431.993958-1-qing.zhao@oracle.com> References: <20230804194431.993958-1-qing.zhao@oracle.com> X-ClientProxiedBy: SJ0PR13CA0060.namprd13.prod.outlook.com (2603:10b6:a03:2c2::35) To CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: CH2PR10MB4344:EE_|MW6PR10MB7590:EE_ X-MS-Office365-Filtering-Correlation-Id: 361c2273-4b11-41b4-34c5-08db952344ec X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; X-Microsoft-Antispam-Message-Info: 5IIcPWJrz/g65oEOP6Lj/lhcgYdjXO0i9pQqhMxVj3YmeDMcn0w+TPIqyVy4+6yNKksn1NUJYuQTyo7xH0bYs9GwKeW4gkArLO0rayAlc36F6h/A8WM8X3Tdn4crcFbU3H1wQWHYe4z3nJFNMbnX1LZb1qsxCC3HgOn38nuoejCPF3u0ceOWSMTp2jG2G/6XATV6YzCnL6wdlHE26VQ6qd6oT1OuWXFa98FT0uyaC9sfAdlMjtA3W0lU4M7qwFgHPZs44qm2VhOLZcH3ml8UZpjKxPeoWGbGfzt6fJKZS7wFPE8gyfsVZmINIS5aP2rVuj4vBpHffn2KDW51mZzazsRo6VJfwmragtPUYpiIXf2xIfAnKa8xkINCvfY2lGe4chcn9Tq16kjAtD0BJzM+ecNl4QANIhnSxyR7M96dSuOWGCNR+OJJ0Z/XPFxnRYcKUa/8teT5ZML7vIWRjO51Zc5K0SU0jE+CmS85J/oq5lRXRaL6eiucFOuRaIChenV/n8FoVQ6PrCrLxwqvLhRwwMwTlgNgnvL7lzsBqAtoCVQ= X-Forefront-Antispam-Report: CIP:255.255.255.255; CTRY:; LANG:en; SCL:1; SRV:; IPV:NLI; SFV:NSPM; H:CH2PR10MB4344.namprd10.prod.outlook.com; PTR:; CAT:NONE; SFS:(13230028)(346002)(39860400002)(136003)(376002)(396003)(366004)(451199021)(1800799003)(186006)(1076003)(2616005)(107886003)(6506007)(26005)(8676002)(66556008)(2906002)(316002)(66946007)(5660300002)(66476007)(4326008)(41300700001)(8936002)(44832011)(6486002)(6512007)(6666004)(478600001)(38100700002)(36756003)(86362001)(84970400001); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: fqhLof7opbGCW1w9I7gRCaY3hGLtvPhPjGlxuRzzeZbOayLZT1WxqQVcvt+yxFZYOAnlCKSgDlgwmt7BB/CGnMrFkMgE2g0CD0knBDKNZPS0JSvDkgIBJwFrWUBmxUfcwaV3Ea4DrTorWZIqlB9EO5fZQn/sd4kRGDLTkEFEqJZL1wHDmS5MslEdTONu5FoxmJfK2lprTNQPmm/Gute9szD8SRefBw3ldYTYO+7DD8NiK+nLrPYVjPJO1d4UZgWbRHq9iQzBgAZm2BTTATSbg8xZI/DjrJX5cm+yR3/VCE4ytISs0mnHoFQmvrZ36nQP+XoRaocliWGhSfqdet0iSw+7bDl61a1lDdRGQvO1yL6//WrRVATrGIsh3oyff2YwH3j15ZsIsnIkxKCBcIMssdj6Fsn5ozvoCbqef1yNNJcOFP5peuumA1UensaNjYSr9x6cdnlCbbyM0TO3brTmEOow/XsCsyC/sqXeXGPOMw06w3grBMDzz2mH8PWP8RB4mKYhwOb0XKfVZ5qesiYxI555GVv0azqMIaJV9U9M87RdQkVbqLF/pj23H3a2OdSiUX5bn9bBplRL6WwcxVo9nhpavWjoodH6XAUoqSqv5A3EQ62gIgw6YFNIYGNvbnm7Ak+awlfec8w+w/7M7hjuBD+QJzAUC2DK/9wO9dTgT83xvPqbuxJgC1h9G6a7d1E2PpUsn/Lmjk0STxGdAc9JE/471XS0rZOqvr/8yXVlvSqIdX5tZXiJ/ZazLJF25W9Zn2zHg0yoFcRIp4ZzYQExuYpyd5p+hfRLh0HtTxFYTKLrCITNA5HGg41WIKCCsgxvhhdiOJ/lrvNf+vIlZI7lhhhAy+YJ2hLFS29McQ1h+1uoJZRcILv4JWiJ+ms53478UvhurOOdIug01uSQ5QjMbjPQuEhj5WiXIWTSiUcxPB1OJMc4egYCGa8Ir3+0tn7remrPlvbW1B/XcUyKh8AH8tdixcyGT7khVIr9Cju4xmZg5SpVptb/WCKuMR8pmASZCCzW4m7NxgJGmdk95gD9dNf0k8AZfbFlhJIUlZ0CbyUTtUwEB7SoarbAeOcsPitUuBQhyzaoQtj6B3/7vH/9EntjlSP8ZWq2jIk2/BsZRsaKN9moy6eKb40MOtApZqw9qvsnolbmy+P8Npi/+Nx3FPAjXrOtVw7YjGvCX+Od3H2kwS0D9Lgp1aH0z9UiquASrhHOjSluMvJ2SGnsGo7NntMyOgU1+t6WV8xLJsTkL7hYOFgxwIIZwuKkYtuiw/Z8W5+G/BixGQDv/I0+AwqtVRno0TEwOym5SfSDBlQroQL3XRyIaDLWy1pteEoQMCbAJjwJjipO04Jhz0ZjtJNM+wmk2w0eTtT8ju8+6Jk8EM5a7YNHU2zdgEnS7/RTIzocEht50PJ3eJrgstdWorEPrwpVW11WZvDBCux0hqmi3p467jnm1cF2ZNC+b5TYIDDnloBHnjZ+0xXzKKQ6ge22GNHMLHybVWA+I0cgEkkmn8fws0KaPVE65ed8QZocOmvQxAB/107vAex7bC7vscYofjrJMOGul4+cInA73OjWbRiASzsK5R84LMJ0HlP2Lxf6 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: xiDTfBpLXtOWqUEF9nXad7MIcO0ndsrdu8c+VvnjUTzSAeW8Rh2kH/dLpdmILQD4EqdszPCvPSJn8Li7C8jUySUPBwdjHi2NyXSi6JjLYz4HBY55dLrjEGc8/yTRqoYHt6fphJVAbmxgZ4lO/EbY2C2gcpPIQYSbz5cBsSKh+JBE01QjsWcTASAk884yVbfigoMyaj+yrxDgaU6RVdtqDmNgDwRE2rc2ZJfgcn+wfdd2KoPks5C4XhN8U9QQPZ569Xs5thVePJ4C9IMa4xFLZQ+HuLxRMEawGBkwkYnULKTVMUW13maF0zLvey1zHfBuYa/0wAn8jD4Mt5psfzHVWTsOWwcB11ImgfN6vWhRDHz/NdasMdtfbS5JEullFRLdSjEuf7n/CXtlEKEZXjRJo2P38kXQ4Vz+h48oOlxW5WBaQXDqqClGzVef109sr+lGwgIGrkE7nK9AXKhc4Mba9DsNzH/Afm2QJupxb0Vxj7qcCDrU2qw+OWHZHISfFNUY97d7W3NsUSisBwIne2Nppm/pwen1yDM9I9AIPr6aw4AuG64v7L9CuCydRjs2Sw42h5stNHYABEBkiLWMT6x7nm6bqdxz3oR2O47U7Ibuj/IgBwEA8hIynG7ih35UhDZ9Kb60g5TahZTMisJ/XjxCk2WK+ZydaK45scAAkv50iCvlhUppCHkCKCmIMmsYmRrAqkEzl2nC/DM7MDWFFQwamwIn6vqy5d85P7CwU3qXIhEvmLflLjplP5ab0OgW19dEdr1+HWlcQiWGEUSTtP1v9tztYb/r/sUBI136qhkhbpNeqJR7gwTc/gIwYFUhsiFXSYCB1kfK2ZcgC6uwYbgXSQcq2+IDblkjQU4m9PpHGgMDpXXfn/5AtTcg9srjwiZ0jy6qNRjtgZqrRAs+Hq8wM7N7LnGaTe9hNE42qTX1T6fTVCTiXe5Tu3OzmigTmc3B X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 361c2273-4b11-41b4-34c5-08db952344ec X-MS-Exchange-CrossTenant-AuthSource: CH2PR10MB4344.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 04 Aug 2023 19:44:51.7523 (UTC) X-MS-Exchange-CrossTenant-FromEntityHeader: Hosted X-MS-Exchange-CrossTenant-Id: 4e2c6054-71cb-48f1-bd6c-3a9705aca71b X-MS-Exchange-CrossTenant-MailboxType: HOSTED X-MS-Exchange-CrossTenant-UserPrincipalName: rF2I54slgy7hvBIKkmB+WR6KwUyjBzqi1m7rsANtGKsUeKQXTzXRQ6SBTblXFnmH3pphiq+tEhMXp9vXUSLGMA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: MW6PR10MB7590 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.267,Aquarius:18.0.957,Hydra:6.0.591,FMLib:17.11.176.26 definitions=2023-08-04_20,2023-08-03_01,2023-05-22_02 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 adultscore=0 mlxscore=0 phishscore=0 bulkscore=0 suspectscore=0 mlxlogscore=785 spamscore=0 malwarescore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2306200000 definitions=main-2308040177 X-Proofpoint-GUID: QPtf8H9F7nr1pYJE6NewuuEQuJYJ_q1Z X-Proofpoint-ORIG-GUID: QPtf8H9F7nr1pYJE6NewuuEQuJYJ_q1Z X-Spam-Status: No, score=-11.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, GIT_PATCH_0, RCVD_IN_DNSWL_LOW, RCVD_IN_MSPIKE_H5, RCVD_IN_MSPIKE_WL, SPF_HELO_NONE, SPF_NONE, TXREP 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: Qing Zhao via Gcc-patches From: Qing Zhao Reply-To: Qing Zhao Errors-To: gcc-patches-bounces+incoming=patchwork.ozlabs.org@gcc.gnu.org Sender: "Gcc-patches" gcc/c-family/ChangeLog: PR C/108896 * c-ubsan.cc (ubsan_instrument_bounds): Use counted_by attribute information. gcc/testsuite/ChangeLog: PR C/108896 * gcc.dg/ubsan/flex-array-counted-by-bounds.c: New test. * gcc.dg/ubsan/flex-array-counted-by-bounds-2.c: New test. --- gcc/c-family/c-ubsan.cc | 16 +++++++ .../ubsan/flex-array-counted-by-bounds-2.c | 27 +++++++++++ .../ubsan/flex-array-counted-by-bounds.c | 46 +++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds-2.c create mode 100644 gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds.c diff --git a/gcc/c-family/c-ubsan.cc b/gcc/c-family/c-ubsan.cc index 51aa83a378d2..a99e8433069f 100644 --- a/gcc/c-family/c-ubsan.cc +++ b/gcc/c-family/c-ubsan.cc @@ -362,6 +362,10 @@ ubsan_instrument_bounds (location_t loc, tree array, tree *index, { tree type = TREE_TYPE (array); tree domain = TYPE_DOMAIN (type); + /* whether the array ref is a flexible array member with valid counted_by + attribute. */ + bool fam_has_count_attr = false; + tree counted_by = NULL_TREE; if (domain == NULL_TREE) return NULL_TREE; @@ -375,6 +379,17 @@ ubsan_instrument_bounds (location_t loc, tree array, tree *index, && COMPLETE_TYPE_P (type) && integer_zerop (TYPE_SIZE (type))) bound = build_int_cst (TREE_TYPE (TYPE_MIN_VALUE (domain)), -1); + /* If the array ref is to flexible array member field which has + counted_by attribute. We can use the information from the + attribute as the bound to instrument the reference. */ + else if ((counted_by = component_ref_get_counted_by (array)) + != NULL_TREE) + { + fam_has_count_attr = true; + bound = fold_build2 (MINUS_EXPR, TREE_TYPE (counted_by), + counted_by, + build_int_cst (TREE_TYPE (counted_by), 1)); + } else return NULL_TREE; } @@ -387,6 +402,7 @@ ubsan_instrument_bounds (location_t loc, tree array, tree *index, -fsanitize=bounds-strict. */ tree base = get_base_address (array); if (!sanitize_flags_p (SANITIZE_BOUNDS_STRICT) + && !fam_has_count_attr && TREE_CODE (array) == COMPONENT_REF && base && (INDIRECT_REF_P (base) || TREE_CODE (base) == MEM_REF)) { diff --git a/gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds-2.c b/gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds-2.c new file mode 100644 index 000000000000..77ec333509d0 --- /dev/null +++ b/gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds-2.c @@ -0,0 +1,27 @@ +/* test the attribute counted_by and its usage in + bounds sanitizer combined with VLA. */ +/* { dg-do run } */ +/* { dg-options "-fsanitize=bounds" } */ + +#include + +void __attribute__((__noinline__)) setup_and_test_vla (int n, int m) +{ + struct foo { + int n; + int p[][n] __attribute__((counted_by(n))); + } *f; + + f = (struct foo *) malloc (sizeof(struct foo) + m*sizeof(int[n])); + f->n = m; + f->p[m][n-1]=1; + return; +} + +int main(int argc, char *argv[]) +{ + setup_and_test_vla (10, 11); + return 0; +} + +/* { dg-output "17:8: runtime error: index 11 out of bounds for type" } */ diff --git a/gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds.c b/gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds.c new file mode 100644 index 000000000000..81eaeb3f2681 --- /dev/null +++ b/gcc/testsuite/gcc.dg/ubsan/flex-array-counted-by-bounds.c @@ -0,0 +1,46 @@ +/* test the attribute counted_by and its usage in + bounds sanitizer. */ +/* { dg-do run } */ +/* { dg-options "-fsanitize=bounds" } */ + +#include + +struct flex { + int b; + int c[]; +} *array_flex; + +struct annotated { + int b; + int c[] __attribute__ ((counted_by (b))); +} *array_annotated; + +void __attribute__((__noinline__)) setup (int normal_count, int annotated_count) +{ + array_flex + = (struct flex *)malloc (sizeof (struct flex) + + normal_count * sizeof (int)); + array_flex->b = normal_count; + + array_annotated + = (struct annotated *)malloc (sizeof (struct annotated) + + annotated_count * sizeof (int)); + array_annotated->b = annotated_count; + + return; +} + +void __attribute__((__noinline__)) test (int normal_index, int annotated_index) +{ + array_flex->c[normal_index] = 1; + array_annotated->c[annotated_index] = 2; +} + +int main(int argc, char *argv[]) +{ + setup (10, 10); + test (10, 10); + return 0; +} + +/* { dg-output "36:21: runtime error: index 10 out of bounds for type" } */