Message ID | 20230525161450.3704901-1-qing.zhao@oracle.com |
---|---|
Headers |
Return-Path: <gcc-patches-bounces+ouuuleilei=gmail.com@gcc.gnu.org> Delivered-To: ouuuleilei@gmail.com Received: by 2002:a59:994d:0:b0:3d9:f83d:47d9 with SMTP id k13csp490554vqr; Thu, 25 May 2023 09:16:44 -0700 (PDT) X-Google-Smtp-Source: ACHHUZ5MR5nCKEzfq5MK4uJbal/H4gXUdEo1ZSgn2B80Dm+5og8GDXqVuzgj2/DDtFnqEH0komMt X-Received: by 2002:a17:907:803:b0:966:335a:5b07 with SMTP id wv3-20020a170907080300b00966335a5b07mr1904106ejb.62.1685031403992; Thu, 25 May 2023 09:16:43 -0700 (PDT) Received: from sourceware.org (server2.sourceware.org. [2620:52:3:1:0:246e:9693:128c]) by mx.google.com with ESMTPS id dn15-20020a17090794cf00b0094ee6dcf95dsi1458710ejc.80.2023.05.25.09.16.43 for <ouuuleilei@gmail.com> (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Thu, 25 May 2023 09:16:43 -0700 (PDT) Received-SPF: pass (google.com: domain of gcc-patches-bounces+ouuuleilei=gmail.com@gcc.gnu.org designates 2620:52:3:1:0:246e:9693:128c as permitted sender) client-ip=2620:52:3:1:0:246e:9693:128c; Authentication-Results: mx.google.com; dkim=pass header.i=@gcc.gnu.org header.s=default header.b="kq/2PLHp"; arc=fail (signature failed); spf=pass (google.com: domain of gcc-patches-bounces+ouuuleilei=gmail.com@gcc.gnu.org designates 2620:52:3:1:0:246e:9693:128c as permitted sender) smtp.mailfrom="gcc-patches-bounces+ouuuleilei=gmail.com@gcc.gnu.org"; dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=gnu.org Received: from server2.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 935D43856275 for <ouuuleilei@gmail.com>; Thu, 25 May 2023 16:15:55 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 935D43856275 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gcc.gnu.org; s=default; t=1685031355; bh=JgZWyXk0jiVsut+oa8NUOGIGzhktqmPdwLI//SrRphE=; h=To:Cc:Subject:Date:List-Id:List-Unsubscribe:List-Archive: List-Post:List-Help:List-Subscribe:From:Reply-To:From; b=kq/2PLHpFvIV2iC5ptGAbL17X8+x4W8ZPv26UjrTH+V1msLMUL03dJwnTkxgUHsUU zo94dNkoNNkWaxoYM2kBp9EI3v9erM/ITIXhOSllDmRTiez65r0yHX7JGqaSSLlU56 EcTlHgj2oXkH3fFcnqQTWV9FV+TvUbvh/O4NaDpg= 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 A05A03858D32 for <gcc-patches@gcc.gnu.org>; Thu, 25 May 2023 16:15:04 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org A05A03858D32 Received: from pps.filterd (m0246632.ppops.net [127.0.0.1]) by mx0b-00069f02.pphosted.com (8.17.1.19/8.17.1.19) with ESMTP id 34PGEoPA031893; Thu, 25 May 2023 16:15:01 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 3qtb0y802a-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 25 May 2023 16:15:00 +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 34PFhWBE015767; Thu, 25 May 2023 16:15:00 GMT Received: from nam11-co1-obe.outbound.protection.outlook.com (mail-co1nam11lp2177.outbound.protection.outlook.com [104.47.56.177]) by iadpaimrmta03.imrmtpd1.prodappiadaev1.oraclevcn.com (PPS) with ESMTPS id 3qqk6nccf9-1 (version=TLSv1.2 cipher=ECDHE-RSA-AES256-GCM-SHA384 bits=256 verify=OK); Thu, 25 May 2023 16:15:00 +0000 ARC-Seal: i=1; a=rsa-sha256; s=arcselector9901; d=microsoft.com; cv=none; b=FefzgErxKmDNNx2iLqHnyXnvOLjdpgFrseq37hfukSsVdcy/HPfe1SfrELpOxSAhT+dvDcX8e+GJ0xIRXgW5VUfg+a4gQvk4OMGdHOuWAGyGsEtXgYbY7U6fi/AGDv4g0KuPa5I8UQbQpsI7iKwYvsg5aWIZDLdqZLQbEf5vGxpBMAHL3w4KbzUBgHN1r55mFfwC9+G23EyeDu8Qnk4zUeCEFzoWIAWI5kEnkOP6hj3f2ToxOoqZCQYUIpqOve90KJB70fM22LRJRqxCBPsoGh4FLk8v1t4PwWqRavK578inD0VN4DqQ+7w1rhorb8ktbSONLrYTNyAZqcue7FcK+g== 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=JgZWyXk0jiVsut+oa8NUOGIGzhktqmPdwLI//SrRphE=; b=Lvx2U62SSHHx52NVo9zT2znXp1eg8eSKRGDqOpfRkOz+lPVl6I3/5EaTxhFiN5Fq0emEXr3KKsdapE4ZSiT0uDDh4VLtFImgH9dJv16ieTkdEp0Zu1bAg68whtuZZUZNrochzj7iIdNNlJfcVYzzm76i4r9AP9+B3jkKpNr8hHB6noXFD+RWy4IevOJTfke6hdguzifNJ82FOaP1EIa+5fjk493x7BzlKiPNYKqjpaoUNVMsabmSPIIp1DRMBe2+Uq7N9KB5fvm3XcRZPy0EQxoCIv0pYm4Q2jAsM02HdANBagK3u8nT/qqHRFVuFd2waAC6Jw22D/Fr3Yxj0LNZlQ== 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 BLAPR10MB5041.namprd10.prod.outlook.com (2603:10b6:208:30e::6) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.6433.15; Thu, 25 May 2023 16:14:57 +0000 Received: from CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::7aa1:df38:105a:21fa]) by CH2PR10MB4344.namprd10.prod.outlook.com ([fe80::7aa1:df38:105a:21fa%7]) with mapi id 15.20.6411.028; Thu, 25 May 2023 16:14:57 +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 <qing.zhao@oracle.com> Subject: [V1][PATCH 0/3] New attribute "element_count" to annotate bounds for C99 FAM(PR108896) Date: Thu, 25 May 2023 16:14:47 +0000 Message-Id: <20230525161450.3704901-1-qing.zhao@oracle.com> X-Mailer: git-send-email 2.31.1 Content-Transfer-Encoding: 8bit Content-Type: text/plain X-ClientProxiedBy: LO4P123CA0139.GBRP123.PROD.OUTLOOK.COM (2603:10a6:600:193::18) To CH2PR10MB4344.namprd10.prod.outlook.com (2603:10b6:610:af::19) MIME-Version: 1.0 X-MS-PublicTrafficType: Email X-MS-TrafficTypeDiagnostic: CH2PR10MB4344:EE_|BLAPR10MB5041:EE_ X-MS-Office365-Filtering-Correlation-Id: 2bb6781b-7324-4081-a501-08db5d3b2eee X-MS-Exchange-SenderADCheck: 1 X-MS-Exchange-AntiSpam-Relay: 0 X-Microsoft-Antispam: BCL:0; X-Microsoft-Antispam-Message-Info: 3GlCUIZTlb5qVvmrauG97Kj3C4avXFHn40TxwSa540wBd41vGsyFPP2yfs+X+A6WBUERPeChoAagmVnjzeB1+G0MrRkMtgIAEsalZ73XyaHEoQ2dcxwpA73RYx63meimTC/kWn6hfmS3xVIgBDLpmak3oGI9PdBKyocgQDFrPwPLfGv9k2R14w7x3BGyR7gc7ELxJ+ByzT4vBGnMagf3mzhXdMmtzZIf0b7R2ZgA+JsuGX2HD6z45mYXB4FWMwWCcEDKoSP4GtCsEEw9W19hpEESy1556IUFgPfKcbrNPg5qHF0So3F5Hzbq/uTFzR2cku6+CG4VUpOJMixRnKcqn9J1V3QaYbTmg9kooefN/xh7EjxW7BNkAuzb9p8g689JK7ZBkvhHhvaHgir1uVFCdvbj4HtcYJ7JAlHFuz5DSN0sR8hBocAzMnnfjucAn5ashqTyWf61IxNB7nRiDW17Q6U/jiphVi/dHK8KD6M0GNB5HFQVtuJoUx44Tshj0ScVbAvwIvuhemNW3szoujUczYbeT27uSMKisEFZWvSw8QPUOBqWTG1DWSy9MiqoK8ANgo+LZEURyKdLGlRZ/eZduA== 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)(366004)(396003)(376002)(136003)(451199021)(2906002)(86362001)(83380400001)(186003)(2616005)(38100700002)(8936002)(36756003)(5660300002)(8676002)(316002)(44832011)(41300700001)(966005)(6506007)(107886003)(26005)(6512007)(6666004)(1076003)(4326008)(66476007)(66556008)(66946007)(478600001)(6486002); DIR:OUT; SFP:1101; X-MS-Exchange-AntiSpam-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-MessageData-0: 8k6+zQKoIx3GMexuQnlBkU8UrlepuRVyGhoDcDDpZhf820sXwDH2bBJ1cc98HYn1il8KQDwEQViY06U/rxFl1xGQbuk+JSYh7HrDpOphcOS+0ibZemzofoDU7cq61a6NpMtgHy5nlZiFz14xJmPLEL9AoD4xEz9eX2AeigpGwTUFLvKhrXVOu1yKscDVvRDwk+AWh22ZYpL9fLVhI3xVHE73Krr12L1O++Dnk/BAxBZHZq5685ANKzD4g3mLiMMz8eAEzzOwQLOb3mBQ31xOHAPEl3am5Ksphv/1K4mD5Bt1D4Z9Tp1p7nY6A0M2uvyDk9b5i28eNzEKF99urMPqVMnj7o+G+6L0a4DsJLGkAn7VtCL1U7KCA67ma2t3/WX73nQ7llbBNx4wftqmLjLk103O7ykwozT41XA326T+/+7Z+xV3FX+b7HfqFE9XCJnvATV+IDXkoBTZTf0uYwwVfeCQntTvoNS9uOwPVk6Fb96q+E1ONfDDUPJgGUajyfpTZHw6qDKF6tEI5DoXveV6v8MAUwNhvR6SdKRaCAr56WHDGr9MYbxJDpFTTzllYM21OZEE+eqCu62Ic/b7WfbGhPTF0nrrOrRx07uSOgivgxkEfj9KSPWoWt4U7ufyHFsr92a/Sxl//pUzAC17HigODMeANpN6bR+6rdwNH92CshZMGXYjz9i7o3HTtlV2BY5mghzqhDgY4kh7tucynvRGmiPZxsIbkCxw44mgHoQGR4MTQZucF1jEGhy8XimrTxj3+AaC6XHRlIozGAzVRBBILDeAvS+caIOAAyQVpiDTP/p8BIWURfOa4Lp2LLmcmMEsASXenYYLOMsaTe7D/SND6E64pk1uSGdyCKVSf6Wzzmv0CqIY+OkkQjIvDraCWG6ywunG0vZ8z/ZRak19pElI83iofiYr+xXttFwcI3bNzY+C/mpf9gB390VLbJ8p8OBZyPiifw4ZKgBehr7CzdwaUJvTWc4sle1B9TE2OLFzAmMDIDJn6xgm3d8Q9fjVMio2xBOO+D9zIDwPouYvi9o/X185CqF3//TuJSw5anguxSiV8I1prI84rzzjJNTBXxoIcfGqSlKrfLeEfspnSYjobDnATr9Tou61YChfo7yndx5AxIjdCrsBMgikNqHM5wai/DkhMSt0jda85JGIVwVu3RI52oIyXiIE58EJisk/DNHeXHedhHaqVI9QvT0q3sCqLLHvXO5Ku3JKJ4Suc95Ydcy0zC0/jqq3ZeiTnUziNo9deIl0fZ1BDGMBv08xtKoUw7wRZodFhsuJSleTBedWb8Z7i24QsfvbVUKsmPUUShLUJF7a/9KbLz9M/vgizUoIf0Eo+aBCUw9d8yk+1B/zfu8G6DQiRDDJmWwNdJHIS7NZioYOufI0ltsU73H3wKY7bvpMMX8vuBor02sXaVd+ViKVMjsT0xFQLHOqBzfRo+pZOnh55PY7wJK+lUiy6NZ4CbgCSOokGhDHowthdUE/iHbJjYINxSgFVy+1JPZKL0m5sDY8lhN2epRAtiPlk2mzMxkQji0BUEmc5xPjGyksl+53WCuRf2S5uGue25hRZiT7CyerL0p4M7780GFgnQqz X-MS-Exchange-AntiSpam-ExternalHop-MessageData-ChunkCount: 1 X-MS-Exchange-AntiSpam-ExternalHop-MessageData-0: SIYbC/sNFv/lFiGlXla5Jc0fwftNC2Ph6NB3z3oF2dKg6aESDBhduxcetpsLZM34qnj2JEtDjM8oESRlAsTbiVxWQ9QXXGXU3FWYoR1u+Fj56m5QdIYKIEf0HP817rVo4WR+Go887LMh0gm7/WbIVKWq/XSEaAc7KeXrSCO1Nq5Dn9N8JYpft1Lcvney9gGNw/nCe58E3aE8JiOXvq0fDQqT5ASjUIoqaXxBzugogjkl/gmoARYxSLjtfbjGLyoF19GHwMYA77D2a4gBmQhYHK7mc52wnS1VYZ3cMmJzlw0kLc8xGpDS0D6bsZx7jfLcg2AwXCpKKHuVQV81KOegG4jIEXAEzAZWe5BUgW610E90yJtgCGMXquA9gKE471cugu2IskhSsSJjAoXEjHhTAb5A0IfNL01iOzn6N8ylPtfQZfKZa6HF4U8WrJUDeEFmBwMF1I0SMQBCuOoisDQuZaQCT+4U/dESUwiueYsqks0RiRvfQxLfDWsk1Z4laE35gaupbBEyrYOUoWZn6mDRMzVSMyUYOs76TUbvvQOUFm1I94FZWZx7FvyX0amZgfwimlaWsszL4x2tTtSOz/IS3Yqv7GBykApko5ubG0Cc7JplJ0akdIm17VR/CcJwrsnJ27JmQkw98/79Z2ykpv3rKJPeORrXT6NBHLpTnw17YuH9gmXptJyBuBIIcrvgAmUnUF3N6J3SKlzg0a01ruk1RepOniS9d5HryG3en4XOlZIL6U1KF7DsNPgoqwySOutyVx7ZcgpHDsoBoDBzVUBd0Q+vWpyw5vw7aU7pFXgp4v7OVq4SNCHbg1hNOgESIuuDDss3+olVy6bQHeSq+JJpHpFTCzsw9Uqv6B2CVu876RmUYV23FhhJlIAAcNLe+xxNXwawVrImBYeyt0U7Amrmd+fU5vYTxN59z32DoWTVzsqlZco0OZr/sZ4/ST+yJWl9 X-OriginatorOrg: oracle.com X-MS-Exchange-CrossTenant-Network-Message-Id: 2bb6781b-7324-4081-a501-08db5d3b2eee X-MS-Exchange-CrossTenant-AuthSource: CH2PR10MB4344.namprd10.prod.outlook.com X-MS-Exchange-CrossTenant-AuthAs: Internal X-MS-Exchange-CrossTenant-OriginalArrivalTime: 25 May 2023 16:14:57.6592 (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: 7S0ZLrr+cVJX8csOWzFZ5mS1f+dSAl9S9otTHC6j6XkiuPDWi8/MofR8g0kqINkaCV3Gs05+W0YsfvvCYlaROA== X-MS-Exchange-Transport-CrossTenantHeadersStamped: BLAPR10MB5041 X-Proofpoint-Virus-Version: vendor=baseguard engine=ICAP:2.0.254,Aquarius:18.0.957,Hydra:6.0.573,FMLib:17.11.176.26 definitions=2023-05-25_09,2023-05-25_03,2023-05-22_02 X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 phishscore=0 malwarescore=0 bulkscore=0 mlxlogscore=999 mlxscore=0 adultscore=0 spamscore=0 suspectscore=0 classifier=spam adjust=0 reason=mlx scancount=1 engine=8.12.0-2304280000 definitions=main-2305250134 X-Proofpoint-GUID: Wt2rTDt1wG88K7gOfsEnAWL3i1gpSa39 X-Proofpoint-ORIG-GUID: Wt2rTDt1wG88K7gOfsEnAWL3i1gpSa39 X-Spam-Status: No, score=-5.4 required=5.0 tests=BAYES_00, DKIM_SIGNED, DKIM_VALID, DKIM_VALID_AU, DKIM_VALID_EF, KAM_SHORT, RCVD_IN_DNSWL_LOW, RCVD_IN_MSPIKE_H5, RCVD_IN_MSPIKE_WL, SPF_HELO_NONE, SPF_NONE, TXREP, T_SCC_BODY_TEXT_LINE 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 <gcc-patches.gcc.gnu.org> List-Unsubscribe: <https://gcc.gnu.org/mailman/options/gcc-patches>, <mailto:gcc-patches-request@gcc.gnu.org?subject=unsubscribe> List-Archive: <https://gcc.gnu.org/pipermail/gcc-patches/> List-Post: <mailto:gcc-patches@gcc.gnu.org> List-Help: <mailto:gcc-patches-request@gcc.gnu.org?subject=help> List-Subscribe: <https://gcc.gnu.org/mailman/listinfo/gcc-patches>, <mailto:gcc-patches-request@gcc.gnu.org?subject=subscribe> From: Qing Zhao via Gcc-patches <gcc-patches@gcc.gnu.org> Reply-To: Qing Zhao <qing.zhao@oracle.com> Errors-To: gcc-patches-bounces+ouuuleilei=gmail.com@gcc.gnu.org Sender: "Gcc-patches" <gcc-patches-bounces+ouuuleilei=gmail.com@gcc.gnu.org> X-getmail-retrieved-from-mailbox: =?utf-8?q?INBOX?= X-GMAIL-THRID: =?utf-8?q?1766883489233223945?= X-GMAIL-MSGID: =?utf-8?q?1766883489233223945?= |
Series |
New attribute "element_count" to annotate bounds for C99 FAM(PR108896)
|
|
Message
Qing Zhao
May 25, 2023, 4:14 p.m. UTC
Hi, This patch set introduces a new attribute "element_count" to annotate bounds for C99 flexible array member. A gcc bugzilla PR108896 has been created to record this task: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=108896 A nice writeup "Bounded Flexible Arrays in C" https://people.kernel.org/kees/bounded-flexible-arrays-in-c. written by Kees Cook, from Kernel Self-Protection Project, provides a solid background and motivation of this new attribute: "With flexible arrays now a first-class citizen in Linux and the compilers, it becomes possible to extend their available diagnostics. What the compiler is missing is knowledge of how the length of a given flexible array is tracked. For well-described flexible array structs, this means associating the member holding the element count with the flexible array member. This idea is not new, though prior implementation (https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2660.pdf) proposals have wanted to make changes to the C language syntax. A simpler approach is the addition of struct member attributes, and is under discussion and early development by both the GCC and Clang developer communities." The basic idea is to annotate the flexible array member with a new attribute "element_count" to track its number of elements to another field in the same structure, for example: struct object { .. size_t count; /* carries the number of elements info for the FAM flex. */ int flex[]; }; will become: struct object { .. size_t count: /* carries the number of elements info for the FAM flex. */ int flex[] __attribute__((element_count ("count"))); }; GCC will pass the number of elements info from the attached attribute to both __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds or dynamic object size issues during runtime for flexible array members. This new feature will provide nice protection to flexible array members (which currently are completely ignored by both __builtin_dynamic_object_size and bounds sanitizers). Possible future additions to this initial work include supporting counts from a variable outside the structure, or a field in the outer structure if needed. If the GCC extension works well, this feature might be promoted into new C standard in the future. Clang has a similar initial implemenation which is under review: https://reviews.llvm.org/D148381 Linux kernel also has a patch to use this new feature: https://lore.kernel.org/lkml/20230504211827.GA1666363@dev-arch.thelio-3990X/T/ The patch set include 3 patches: 1/3: Provide element_count attribute to flexible array member field (PR108896) 2/3: Use the element_count atribute info in builtin object size [PR108896]. 3/3: Use the element_count attribute information in bound sanitizer[PR108896] bootstrapped and regression tested on aarch64 and x86. Let me know if you have any comment or suggestion. Thanks. Qing
Comments
On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: > This patch set introduces a new attribute "element_count" to annotate bounds > for C99 flexible array member. Thank you for this work! I'm really excited to start using it in the Linux kernel. I'll give this a spin, but I know you've already been testing this series against the test cases I created earlier, so I don't expect any problems. :) One bike-shedding note: with the recent "-fbounds-safety" RFC posted for LLVM, we may want to consider renaming "element_count" to "counted_by": https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/ Thanks again! -Kees
On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: > GCC will pass the number of elements info from the attached attribute to both > __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds > or dynamic object size issues during runtime for flexible array members. > > This new feature will provide nice protection to flexible array members (which > currently are completely ignored by both __builtin_dynamic_object_size and > bounds sanitizers). Testing went pretty well, though I think I found some bdos issues: - some things that bdos can't know the size of, and correctly returned SIZE_MAX in the past, now thinks are 0-sized. - while bdos correctly knows the size of an element_count-annotated flexible array, it doesn't know the size of the containing object (i.e. it returns SIZE_MAX). Also, I think I found a precedence issue: - if both __alloc_size and 'element_count' are in use, the _smallest_ of the two is what I would expect to be enforced by the sanitizer and reported by __bdos. As is, alloc_size appears to be used when it is available, regardless of what 'element_count' shows. I've updated my test cases to show it more clearly, but here is the before/after: GCC 13 (correctly does not implement "element_count"): $ ./array-bounds 2>&1 | grep -v ^'#' TAP version 13 1..12 ok 1 global.fixed_size_seen_by_bdos ok 2 global.fixed_size_enforced_by_sanitizer ok 3 global.unknown_size_unknown_to_bdos ok 4 global.unknown_size_ignored_by_sanitizer ok 5 global.alloc_size_seen_by_bdos ok 6 global.alloc_size_enforced_by_sanitizer not ok 7 global.element_count_seen_by_bdos not ok 8 global.element_count_enforced_by_sanitizer not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer ToT GCC + this element_count series: $ ./array-bounds 2>&1 | grep -v ^'#' TAP version 13 1..12 ok 1 global.fixed_size_seen_by_bdos ok 2 global.fixed_size_enforced_by_sanitizer not ok 3 global.unknown_size_unknown_to_bdos not ok 4 global.unknown_size_ignored_by_sanitizer ok 5 global.alloc_size_seen_by_bdos ok 6 global.alloc_size_enforced_by_sanitizer not ok 7 global.element_count_seen_by_bdos ok 8 global.element_count_enforced_by_sanitizer not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer Test suite is here: https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c
> On May 26, 2023, at 4:40 PM, Kees Cook <keescook@chromium.org> wrote: > > On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: >> GCC will pass the number of elements info from the attached attribute to both >> __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds >> or dynamic object size issues during runtime for flexible array members. >> >> This new feature will provide nice protection to flexible array members (which >> currently are completely ignored by both __builtin_dynamic_object_size and >> bounds sanitizers). > > Testing went pretty well, though I think I found some bdos issues: > > - some things that bdos can't know the size of, and correctly returned > SIZE_MAX in the past, now thinks are 0-sized. Will check this issue and fix it. > - while bdos correctly knows the size of an element_count-annotated > flexible array, it doesn't know the size of the containing object > (i.e. it returns SIZE_MAX). This is a known issue I found during the implementation, and filed a bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557 for it And turned out that this was expected behavior. > > Also, I think I found a precedence issue: > > - if both __alloc_size and 'element_count' are in use, the _smallest_ > of the two is what I would expect to be enforced by the sanitizer > and reported by __bdos. As is, alloc_size appears to be used when > it is available, regardless of what 'element_count' shows. Will check on this and fix it. > > I've updated my test cases to show it more clearly, but here is the > before/after: > > > GCC 13 (correctly does not implement "element_count"): > > $ ./array-bounds 2>&1 | grep -v ^'#' > TAP version 13 > 1..12 > ok 1 global.fixed_size_seen_by_bdos > ok 2 global.fixed_size_enforced_by_sanitizer > ok 3 global.unknown_size_unknown_to_bdos > ok 4 global.unknown_size_ignored_by_sanitizer > ok 5 global.alloc_size_seen_by_bdos > ok 6 global.alloc_size_enforced_by_sanitizer > not ok 7 global.element_count_seen_by_bdos > not ok 8 global.element_count_enforced_by_sanitizer > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > > ToT GCC + this element_count series: > > $ ./array-bounds 2>&1 | grep -v ^'#' > TAP version 13 > 1..12 > ok 1 global.fixed_size_seen_by_bdos > ok 2 global.fixed_size_enforced_by_sanitizer > not ok 3 global.unknown_size_unknown_to_bdos > not ok 4 global.unknown_size_ignored_by_sanitizer > ok 5 global.alloc_size_seen_by_bdos > ok 6 global.alloc_size_enforced_by_sanitizer > not ok 7 global.element_count_seen_by_bdos > ok 8 global.element_count_enforced_by_sanitizer > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > > Test suite is here: > https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c Thanks a lot for the testing, this is really helpful. Will study and fix all these issues. Qing > > -- > Kees Cook
> On May 26, 2023, at 12:12 PM, Kees Cook <keescook@chromium.org> wrote: > > On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: >> This patch set introduces a new attribute "element_count" to annotate bounds >> for C99 flexible array member. > > Thank you for this work! I'm really excited to start using it in the > Linux kernel. I'll give this a spin, but I know you've already been > testing this series against the test cases I created earlier, so I don't > expect any problems. :) > > One bike-shedding note: with the recent "-fbounds-safety" RFC posted for > LLVM, we may want to consider renaming "element_count" to "counted_by": > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/ Yeah, we can do that. thanks. Qing > > Thanks again! > > -Kees > > -- > Kees Cook
Hi, Kees, I have updated my V1 patch with the following changes: A. changed the name to "counted_by" B. changed the argument from a string to an identifier C. updated the documentation and testing cases accordingly. And then used this new gcc to test https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c (with the following change) [opc@qinzhao-ol8u3-x86 Kees]$ !1091 diff array-bounds.c array-bounds.c.org 32c32 < # define __counted_by(member) __attribute__((counted_by (member))) --- > # define __counted_by(member) __attribute__((__element_count__(#member))) 34c34 < # define __counted_by(member) __attribute__((counted_by (member))) --- > # define __counted_by(member) /* __attribute__((__element_count__(#member))) */ Then I got the following result: [opc@qinzhao-ol8u3-x86 Kees]$ ./array-bounds 2>&1 | grep -v ^'#' TAP version 13 1..12 ok 1 global.fixed_size_seen_by_bdos ok 2 global.fixed_size_enforced_by_sanitizer not ok 3 global.unknown_size_unknown_to_bdos not ok 4 global.unknown_size_ignored_by_sanitizer ok 5 global.alloc_size_seen_by_bdos ok 6 global.alloc_size_enforced_by_sanitizer not ok 7 global.element_count_seen_by_bdos ok 8 global.element_count_enforced_by_sanitizer not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer The same as your previous results. Then I took a look at all the failed testing: 3, 4, 7, 9, and 10. And studied the reasons for all of them. in a summary, there are two major issues: 1. The reason for the failed testing 7 is the same issue as I observed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557 Which is not a bug, it’s an expected behavior. 2. The common issue for the failed testing 3, 4, 9, 10 is: for the following annotated structure: ==== struct annotated { unsigned long flags; size_t foo; int array[] __attribute__((counted_by (foo))); }; struct annotated *p; int index = 16; p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 or p->foo was not set to any value as in test 3 and 4 ==== i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. I think that this should be considered as an user error, and the documentation of the attribute should include this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) We can add a new warning option -Wcounted-by to report such user error if needed. What’s your opinion on this? thanks. Qing > On May 26, 2023, at 4:40 PM, Kees Cook <keescook@chromium.org> wrote: > > On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: >> GCC will pass the number of elements info from the attached attribute to both >> __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds >> or dynamic object size issues during runtime for flexible array members. >> >> This new feature will provide nice protection to flexible array members (which >> currently are completely ignored by both __builtin_dynamic_object_size and >> bounds sanitizers). > > Testing went pretty well, though I think I found some bdos issues: > > - some things that bdos can't know the size of, and correctly returned > SIZE_MAX in the past, now thinks are 0-sized. > - while bdos correctly knows the size of an element_count-annotated > flexible array, it doesn't know the size of the containing object > (i.e. it returns SIZE_MAX). > > Also, I think I found a precedence issue: > > - if both __alloc_size and 'element_count' are in use, the _smallest_ > of the two is what I would expect to be enforced by the sanitizer > and reported by __bdos. As is, alloc_size appears to be used when > it is available, regardless of what 'element_count' shows. > > I've updated my test cases to show it more clearly, but here is the > before/after: > > > GCC 13 (correctly does not implement "element_count"): > > $ ./array-bounds 2>&1 | grep -v ^'#' > TAP version 13 > 1..12 > ok 1 global.fixed_size_seen_by_bdos > ok 2 global.fixed_size_enforced_by_sanitizer > ok 3 global.unknown_size_unknown_to_bdos > ok 4 global.unknown_size_ignored_by_sanitizer > ok 5 global.alloc_size_seen_by_bdos > ok 6 global.alloc_size_enforced_by_sanitizer > not ok 7 global.element_count_seen_by_bdos > not ok 8 global.element_count_enforced_by_sanitizer > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > > ToT GCC + this element_count series: > > $ ./array-bounds 2>&1 | grep -v ^'#' > TAP version 13 > 1..12 > ok 1 global.fixed_size_seen_by_bdos > ok 2 global.fixed_size_enforced_by_sanitizer > not ok 3 global.unknown_size_unknown_to_bdos > not ok 4 global.unknown_size_ignored_by_sanitizer > ok 5 global.alloc_size_seen_by_bdos > ok 6 global.alloc_size_enforced_by_sanitizer > not ok 7 global.element_count_seen_by_bdos > ok 8 global.element_count_enforced_by_sanitizer > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > > Test suite is here: > https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c > > -- > Kees Cook
Am Donnerstag, dem 06.07.2023 um 18:56 +0000 schrieb Qing Zhao: > Hi, Kees, > > I have updated my V1 patch with the following changes: > A. changed the name to "counted_by" > B. changed the argument from a string to an identifier > C. updated the documentation and testing cases accordingly. > > And then used this new gcc to test https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c (with the following change) > [opc@qinzhao-ol8u3-x86 Kees]$ !1091 > diff array-bounds.c array-bounds.c.org > 32c32 > < # define __counted_by(member) __attribute__((counted_by (member))) > --- > > # define __counted_by(member) __attribute__((__element_count__(#member))) > 34c34 > < # define __counted_by(member) __attribute__((counted_by (member))) > --- > > # define __counted_by(member) /* __attribute__((__element_count__(#member))) */ > > Then I got the following result: > [opc@qinzhao-ol8u3-x86 Kees]$ ./array-bounds 2>&1 | grep -v ^'#' > TAP version 13 > 1..12 > ok 1 global.fixed_size_seen_by_bdos > ok 2 global.fixed_size_enforced_by_sanitizer > not ok 3 global.unknown_size_unknown_to_bdos > not ok 4 global.unknown_size_ignored_by_sanitizer > ok 5 global.alloc_size_seen_by_bdos > ok 6 global.alloc_size_enforced_by_sanitizer > not ok 7 global.element_count_seen_by_bdos > ok 8 global.element_count_enforced_by_sanitizer > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > The same as your previous results. Then I took a look at all the failed testing: 3, 4, 7, 9, and 10. And studied the reasons for all of them. > > in a summary, there are two major issues: > 1. The reason for the failed testing 7 is the same issue as I observed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557 > Which is not a bug, it’s an expected behavior. > > 2. The common issue for the failed testing 3, 4, 9, 10 is: > > for the following annotated structure: > > ==== > struct annotated { > unsigned long flags; > size_t foo; > int array[] __attribute__((counted_by (foo))); > }; > > > struct annotated *p; > int index = 16; > > p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size > > p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 > or > p->foo was not set to any value as in test 3 and 4 > > ==== > > i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. > > I think that this should be considered as an user error, and the documentation of the attribute should include > this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) > > We can add a new warning option -Wcounted-by to report such user error if needed. > > What’s your opinion on this? Additionally, we could also have a sanitizer that checks this at run-time. Personally, I am still not very happy that in the following example the two 'n's refer to different entities: void f(int n) { struct foo { int n; int (*p[])[n] [[counted_by(n)]]; }; } But I guess it will be difficult to convince everybody that it would be wise to use a new syntax for disambiguation: void f(int n) { struct foo { int n; int (*p[])[n] [[counted_by(.n)]]; }; } Martin > > thanks. > > Qing > > > > On May 26, 2023, at 4:40 PM, Kees Cook <keescook@chromium.org> wrote: > > > > On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: > > > GCC will pass the number of elements info from the attached attribute to both > > > __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds > > > or dynamic object size issues during runtime for flexible array members. > > > > > > This new feature will provide nice protection to flexible array members (which > > > currently are completely ignored by both __builtin_dynamic_object_size and > > > bounds sanitizers). > > > > Testing went pretty well, though I think I found some bdos issues: > > > > - some things that bdos can't know the size of, and correctly returned > > SIZE_MAX in the past, now thinks are 0-sized. > > - while bdos correctly knows the size of an element_count-annotated > > flexible array, it doesn't know the size of the containing object > > (i.e. it returns SIZE_MAX). > > > > Also, I think I found a precedence issue: > > > > - if both __alloc_size and 'element_count' are in use, the _smallest_ > > of the two is what I would expect to be enforced by the sanitizer > > and reported by __bdos. As is, alloc_size appears to be used when > > it is available, regardless of what 'element_count' shows. > > > > I've updated my test cases to show it more clearly, but here is the > > before/after: > > > > > > GCC 13 (correctly does not implement "element_count"): > > > > $ ./array-bounds 2>&1 | grep -v ^'#' > > TAP version 13 > > 1..12 > > ok 1 global.fixed_size_seen_by_bdos > > ok 2 global.fixed_size_enforced_by_sanitizer > > ok 3 global.unknown_size_unknown_to_bdos > > ok 4 global.unknown_size_ignored_by_sanitizer > > ok 5 global.alloc_size_seen_by_bdos > > ok 6 global.alloc_size_enforced_by_sanitizer > > not ok 7 global.element_count_seen_by_bdos > > not ok 8 global.element_count_enforced_by_sanitizer > > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > > > > > ToT GCC + this element_count series: > > > > $ ./array-bounds 2>&1 | grep -v ^'#' > > TAP version 13 > > 1..12 > > ok 1 global.fixed_size_seen_by_bdos > > ok 2 global.fixed_size_enforced_by_sanitizer > > not ok 3 global.unknown_size_unknown_to_bdos > > not ok 4 global.unknown_size_ignored_by_sanitizer > > ok 5 global.alloc_size_seen_by_bdos > > ok 6 global.alloc_size_enforced_by_sanitizer > > not ok 7 global.element_count_seen_by_bdos > > ok 8 global.element_count_enforced_by_sanitizer > > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > > > > > Test suite is here: > > https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c > > > > -- > > Kees Cook >
> On Jul 6, 2023, at 5:10 PM, Martin Uecker <uecker@tugraz.at> wrote: > > Am Donnerstag, dem 06.07.2023 um 18:56 +0000 schrieb Qing Zhao: >> Hi, Kees, >> >> I have updated my V1 patch with the following changes: >> A. changed the name to "counted_by" >> B. changed the argument from a string to an identifier >> C. updated the documentation and testing cases accordingly. >> >> And then used this new gcc to test https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c (with the following change) >> [opc@qinzhao-ol8u3-x86 Kees]$ !1091 >> diff array-bounds.c array-bounds.c.org >> 32c32 >> < # define __counted_by(member) __attribute__((counted_by (member))) >> --- >>> # define __counted_by(member) __attribute__((__element_count__(#member))) >> 34c34 >> < # define __counted_by(member) __attribute__((counted_by (member))) >> --- >>> # define __counted_by(member) /* __attribute__((__element_count__(#member))) */ >> >> Then I got the following result: >> [opc@qinzhao-ol8u3-x86 Kees]$ ./array-bounds 2>&1 | grep -v ^'#' >> TAP version 13 >> 1..12 >> ok 1 global.fixed_size_seen_by_bdos >> ok 2 global.fixed_size_enforced_by_sanitizer >> not ok 3 global.unknown_size_unknown_to_bdos >> not ok 4 global.unknown_size_ignored_by_sanitizer >> ok 5 global.alloc_size_seen_by_bdos >> ok 6 global.alloc_size_enforced_by_sanitizer >> not ok 7 global.element_count_seen_by_bdos >> ok 8 global.element_count_enforced_by_sanitizer >> not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos >> not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer >> ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos >> ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer >> >> The same as your previous results. Then I took a look at all the failed testing: 3, 4, 7, 9, and 10. And studied the reasons for all of them. >> >> in a summary, there are two major issues: >> 1. The reason for the failed testing 7 is the same issue as I observed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557 >> Which is not a bug, it’s an expected behavior. >> >> 2. The common issue for the failed testing 3, 4, 9, 10 is: >> >> for the following annotated structure: >> >> ==== >> struct annotated { >> unsigned long flags; >> size_t foo; >> int array[] __attribute__((counted_by (foo))); >> }; >> >> >> struct annotated *p; >> int index = 16; >> >> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size >> >> p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 >> or >> p->foo was not set to any value as in test 3 and 4 >> >> ==== >> >> i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. >> >> I think that this should be considered as an user error, and the documentation of the attribute should include >> this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: >> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) >> >> We can add a new warning option -Wcounted-by to report such user error if needed. >> >> What’s your opinion on this? > > > Additionally, we could also have a sanitizer that > checks this at run-time. Yes, that’s also a nice feature to have. I think that the main point here is to catch such user errors during compilation time or run time. I will add one or two separate patches for these compilation warning and sanitizer feature. > > Personally, I am still not very happy that in the > following example the two 'n's refer to different > entities: > > void f(int n) > { > struct foo { > int n; > int (*p[])[n] [[counted_by(n)]]; > }; > } > Me either )-: > But I guess it will be difficult to convince everybody > that it would be wise to use a new syntax for > disambiguation: > > void f(int n) > { > struct foo { > int n; > int (*p[])[n] [[counted_by(.n)]]; > }; > } > I guess that it’s quite hard to convince everyone that the new syntax is the best solution at this moment. And it might not worth the effort at this time. We can do the new syntax later if necessary. thanks. Qing > Martin > > >> >> thanks. >> >> Qing >> >> >>> On May 26, 2023, at 4:40 PM, Kees Cook <keescook@chromium.org> wrote: >>> >>> On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: >>>> GCC will pass the number of elements info from the attached attribute to both >>>> __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds >>>> or dynamic object size issues during runtime for flexible array members. >>>> >>>> This new feature will provide nice protection to flexible array members (which >>>> currently are completely ignored by both __builtin_dynamic_object_size and >>>> bounds sanitizers). >>> >>> Testing went pretty well, though I think I found some bdos issues: >>> >>> - some things that bdos can't know the size of, and correctly returned >>> SIZE_MAX in the past, now thinks are 0-sized. >>> - while bdos correctly knows the size of an element_count-annotated >>> flexible array, it doesn't know the size of the containing object >>> (i.e. it returns SIZE_MAX). >>> >>> Also, I think I found a precedence issue: >>> >>> - if both __alloc_size and 'element_count' are in use, the _smallest_ >>> of the two is what I would expect to be enforced by the sanitizer >>> and reported by __bdos. As is, alloc_size appears to be used when >>> it is available, regardless of what 'element_count' shows. >>> >>> I've updated my test cases to show it more clearly, but here is the >>> before/after: >>> >>> >>> GCC 13 (correctly does not implement "element_count"): >>> >>> $ ./array-bounds 2>&1 | grep -v ^'#' >>> TAP version 13 >>> 1..12 >>> ok 1 global.fixed_size_seen_by_bdos >>> ok 2 global.fixed_size_enforced_by_sanitizer >>> ok 3 global.unknown_size_unknown_to_bdos >>> ok 4 global.unknown_size_ignored_by_sanitizer >>> ok 5 global.alloc_size_seen_by_bdos >>> ok 6 global.alloc_size_enforced_by_sanitizer >>> not ok 7 global.element_count_seen_by_bdos >>> not ok 8 global.element_count_enforced_by_sanitizer >>> not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos >>> not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer >>> ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos >>> ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer >>> >>> >>> ToT GCC + this element_count series: >>> >>> $ ./array-bounds 2>&1 | grep -v ^'#' >>> TAP version 13 >>> 1..12 >>> ok 1 global.fixed_size_seen_by_bdos >>> ok 2 global.fixed_size_enforced_by_sanitizer >>> not ok 3 global.unknown_size_unknown_to_bdos >>> not ok 4 global.unknown_size_ignored_by_sanitizer >>> ok 5 global.alloc_size_seen_by_bdos >>> ok 6 global.alloc_size_enforced_by_sanitizer >>> not ok 7 global.element_count_seen_by_bdos >>> ok 8 global.element_count_enforced_by_sanitizer >>> not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos >>> not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer >>> ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos >>> ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer >>> >>> >>> Test suite is here: >>> https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c >>> >>> -- >>> Kees Cook >> > >
The following is the updated documentation on this new attribute, please let me know any suggestion and comment: ====== '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 '__builtin_dynamic_object_size' and array bound sanitizer. For instance, the following declaration: 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 '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 '__builtin_dynamic_object_size' and array bound sanitizer might be incorrect. For instance, the following 2nd update to the field 'count' of the above structure will permit out-of-bounds access to the array 'sbuf>array': struct P *sbuf; void alloc_buf (size_t nelems) { sbuf = (int *) malloc (sizeof (struct P) + sizeof (int) * nelems); sbuf->count = nelems; } void use_buf (int index) { sbuf->count++; /* Now the value of sbuf->count and the number of elements of sbuf->array is out of sync. */ sbuf->array[index] = 0; /* then the out-of-bound access to this array might not be detected. */ } The users can use the warning option '-Wcounted-by-attribute' to detect such user errors during compilation time, or the sanitizer option '-fsanitize=counted-by-attribute' to detect such user errors during runtime. ===== Qing > On Jul 7, 2023, at 11:47 AM, Qing Zhao via Gcc-patches <gcc-patches@gcc.gnu.org> wrote: > > > >> On Jul 6, 2023, at 5:10 PM, Martin Uecker <uecker@tugraz.at> wrote: >> >> Am Donnerstag, dem 06.07.2023 um 18:56 +0000 schrieb Qing Zhao: >>> Hi, Kees, >>> >>> I have updated my V1 patch with the following changes: >>> A. changed the name to "counted_by" >>> B. changed the argument from a string to an identifier >>> C. updated the documentation and testing cases accordingly. >>> >>> And then used this new gcc to test https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c (with the following change) >>> [opc@qinzhao-ol8u3-x86 Kees]$ !1091 >>> diff array-bounds.c array-bounds.c.org >>> 32c32 >>> < # define __counted_by(member) __attribute__((counted_by (member))) >>> --- >>>> # define __counted_by(member) __attribute__((__element_count__(#member))) >>> 34c34 >>> < # define __counted_by(member) __attribute__((counted_by (member))) >>> --- >>>> # define __counted_by(member) /* __attribute__((__element_count__(#member))) */ >>> >>> Then I got the following result: >>> [opc@qinzhao-ol8u3-x86 Kees]$ ./array-bounds 2>&1 | grep -v ^'#' >>> TAP version 13 >>> 1..12 >>> ok 1 global.fixed_size_seen_by_bdos >>> ok 2 global.fixed_size_enforced_by_sanitizer >>> not ok 3 global.unknown_size_unknown_to_bdos >>> not ok 4 global.unknown_size_ignored_by_sanitizer >>> ok 5 global.alloc_size_seen_by_bdos >>> ok 6 global.alloc_size_enforced_by_sanitizer >>> not ok 7 global.element_count_seen_by_bdos >>> ok 8 global.element_count_enforced_by_sanitizer >>> not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos >>> not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer >>> ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos >>> ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer >>> >>> The same as your previous results. Then I took a look at all the failed testing: 3, 4, 7, 9, and 10. And studied the reasons for all of them. >>> >>> in a summary, there are two major issues: >>> 1. The reason for the failed testing 7 is the same issue as I observed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557 >>> Which is not a bug, it’s an expected behavior. >>> >>> 2. The common issue for the failed testing 3, 4, 9, 10 is: >>> >>> for the following annotated structure: >>> >>> ==== >>> struct annotated { >>> unsigned long flags; >>> size_t foo; >>> int array[] __attribute__((counted_by (foo))); >>> }; >>> >>> >>> struct annotated *p; >>> int index = 16; >>> >>> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size >>> >>> p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 >>> or >>> p->foo was not set to any value as in test 3 and 4 >>> >>> ==== >>> >>> i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. >>> >>> I think that this should be considered as an user error, and the documentation of the attribute should include >>> this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: >>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) >>> >>> We can add a new warning option -Wcounted-by to report such user error if needed. >>> >>> What’s your opinion on this? >> >> >> Additionally, we could also have a sanitizer that >> checks this at run-time. > > Yes, that’s also a nice feature to have. > I think that the main point here is to catch such user errors during compilation time or run time. > > I will add one or two separate patches for these compilation warning and sanitizer feature. > > >> >> Personally, I am still not very happy that in the >> following example the two 'n's refer to different >> entities: >> >> void f(int n) >> { >> struct foo { >> int n; >> int (*p[])[n] [[counted_by(n)]]; >> }; >> } >> > Me either )-: > > >> But I guess it will be difficult to convince everybody >> that it would be wise to use a new syntax for >> disambiguation: >> >> void f(int n) >> { >> struct foo { >> int n; >> int (*p[])[n] [[counted_by(.n)]]; >> }; >> } >> > > I guess that it’s quite hard to convince everyone that the new syntax is the best solution at this moment. > And it might not worth the effort at this time. > > We can do the new syntax later if necessary. > > thanks. > > Qing > >> Martin >> >> >>> >>> thanks. >>> >>> Qing >>> >>> >>>> On May 26, 2023, at 4:40 PM, Kees Cook <keescook@chromium.org> wrote: >>>> >>>> On Thu, May 25, 2023 at 04:14:47PM +0000, Qing Zhao wrote: >>>>> GCC will pass the number of elements info from the attached attribute to both >>>>> __builtin_dynamic_object_size and bounds sanitizer to check the out-of-bounds >>>>> or dynamic object size issues during runtime for flexible array members. >>>>> >>>>> This new feature will provide nice protection to flexible array members (which >>>>> currently are completely ignored by both __builtin_dynamic_object_size and >>>>> bounds sanitizers). >>>> >>>> Testing went pretty well, though I think I found some bdos issues: >>>> >>>> - some things that bdos can't know the size of, and correctly returned >>>> SIZE_MAX in the past, now thinks are 0-sized. >>>> - while bdos correctly knows the size of an element_count-annotated >>>> flexible array, it doesn't know the size of the containing object >>>> (i.e. it returns SIZE_MAX). >>>> >>>> Also, I think I found a precedence issue: >>>> >>>> - if both __alloc_size and 'element_count' are in use, the _smallest_ >>>> of the two is what I would expect to be enforced by the sanitizer >>>> and reported by __bdos. As is, alloc_size appears to be used when >>>> it is available, regardless of what 'element_count' shows. >>>> >>>> I've updated my test cases to show it more clearly, but here is the >>>> before/after: >>>> >>>> >>>> GCC 13 (correctly does not implement "element_count"): >>>> >>>> $ ./array-bounds 2>&1 | grep -v ^'#' >>>> TAP version 13 >>>> 1..12 >>>> ok 1 global.fixed_size_seen_by_bdos >>>> ok 2 global.fixed_size_enforced_by_sanitizer >>>> ok 3 global.unknown_size_unknown_to_bdos >>>> ok 4 global.unknown_size_ignored_by_sanitizer >>>> ok 5 global.alloc_size_seen_by_bdos >>>> ok 6 global.alloc_size_enforced_by_sanitizer >>>> not ok 7 global.element_count_seen_by_bdos >>>> not ok 8 global.element_count_enforced_by_sanitizer >>>> not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos >>>> not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer >>>> ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos >>>> ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer >>>> >>>> >>>> ToT GCC + this element_count series: >>>> >>>> $ ./array-bounds 2>&1 | grep -v ^'#' >>>> TAP version 13 >>>> 1..12 >>>> ok 1 global.fixed_size_seen_by_bdos >>>> ok 2 global.fixed_size_enforced_by_sanitizer >>>> not ok 3 global.unknown_size_unknown_to_bdos >>>> not ok 4 global.unknown_size_ignored_by_sanitizer >>>> ok 5 global.alloc_size_seen_by_bdos >>>> ok 6 global.alloc_size_enforced_by_sanitizer >>>> not ok 7 global.element_count_seen_by_bdos >>>> ok 8 global.element_count_enforced_by_sanitizer >>>> not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos >>>> not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer >>>> ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos >>>> ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer >>>> >>>> >>>> Test suite is here: >>>> https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c >>>> >>>> -- >>>> Kees Cook
On Thu, Jul 06, 2023 at 06:56:21PM +0000, Qing Zhao wrote: > Hi, Kees, > > I have updated my V1 patch with the following changes: > A. changed the name to "counted_by" > B. changed the argument from a string to an identifier > C. updated the documentation and testing cases accordingly. Sounds great! > > And then used this new gcc to test https://github.com/kees/kernel-tools/blob/trunk/fortify/array-bounds.c (with the following change) > [opc@qinzhao-ol8u3-x86 Kees]$ !1091 > diff array-bounds.c array-bounds.c.org > 32c32 > < # define __counted_by(member) __attribute__((counted_by (member))) > --- > > # define __counted_by(member) __attribute__((__element_count__(#member))) > 34c34 > < # define __counted_by(member) __attribute__((counted_by (member))) > --- > > # define __counted_by(member) /* __attribute__((__element_count__(#member))) */ > > Then I got the following result: > [opc@qinzhao-ol8u3-x86 Kees]$ ./array-bounds 2>&1 | grep -v ^'#' > TAP version 13 > 1..12 > ok 1 global.fixed_size_seen_by_bdos > ok 2 global.fixed_size_enforced_by_sanitizer > not ok 3 global.unknown_size_unknown_to_bdos > not ok 4 global.unknown_size_ignored_by_sanitizer > ok 5 global.alloc_size_seen_by_bdos > ok 6 global.alloc_size_enforced_by_sanitizer > not ok 7 global.element_count_seen_by_bdos > ok 8 global.element_count_enforced_by_sanitizer > not ok 9 global.alloc_size_with_smaller_element_count_seen_by_bdos > not ok 10 global.alloc_size_with_smaller_element_count_enforced_by_sanitizer > ok 11 global.alloc_size_with_bigger_element_count_seen_by_bdos > ok 12 global.alloc_size_with_bigger_element_count_enforced_by_sanitizer > > The same as your previous results. Then I took a look at all the failed testing: 3, 4, 7, 9, and 10. And studied the reasons for all of them. > > in a summary, there are two major issues: > 1. The reason for the failed testing 7 is the same issue as I observed in https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557 > Which is not a bug, it’s an expected behavior. In the bug, the problem is that "p" isn't known to be allocated, if I'm reading that correctly? I'm not sure this is a reasonable behavior, but let me get into the specific test, which looks like this: TEST(counted_by_seen_by_bdos) { struct annotated *p; int index = MAX_INDEX + unconst; p = alloc_annotated(index); REPORT_SIZE(p->array); /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); /* Check array size alone. */ /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), SIZE_MAX); /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(*p->array)); /* Check check entire object size. */ /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), sizeof(*p) + p->foo * sizeof(*p->array)); } Test 1 trivially passes -- this is just a sanity check. Test 2 should be SIZE_MAX because __bos only knows compile-time sizes. Test 3 should pass: counted_by knows the allocation size and can be queried as part of the "p" object. Test 4 should be SIZE_MAX because __bos only knows compile-time sizes. Test 5 should pass as well, since, again, p can be examined. Passing p to __bdos implies it is allocated and the __counted_by annotation can be examined. If "return p->array[index];" would be caught by the sanitizer, then it follows that __builtin_dynamic_object_size(p, 1) must also know the size. i.e. both must examine "p" and its trailing flexible array and __counted_by annotation. > > 2. The common issue for the failed testing 3, 4, 9, 10 is: > > for the following annotated structure: > > ==== > struct annotated { > unsigned long flags; > size_t foo; > int array[] __attribute__((counted_by (foo))); > }; > > > struct annotated *p; > int index = 16; > > p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size > > p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 Right, tests 9 and 10 are checking that the _smallest_ possible value of the array is used. (There are two sources of information: the allocation size and the size calculated by counted_by. The smaller of the two should be used when both are available.) > or > p->foo was not set to any value as in test 3 and 4 For tests 3 and 4, yes, this was my mistake. I have fixed up the tests now. Bill noticed the same issue. Sorry for the think-o! > ==== > > i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. > > I think that this should be considered as an user error, and the documentation of the attribute should include > this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) > > We can add a new warning option -Wcounted-by to report such user error if needed. > > What’s your opinion on this? I think it is correct to allow mismatch between allocation and counted_by as long as only the least of the two is used. This may be desirable in a few situations. One example would be a large allocation that is slowly filled up by the program. I.e. the counted_by member is slowly increased during runtime (but not beyond the true allocation size). Of course allocation size is only available in limited situations, so the loss of that info is fine: we have counted_by for everything else.
> On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> wrote: > > In the bug, the problem is that "p" isn't known to be allocated, if I'm > reading that correctly? I think that the major point in PR109557 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): for the following pointer p.3_1, p.3_1 = p; _2 = __builtin_object_size (p.3_1, 0); Question: why the size of p.3_1 cannot use the TYPE_SIZE of the pointee of p when the TYPE_SIZE can be determined at compile time? Answer: From just knowing the type of the pointee of p, the compiler cannot determine the size of the object. Therefore the bug has been closed. In your following testing 5: > I'm not sure this is a reasonable behavior, but > let me get into the specific test, which looks like this: > > TEST(counted_by_seen_by_bdos) > { > struct annotated *p; > int index = MAX_INDEX + unconst; > > p = alloc_annotated(index); > > REPORT_SIZE(p->array); > /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); > /* Check array size alone. */ > /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), SIZE_MAX); > /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(*p->array)); > /* Check check entire object size. */ > /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); > /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), sizeof(*p) + p->foo * sizeof(*p->array)); > } > > Test 5 should pass as well, since, again, p can be examined. Passing p > to __bdos implies it is allocated and the __counted_by annotation can be > examined. Since the call to the routine “alloc_annotated" cannot be inlined, GCC does not see any allocation calls for the pointer p. At the same time, due to the same reason as PR109986, GCC cannot determine the size of the object by just knowing the TYPE_SIZE of the pointee of p. So, this is exactly the same issue as PR109557. It’s an existing behavior per the current __buitlin_object_size algorithm. I am still not very sure whether the situation in PR109557 can be improved or not, but either way, it’s a separate issue. Please see the new testing case I added for PR109557, you will see that the above case 5 is a similar case as the new testing case in PR109557. > > If "return p->array[index];" would be caught by the sanitizer, then > it follows that __builtin_dynamic_object_size(p, 1) must also know the > size. i.e. both must examine "p" and its trailing flexible array and > __counted_by annotation. > >> >> 2. The common issue for the failed testing 3, 4, 9, 10 is: >> >> for the following annotated structure: >> >> ==== >> struct annotated { >> unsigned long flags; >> size_t foo; >> int array[] __attribute__((counted_by (foo))); >> }; >> >> >> struct annotated *p; >> int index = 16; >> >> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size >> >> p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 > > Right, tests 9 and 10 are checking that the _smallest_ possible value of > the array is used. (There are two sources of information: the allocation > size and the size calculated by counted_by. The smaller of the two > should be used when both are available.) The counted_by attribute is used to annotate a Flexible array member on how many elements it will have. However, if this information can not accurately reflect the real number of elements for the array allocated, What’s the purpose of such information? >> or >> p->foo was not set to any value as in test 3 and 4 > > For tests 3 and 4, yes, this was my mistake. I have fixed up the tests > now. Bill noticed the same issue. Sorry for the think-o! > >> ==== >> >> i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. >> >> I think that this should be considered as an user error, and the documentation of the attribute should include >> this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: >> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) >> >> We can add a new warning option -Wcounted-by to report such user error if needed. >> >> What’s your opinion on this? > > I think it is correct to allow mismatch between allocation and > counted_by as long as only the least of the two is used. What’s your mean by “only the least of the two is used”? > This may be > desirable in a few situations. One example would be a large allocation > that is slowly filled up by the program. So, for such situation, whenever the allocation is filled up, the field that hold the “counted_by” attribute should be increased at the same time, Then, the “counted_by” value always sync with the real allocation. > I.e. the counted_by member is > slowly increased during runtime (but not beyond the true allocation size). Then there should be source code to increase the “counted_by” field whenever the allocated space increased too. > > Of course allocation size is only available in limited situations, so > the loss of that info is fine: we have counted_by for everything else. The point is: allocation size should synced with the value of “counted_by”. LLVM’s RFC also have the similar requirement: https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 Qing > > -- > Kees Cook
On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: > > > On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> wrote: > > > > In the bug, the problem is that "p" isn't known to be allocated, if I'm > > reading that correctly? > > I think that the major point in PR109557 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): > > for the following pointer p.3_1, > > p.3_1 = p; > _2 = __builtin_object_size (p.3_1, 0); > > Question: why the size of p.3_1 cannot use the TYPE_SIZE of the pointee of p when the TYPE_SIZE can be determined at compile time? > > Answer: From just knowing the type of the pointee of p, the compiler cannot determine the size of the object. Why is that? "p" points to "struct P", which has a fixed size. There must be an assumption somewhere that a pointer is allocated, otherwise __bos would almost never work? > Therefore the bug has been closed. > > In your following testing 5: > > > I'm not sure this is a reasonable behavior, but > > let me get into the specific test, which looks like this: > > > > TEST(counted_by_seen_by_bdos) > > { > > struct annotated *p; > > int index = MAX_INDEX + unconst; > > > > p = alloc_annotated(index); > > > > REPORT_SIZE(p->array); > > /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); > > /* Check array size alone. */ > > /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), SIZE_MAX); > > /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(*p->array)); > > /* Check check entire object size. */ > > /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); > > /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), sizeof(*p) + p->foo * sizeof(*p->array)); > > } > > > > Test 5 should pass as well, since, again, p can be examined. Passing p > > to __bdos implies it is allocated and the __counted_by annotation can be > > examined. > > Since the call to the routine “alloc_annotated" cannot be inlined, GCC does not see any allocation calls for the pointer p. Correct. > At the same time, due to the same reason as PR109986, GCC cannot determine the size of the object by just knowing the TYPE_SIZE > of the pointee of p. So the difference between test 3 and test 5 is that "p" is explicitly dereferenced to find "array", and therefore an assumption is established that "p" is allocated? > So, this is exactly the same issue as PR109557. It’s an existing behavior per the current __buitlin_object_size algorithm. > I am still not very sure whether the situation in PR109557 can be improved or not, but either way, it’s a separate issue. Okay, so the issue is one of object allocation visibility (or assumptions there in)? > Please see the new testing case I added for PR109557, you will see that the above case 5 is a similar case as the new testing case in PR109557. I will ponder this a bit more to see if I can come up with a useful test case to replace the part from "test 5" above. > > > > If "return p->array[index];" would be caught by the sanitizer, then > > it follows that __builtin_dynamic_object_size(p, 1) must also know the > > size. i.e. both must examine "p" and its trailing flexible array and > > __counted_by annotation. > > > >> > >> 2. The common issue for the failed testing 3, 4, 9, 10 is: > >> > >> for the following annotated structure: > >> > >> ==== > >> struct annotated { > >> unsigned long flags; > >> size_t foo; > >> int array[] __attribute__((counted_by (foo))); > >> }; > >> > >> > >> struct annotated *p; > >> int index = 16; > >> > >> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size > >> > >> p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 > > > > Right, tests 9 and 10 are checking that the _smallest_ possible value of > > the array is used. (There are two sources of information: the allocation > > size and the size calculated by counted_by. The smaller of the two > > should be used when both are available.) > > The counted_by attribute is used to annotate a Flexible array member on how many elements it will have. > However, if this information can not accurately reflect the real number of elements for the array allocated, > What’s the purpose of such information? For example, imagine code that allocates space for 100 elements since the common case is that the number of elements will grow over time. Elements are added as it goes. For example: struct grows { int alloc_count; int valid_count; struct element item[] __counted_by(valid_count); } *p; void something(void) { p = malloc(sizeof(*p) + sizeof(*p->item) * 100); p->alloc_count = 100; p->valid_count = 0; /* this loop doesn't check that we don't go over 100. */ while (items_to_copy) { struct element *item_ptr = get_next_item(); /* __counted_by stays in sync: */ p->valid_count++; p->item[p->valid_count - 1] = *item_ptr; } } We would want to catch cases there p->item[] is accessed with an index that is >= p->valid_count, even though the allocation is (currently) larger. However, if we ever reached valid_count >= alloc_count, we need to trap too, since we can still "see" the true allocation size. Now, the __alloc_size hint is visible in very few places, so if there is a strong reason to do so, I can live with saying that __counted_by takes full precedence over __alloc_size. It seems it should be possible to compare when both are present, but I can live with __counted_by being the universal truth. :) > > >> or > >> p->foo was not set to any value as in test 3 and 4 > > > > For tests 3 and 4, yes, this was my mistake. I have fixed up the tests > > now. Bill noticed the same issue. Sorry for the think-o! > > > >> ==== > >> > >> i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. > >> > >> I think that this should be considered as an user error, and the documentation of the attribute should include > >> this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: > >> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) > >> > >> We can add a new warning option -Wcounted-by to report such user error if needed. > >> > >> What’s your opinion on this? > > > > I think it is correct to allow mismatch between allocation and > > counted_by as long as only the least of the two is used. > > What’s your mean by “only the least of the two is used”? I was just restating the above: if size information is available via both __alloc_size and __counted_by, the smaller of the two should be used. > > > This may be > > desirable in a few situations. One example would be a large allocation > > that is slowly filled up by the program. > > So, for such situation, whenever the allocation is filled up, the field that hold the “counted_by” attribute should be increased at the same time, > Then, the “counted_by” value always sync with the real allocation. > > I.e. the counted_by member is > > slowly increased during runtime (but not beyond the true allocation size). > > Then there should be source code to increase the “counted_by” field whenever the allocated space increased too. > > > > Of course allocation size is only available in limited situations, so > > the loss of that info is fine: we have counted_by for everything else. > > The point is: allocation size should synced with the value of “counted_by”. LLVM’s RFC also have the similar requirement: > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 Right, I'm saying it would be nice if __alloc_size was checked as well, in the sense that if it is available, it knows without question what the size of the allocation is. If __alloc_size and __counted_by conflict, the smaller of the two should be the truth. But, as I said, if there is some need to explicitly ignore __alloc_size when __counted_by is present, I can live with it; we just need to document it. If the RFC and you agree that the __counted_by variable can only ever be (re)assigned after the flex array has been (re)allocated, then I guess we'll see how it goes. :) I think most places in the kernel using __counted_by will be fine, but I suspect we may have cases where we need to update it like in the loop I described above. If that's true, we can revisit the requirement then. :) -Kees
> On Jul 17, 2023, at 7:40 PM, Kees Cook <keescook@chromium.org> wrote: > > On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: >> >>> On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> wrote: >>> >>> In the bug, the problem is that "p" isn't known to be allocated, if I'm >>> reading that correctly? >> >> I think that the major point in PR109557 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): >> >> for the following pointer p.3_1, >> >> p.3_1 = p; >> _2 = __builtin_object_size (p.3_1, 0); >> >> Question: why the size of p.3_1 cannot use the TYPE_SIZE of the pointee of p when the TYPE_SIZE can be determined at compile time? >> >> Answer: From just knowing the type of the pointee of p, the compiler cannot determine the size of the object. > > Why is that? "p" points to "struct P", which has a fixed size. There > must be an assumption somewhere that a pointer is allocated, otherwise > __bos would almost never work? My understanding from the comments in PR109557 was: In general the pointer could point to the first object of an array that has more elements, or to an object of a different type. Without seeing the real allocation to the pointer, the compiler cannot assume that the pointer point to an object that has the exact same type as its declaration. Sid and Martin, is the above understand correctly? Honestly, I am still not 100% clear on this yet. Jakub, Sid and Martin, could you please explain a little bit more here, especially for the following small example? [opc@qinzhao-ol8u3-x86 109557]$ cat t.c #include <stdlib.h> #include <assert.h> struct P { int k; int x[10]; } *p; void store(int a, int b) { p = (struct P *)malloc (sizeof (struct P)); p->k = a; p->x[b] = 0; assert (__builtin_dynamic_object_size (p->x, 1) == sizeof (int[10])); assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); return; } int main() { store(7, 7); assert (__builtin_dynamic_object_size (p->x, 1) == sizeof (int[10])); assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); free (p); } [opc@qinzhao-ol8u3-x86 109557]$ sh t /home/opc/Install/latest/bin/gcc -O -fdump-tree-all t.c a.out: t.c:21: main: Assertion `__builtin_dynamic_object_size (p->x, 1) == sizeof (int[10])' failed. t: line 19: 859944 Aborted (core dumped) ./a.out In the above, among the 4 assertions, only the last one failed. Why GCC can use the TYPE_SIZE of the pointee of the pointer “p->x” as the size of the object, but cannot use the TYPE_SIZE of the pointee of the pointer “p” as the size of the object? > >> Therefore the bug has been closed. >> >> In your following testing 5: >> >>> I'm not sure this is a reasonable behavior, but >>> let me get into the specific test, which looks like this: >>> >>> TEST(counted_by_seen_by_bdos) >>> { >>> struct annotated *p; >>> int index = MAX_INDEX + unconst; >>> >>> p = alloc_annotated(index); >>> >>> REPORT_SIZE(p->array); >>> /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); >>> /* Check array size alone. */ >>> /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), SIZE_MAX); >>> /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(*p->array)); >>> /* Check check entire object size. */ >>> /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); >>> /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), sizeof(*p) + p->foo * sizeof(*p->array)); >>> } >>> >>> Test 5 should pass as well, since, again, p can be examined. Passing p >>> to __bdos implies it is allocated and the __counted_by annotation can be >>> examined. >> >> Since the call to the routine “alloc_annotated" cannot be inlined, GCC does not see any allocation calls for the pointer p. > > Correct. > >> At the same time, due to the same reason as PR109986, GCC cannot determine the size of the object by just knowing the TYPE_SIZE >> of the pointee of p. > > So the difference between test 3 and test 5 is that "p" is explicitly > dereferenced to find "array", and therefore an assumption is established > that "p" is allocated? Yes, this might be the assumption that GCC made -:) > >> So, this is exactly the same issue as PR109557. It’s an existing behavior per the current __buitlin_object_size algorithm. >> I am still not very sure whether the situation in PR109557 can be improved or not, but either way, it’s a separate issue. > > Okay, so the issue is one of object allocation visibility (or > assumptions there in)? Might be, let’s see what Sid or Martin will say on this. > >> Please see the new testing case I added for PR109557, you will see that the above case 5 is a similar case as the new testing case in PR109557. > > I will ponder this a bit more to see if I can come up with a useful > test case to replace the part from "test 5" above. > >>> >>> If "return p->array[index];" would be caught by the sanitizer, then >>> it follows that __builtin_dynamic_object_size(p, 1) must also know the >>> size. i.e. both must examine "p" and its trailing flexible array and >>> __counted_by annotation. >>> >>>> >>>> 2. The common issue for the failed testing 3, 4, 9, 10 is: >>>> >>>> for the following annotated structure: >>>> >>>> ==== >>>> struct annotated { >>>> unsigned long flags; >>>> size_t foo; >>>> int array[] __attribute__((counted_by (foo))); >>>> }; >>>> >>>> >>>> struct annotated *p; >>>> int index = 16; >>>> >>>> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size >>>> >>>> p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 >>> >>> Right, tests 9 and 10 are checking that the _smallest_ possible value of >>> the array is used. (There are two sources of information: the allocation >>> size and the size calculated by counted_by. The smaller of the two >>> should be used when both are available.) >> >> The counted_by attribute is used to annotate a Flexible array member on how many elements it will have. >> However, if this information can not accurately reflect the real number of elements for the array allocated, >> What’s the purpose of such information? > > For example, imagine code that allocates space for 100 elements since > the common case is that the number of elements will grow over time. > Elements are added as it goes. For example: > > struct grows { > int alloc_count; > int valid_count; > struct element item[] __counted_by(valid_count); > } *p; > > void something(void) > { > p = malloc(sizeof(*p) + sizeof(*p->item) * 100); > p->alloc_count = 100; > p->valid_count = 0; > > /* this loop doesn't check that we don't go over 100. */ > while (items_to_copy) { > struct element *item_ptr = get_next_item(); > /* __counted_by stays in sync: */ > p->valid_count++; > p->item[p->valid_count - 1] = *item_ptr; > } > } > > We would want to catch cases there p->item[] is accessed with an index > that is >= p->valid_count, even though the allocation is (currently) > larger. > > However, if we ever reached valid_count >= alloc_count, we need to trap > too, since we can still "see" the true allocation size. > > Now, the __alloc_size hint is visible in very few places, so if there is > a strong reason to do so, I can live with saying that __counted_by takes > full precedence over __alloc_size. It seems it should be possible to > compare when both are present, but I can live with __counted_by being > the universal truth. :) > Thanks for the example and the explanation. Understood now. LLVM’s RFC requires the following relationship: (https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) Buffer’s real allocated size >= counted_by value Should be true all the time. I think that this is a reasonable requirement. (Otherwise, if counted_by > buffer’s real allocated size, overflow might happen) Is the above enough to cover your use cases? If so, I will study a little bit more to see how to implement this. >> >>>> or >>>> p->foo was not set to any value as in test 3 and 4 >>> >>> For tests 3 and 4, yes, this was my mistake. I have fixed up the tests >>> now. Bill noticed the same issue. Sorry for the think-o! >>> >>>> ==== >>>> >>>> i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. >>>> >>>> I think that this should be considered as an user error, and the documentation of the attribute should include >>>> this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: >>>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) >>>> >>>> We can add a new warning option -Wcounted-by to report such user error if needed. >>>> >>>> What’s your opinion on this? >>> >>> I think it is correct to allow mismatch between allocation and >>> counted_by as long as only the least of the two is used. >> >> What’s your mean by “only the least of the two is used”? > > I was just restating the above: if size information is available via > both __alloc_size and __counted_by, the smaller of the two should be > used. If we are consistent with LLVM’s RFC, __alloc_size >= __counted_by all the time. Then we can always use the counted_by info for the array size. > >> >>> This may be >>> desirable in a few situations. One example would be a large allocation >>> that is slowly filled up by the program. >> >> So, for such situation, whenever the allocation is filled up, the field that hold the “counted_by” attribute should be increased at the same time, >> Then, the “counted_by” value always sync with the real allocation. >>> I.e. the counted_by member is >>> slowly increased during runtime (but not beyond the true allocation size). >> >> Then there should be source code to increase the “counted_by” field whenever the allocated space increased too. >>> >>> Of course allocation size is only available in limited situations, so >>> the loss of that info is fine: we have counted_by for everything else. >> >> The point is: allocation size should synced with the value of “counted_by”. LLVM’s RFC also have the similar requirement: >> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > Right, I'm saying it would be nice if __alloc_size was checked as well, > in the sense that if it is available, it knows without question what the > size of the allocation is. If __alloc_size and __counted_by conflict, > the smaller of the two should be the truth. > > But, as I said, if there is some need to explicitly ignore __alloc_size > when __counted_by is present, I can live with it; we just need to > document it. > > If the RFC and you agree that the __counted_by variable can only ever be > (re)assigned after the flex array has been (re)allocated, then I guess > we'll see how it goes. :) I think most places in the kernel using > __counted_by will be fine, but I suspect we may have cases where we need > to update it like in the loop I described above. If that's true, we can > revisit the requirement then. :) I guess if we can always keep the relationship: __alloc_size >= __counted_by all the time. Should be fine. Please check whether this is enough for kernel, I will check whether this is doable For GCC. thanks. Qing > > -Kees > > -- > Kees Cook
Am Dienstag, dem 18.07.2023 um 15:37 +0000 schrieb Qing Zhao: > > > > On Jul 17, 2023, at 7:40 PM, Kees Cook <keescook@chromium.org> > > wrote: > > > > On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: > > > > > > > On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> > > > > wrote: > > > > > > > > In the bug, the problem is that "p" isn't known to be > > > > allocated, if I'm > > > > reading that correctly? > > > > > > I think that the major point in PR109557 > > > (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): > > > > > > for the following pointer p.3_1, > > > > > > p.3_1 = p; > > > _2 = __builtin_object_size (p.3_1, 0); > > > > > > Question: why the size of p.3_1 cannot use the TYPE_SIZE of the > > > pointee of p when the TYPE_SIZE can be determined at compile > > > time? > > > > > > Answer: From just knowing the type of the pointee of p, the > > > compiler cannot determine the size of the object. > > > > Why is that? "p" points to "struct P", which has a fixed size. > > There > > must be an assumption somewhere that a pointer is allocated, > > otherwise > > __bos would almost never work? > > My understanding from the comments in PR109557 was: > > In general the pointer could point to the first object of an array > that has more elements, or to an object of a different type. > Without seeing the real allocation to the pointer, the compiler > cannot assume that the pointer point to an object that has > the exact same type as its declaration. > > Sid and Martin, is the above understand correctly? Yes. In the example, it *could* work because the compiler could inline 'store' or otherwise use its knowledge about the function definition to conclude that 'p' points to an object of size 'sizeof (struct P)'. But this is fragile because it relies on optimization and will not work across TUs. > Honestly, I am still not 100% clear on this yet. > Jakub, Sid and Martin, could you please explain a little bit more > here, especially for the following small example? > > [opc@qinzhao-ol8u3-x86 109557]$ cat t.c > #include <stdlib.h> > #include <assert.h> > struct P { > int k; > int x[10]; > } *p; > > void store(int a, int b) > { > p = (struct P *)malloc (sizeof (struct P)); > p->k = a; > p->x[b] = 0; > assert (__builtin_dynamic_object_size (p->x, 1) == sizeof > (int[10])); > assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); > return; > } > > int main() > { > store(7, 7); > assert (__builtin_dynamic_object_size (p->x, 1) == sizeof > (int[10])); > assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); > free (p); > } > [opc@qinzhao-ol8u3-x86 109557]$ sh t > /home/opc/Install/latest/bin/gcc -O -fdump-tree-all t.c > a.out: t.c:21: main: Assertion `__builtin_dynamic_object_size (p->x, > 1) == sizeof (int[10])' failed. > t: line 19: 859944 Aborted (core dumped) ./a.out > > > In the above, among the 4 assertions, only the last one failed. I don't know why this is the case. > > Why GCC can use the TYPE_SIZE of the pointee of the pointer “p->x” as > the size of the object, I do not think it can do this in general. Is this how it is implemented? Thus would then seem incorrect to me. > but cannot use the TYPE_SIZE of the pointee of the pointer “p” as the > size of the object? In general, the type of a pointer does not say anything about the object it points to, because you could cast the pointer to a different type, pass it around, and then cast it back before use. Only observed allocations or observed accesses provide information about the type / existence of an object at the corresponding address. 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]); Martin > > > > > > Therefore the bug has been closed. > > > > > > In your following testing 5: > > > > > > > I'm not sure this is a reasonable behavior, but > > > > let me get into the specific test, which looks like this: > > > > > > > > TEST(counted_by_seen_by_bdos) > > > > { > > > > struct annotated *p; > > > > int index = MAX_INDEX + unconst; > > > > > > > > p = alloc_annotated(index); > > > > > > > > REPORT_SIZE(p->array); > > > > /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); > > > > /* Check array size alone. */ > > > > /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), > > > > SIZE_MAX); > > > > /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), > > > > p->foo * sizeof(*p->array)); > > > > /* Check check entire object size. */ > > > > /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); > > > > /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), > > > > sizeof(*p) + p->foo * sizeof(*p->array)); > > > > } > > > > > > > > Test 5 should pass as well, since, again, p can be examined. > > > > Passing p > > > > to __bdos implies it is allocated and the __counted_by > > > > annotation can be > > > > examined. > > > > > > Since the call to the routine “alloc_annotated" cannot be > > > inlined, GCC does not see any allocation calls for the pointer p. > > > > Correct. > > > > > At the same time, due to the same reason as PR109986, GCC cannot > > > determine the size of the object by just knowing the TYPE_SIZE > > > of the pointee of p. > > > > So the difference between test 3 and test 5 is that "p" is > > explicitly > > dereferenced to find "array", and therefore an assumption is > > established > > that "p" is allocated? > > Yes, this might be the assumption that GCC made -:) > > > > > So, this is exactly the same issue as PR109557. It’s an existing > > > behavior per the current __buitlin_object_size algorithm. > > > I am still not very sure whether the situation in PR109557 can be > > > improved or not, but either way, it’s a separate issue. > > > > Okay, so the issue is one of object allocation visibility (or > > assumptions there in)? > > Might be, let’s see what Sid or Martin will say on this. > > > > > Please see the new testing case I added for PR109557, you will > > > see that the above case 5 is a similar case as the new testing > > > case in PR109557. > > > > I will ponder this a bit more to see if I can come up with a useful > > test case to replace the part from "test 5" above. > > > > > > > > > > If "return p->array[index];" would be caught by the sanitizer, > > > > then > > > > it follows that __builtin_dynamic_object_size(p, 1) must also > > > > know the > > > > size. i.e. both must examine "p" and its trailing flexible > > > > array and > > > > __counted_by annotation. > > > > > > > > > > > > > > 2. The common issue for the failed testing 3, 4, 9, 10 is: > > > > > > > > > > for the following annotated structure: > > > > > > > > > > ==== > > > > > struct annotated { > > > > > unsigned long flags; > > > > > size_t foo; > > > > > int array[] __attribute__((counted_by (foo))); > > > > > }; > > > > > > > > > > > > > > > struct annotated *p; > > > > > int index = 16; > > > > > > > > > > p = malloc(sizeof(*p) + index * sizeof(*p->array)); // > > > > > allocated real size > > > > > > > > > > p->foo = index + 2; // p->foo was set by a different value > > > > > than the real size of p->array as in test 9 and 10 > > > > > > > > Right, tests 9 and 10 are checking that the _smallest_ possible > > > > value of > > > > the array is used. (There are two sources of information: the > > > > allocation > > > > size and the size calculated by counted_by. The smaller of the > > > > two > > > > should be used when both are available.) > > > > > > The counted_by attribute is used to annotate a Flexible array > > > member on how many elements it will have. > > > However, if this information can not accurately reflect the real > > > number of elements for the array allocated, > > > What’s the purpose of such information? > > > > For example, imagine code that allocates space for 100 elements > > since > > the common case is that the number of elements will grow over time. > > Elements are added as it goes. For example: > > > > struct grows { > > int alloc_count; > > int valid_count; > > struct element item[] __counted_by(valid_count); > > } *p; > > > > void something(void) > > { > > p = malloc(sizeof(*p) + sizeof(*p->item) * 100); > > p->alloc_count = 100; > > p->valid_count = 0; > > > > /* this loop doesn't check that we don't go over 100. */ > > while (items_to_copy) { > > struct element *item_ptr = get_next_item(); > > /* __counted_by stays in sync: */ > > p->valid_count++; > > p->item[p->valid_count - 1] = *item_ptr; > > } > > } > > > > We would want to catch cases there p->item[] is accessed with an > > index > > that is >= p->valid_count, even though the allocation is > > (currently) > > larger. > > > > However, if we ever reached valid_count >= alloc_count, we need to > > trap > > too, since we can still "see" the true allocation size. > > > > Now, the __alloc_size hint is visible in very few places, so if > > there is > > a strong reason to do so, I can live with saying that __counted_by > > takes > > full precedence over __alloc_size. It seems it should be possible > > to > > compare when both are present, but I can live with __counted_by > > being > > the universal truth. :) > > > > Thanks for the example and the explanation. Understood now. > > LLVM’s RFC requires the following relationship: > (https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbound > s-safety/70854#maintaining-correctness-of-bounds-annotations-18) > > Buffer’s real allocated size >= counted_by value > > Should be true all the time. > > I think that this is a reasonable requirement. > > (Otherwise, if counted_by > buffer’s real allocated size, overflow > might happen) > > Is the above enough to cover your use cases? > > If so, I will study a little bit more to see how to implement this. > > > > > > > > or > > > > > p->foo was not set to any value as in test 3 and 4 > > > > > > > > For tests 3 and 4, yes, this was my mistake. I have fixed up > > > > the tests > > > > now. Bill noticed the same issue. Sorry for the think-o! > > > > > > > > > ==== > > > > > > > > > > i.e, the value of p->foo is NOT synced with the number of > > > > > elements allocated for the array p->array. > > > > > > > > > > I think that this should be considered as an user error, and > > > > > the documentation of the attribute should include > > > > > this requirement. (In the LLVM’s RFC, such requirement was > > > > > included in the programing model: > > > > > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > > > > ) > > > > > > > > > > We can add a new warning option -Wcounted-by to report such > > > > > user error if needed. > > > > > > > > > > What’s your opinion on this? > > > > > > > > I think it is correct to allow mismatch between allocation and > > > > counted_by as long as only the least of the two is used. > > > > > > What’s your mean by “only the least of the two is used”? > > > > I was just restating the above: if size information is available > > via > > both __alloc_size and __counted_by, the smaller of the two should > > be > > used. > > If we are consistent with LLVM’s RFC, __alloc_size >= __counted_by > all the time. > Then we can always use the counted_by info for the array size. > > > > > > > > > This may be > > > > desirable in a few situations. One example would be a large > > > > allocation > > > > that is slowly filled up by the program. > > > > > > So, for such situation, whenever the allocation is filled up, the > > > field that hold the “counted_by” attribute should be increased at > > > the same time, > > > Then, the “counted_by” value always sync with the real > > > allocation. > > > > I.e. the counted_by member is > > > > slowly increased during runtime (but not beyond the true > > > > allocation size). > > > > > > Then there should be source code to increase the “counted_by” > > > field whenever the allocated space increased too. > > > > > > > > Of course allocation size is only available in limited > > > > situations, so > > > > the loss of that info is fine: we have counted_by for > > > > everything else. > > > > > > The point is: allocation size should synced with the value of > > > “counted_by”. LLVM’s RFC also have the similar requirement: > > > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > > > Right, I'm saying it would be nice if __alloc_size was checked as > > well, > > in the sense that if it is available, it knows without question > > what the > > size of the allocation is. If __alloc_size and __counted_by > > conflict, > > the smaller of the two should be the truth. > > > > > But, as I said, if there is some need to explicitly ignore > > __alloc_size > > when __counted_by is present, I can live with it; we just need to > > document it. > > > > If the RFC and you agree that the __counted_by variable can only > > ever be > > (re)assigned after the flex array has been (re)allocated, then I > > guess > > we'll see how it goes. :) I think most places in the kernel using > > __counted_by will be fine, but I suspect we may have cases where we > > need > > to update it like in the loop I described above. If that's true, we > > can > > revisit the requirement then. :) > > I guess if we can always keep the relationship: __alloc_size >= > __counted_by all the time. Should be fine. > > Please check whether this is enough for kernel, I will check whether > this is doable For GCC. > > thanks. > > > Qing > > > > -Kees > > > > -- > > Kees Cook >
> On Jul 18, 2023, at 12:03 PM, Martin Uecker <uecker@tugraz.at> wrote: > > Am Dienstag, dem 18.07.2023 um 15:37 +0000 schrieb Qing Zhao: >> >> >>> On Jul 17, 2023, at 7:40 PM, Kees Cook <keescook@chromium.org> >>> wrote: >>> >>> On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: >>>> >>>>> On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> >>>>> wrote: >>>>> >>>>> In the bug, the problem is that "p" isn't known to be >>>>> allocated, if I'm >>>>> reading that correctly? >>>> >>>> I think that the major point in PR109557 >>>> (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): >>>> >>>> for the following pointer p.3_1, >>>> >>>> p.3_1 = p; >>>> _2 = __builtin_object_size (p.3_1, 0); >>>> >>>> Question: why the size of p.3_1 cannot use the TYPE_SIZE of the >>>> pointee of p when the TYPE_SIZE can be determined at compile >>>> time? >>>> >>>> Answer: From just knowing the type of the pointee of p, the >>>> compiler cannot determine the size of the object. >>> >>> Why is that? "p" points to "struct P", which has a fixed size. >>> There >>> must be an assumption somewhere that a pointer is allocated, >>> otherwise >>> __bos would almost never work? >> >> My understanding from the comments in PR109557 was: >> >> In general the pointer could point to the first object of an array >> that has more elements, or to an object of a different type. >> Without seeing the real allocation to the pointer, the compiler >> cannot assume that the pointer point to an object that has >> the exact same type as its declaration. >> >> Sid and Martin, is the above understand correctly? > > Yes. > > In the example, it *could* work because the compiler > could inline 'store' or otherwise use its knowledge about > the function definition to conclude that 'p' points to > an object of size 'sizeof (struct P)'. But this is fragile > because it relies on optimization and will not work across > TUs. > >> Honestly, I am still not 100% clear on this yet. > >> Jakub, Sid and Martin, could you please explain a little bit more >> here, especially for the following small example? >> >> [opc@qinzhao-ol8u3-x86 109557]$ cat t.c >> #include <stdlib.h> >> #include <assert.h> >> struct P { >> int k; >> int x[10]; >> } *p; >> >> void store(int a, int b) >> { >> p = (struct P *)malloc (sizeof (struct P)); >> p->k = a; >> p->x[b] = 0; >> assert (__builtin_dynamic_object_size (p->x, 1) == sizeof >> (int[10])); >> assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); >> return; >> } >> >> int main() >> { >> store(7, 7); >> assert (__builtin_dynamic_object_size (p->x, 1) == sizeof >> (int[10])); >> assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); >> free (p); >> } >> [opc@qinzhao-ol8u3-x86 109557]$ sh t >> /home/opc/Install/latest/bin/gcc -O -fdump-tree-all t.c >> a.out: t.c:21: main: Assertion `__builtin_dynamic_object_size (p->x, >> 1) == sizeof (int[10])' failed. >> t: line 19: 859944 Aborted (core dumped) ./a.out >> >> >> In the above, among the 4 assertions, only the last one failed. > > I don't know why this is the case. > >> >> Why GCC can use the TYPE_SIZE of the pointee of the pointer “p->x” as >> the size of the object, > > I do not think it can do this in general. Is this how it > is implemented? No. -:) I guess that the implementation of this should base on your following case, “observed accesses”: Although I am not 100% sure on the definition of “observed accesses”. p->x is an access to the field of the object, so compiler can assume that the object exist and have the type associate with this access? On the other hand, “p” is just a plain pointer, no observed access. > Thus would then seem incorrect to me. > >> but cannot use the TYPE_SIZE of the pointee of the pointer “p” as the >> size of the object? > > In general, the type of a pointer does not say anything about the > object it points to, because you could cast the pointer to a different > type, pass it around, and then cast it back before use. Okay, I see. > > Only observed allocations or observed accesses provide information > about the type / existence of an object at the corresponding address. What will be included in “observed accesses”? > > 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]); Thanks for the info. Qing > > > > Martin > > >> >>> >>>> Therefore the bug has been closed. >>>> >>>> In your following testing 5: >>>> >>>>> I'm not sure this is a reasonable behavior, but >>>>> let me get into the specific test, which looks like this: >>>>> >>>>> TEST(counted_by_seen_by_bdos) >>>>> { >>>>> struct annotated *p; >>>>> int index = MAX_INDEX + unconst; >>>>> >>>>> p = alloc_annotated(index); >>>>> >>>>> REPORT_SIZE(p->array); >>>>> /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); >>>>> /* Check array size alone. */ >>>>> /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), >>>>> SIZE_MAX); >>>>> /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), >>>>> p->foo * sizeof(*p->array)); >>>>> /* Check check entire object size. */ >>>>> /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); >>>>> /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), >>>>> sizeof(*p) + p->foo * sizeof(*p->array)); >>>>> } >>>>> >>>>> Test 5 should pass as well, since, again, p can be examined. >>>>> Passing p >>>>> to __bdos implies it is allocated and the __counted_by >>>>> annotation can be >>>>> examined. >>>> >>>> Since the call to the routine “alloc_annotated" cannot be >>>> inlined, GCC does not see any allocation calls for the pointer p. >>> >>> Correct. >>> >>>> At the same time, due to the same reason as PR109986, GCC cannot >>>> determine the size of the object by just knowing the TYPE_SIZE >>>> of the pointee of p. >>> >>> So the difference between test 3 and test 5 is that "p" is >>> explicitly >>> dereferenced to find "array", and therefore an assumption is >>> established >>> that "p" is allocated? >> >> Yes, this might be the assumption that GCC made -:) >>> >>>> So, this is exactly the same issue as PR109557. It’s an existing >>>> behavior per the current __buitlin_object_size algorithm. >>>> I am still not very sure whether the situation in PR109557 can be >>>> improved or not, but either way, it’s a separate issue. >>> >>> Okay, so the issue is one of object allocation visibility (or >>> assumptions there in)? >> >> Might be, let’s see what Sid or Martin will say on this. >>> >>>> Please see the new testing case I added for PR109557, you will >>>> see that the above case 5 is a similar case as the new testing >>>> case in PR109557. >>> >>> I will ponder this a bit more to see if I can come up with a useful >>> test case to replace the part from "test 5" above. >>> >>>>> >>>>> If "return p->array[index];" would be caught by the sanitizer, >>>>> then >>>>> it follows that __builtin_dynamic_object_size(p, 1) must also >>>>> know the >>>>> size. i.e. both must examine "p" and its trailing flexible >>>>> array and >>>>> __counted_by annotation. >>>>> >>>>>> >>>>>> 2. The common issue for the failed testing 3, 4, 9, 10 is: >>>>>> >>>>>> for the following annotated structure: >>>>>> >>>>>> ==== >>>>>> struct annotated { >>>>>> unsigned long flags; >>>>>> size_t foo; >>>>>> int array[] __attribute__((counted_by (foo))); >>>>>> }; >>>>>> >>>>>> >>>>>> struct annotated *p; >>>>>> int index = 16; >>>>>> >>>>>> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // >>>>>> allocated real size >>>>>> >>>>>> p->foo = index + 2; // p->foo was set by a different value >>>>>> than the real size of p->array as in test 9 and 10 >>>>> >>>>> Right, tests 9 and 10 are checking that the _smallest_ possible >>>>> value of >>>>> the array is used. (There are two sources of information: the >>>>> allocation >>>>> size and the size calculated by counted_by. The smaller of the >>>>> two >>>>> should be used when both are available.) >>>> >>>> The counted_by attribute is used to annotate a Flexible array >>>> member on how many elements it will have. >>>> However, if this information can not accurately reflect the real >>>> number of elements for the array allocated, >>>> What’s the purpose of such information? >>> >>> For example, imagine code that allocates space for 100 elements >>> since >>> the common case is that the number of elements will grow over time. >>> Elements are added as it goes. For example: >>> >>> struct grows { >>> int alloc_count; >>> int valid_count; >>> struct element item[] __counted_by(valid_count); >>> } *p; >>> >>> void something(void) >>> { >>> p = malloc(sizeof(*p) + sizeof(*p->item) * 100); >>> p->alloc_count = 100; >>> p->valid_count = 0; >>> >>> /* this loop doesn't check that we don't go over 100. */ >>> while (items_to_copy) { >>> struct element *item_ptr = get_next_item(); >>> /* __counted_by stays in sync: */ >>> p->valid_count++; >>> p->item[p->valid_count - 1] = *item_ptr; >>> } >>> } >>> >>> We would want to catch cases there p->item[] is accessed with an >>> index >>> that is >= p->valid_count, even though the allocation is >>> (currently) >>> larger. >>> >>> However, if we ever reached valid_count >= alloc_count, we need to >>> trap >>> too, since we can still "see" the true allocation size. >>> >>> Now, the __alloc_size hint is visible in very few places, so if >>> there is >>> a strong reason to do so, I can live with saying that __counted_by >>> takes >>> full precedence over __alloc_size. It seems it should be possible >>> to >>> compare when both are present, but I can live with __counted_by >>> being >>> the universal truth. :) >>> >> >> Thanks for the example and the explanation. Understood now. >> >> LLVM’s RFC requires the following relationship: >> (https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbound >> s-safety/70854#maintaining-correctness-of-bounds-annotations-18) >> >> Buffer’s real allocated size >= counted_by value >> >> Should be true all the time. >> >> I think that this is a reasonable requirement. >> >> (Otherwise, if counted_by > buffer’s real allocated size, overflow >> might happen) >> >> Is the above enough to cover your use cases? >> >> If so, I will study a little bit more to see how to implement this. >>>> >>>>>> or >>>>>> p->foo was not set to any value as in test 3 and 4 >>>>> >>>>> For tests 3 and 4, yes, this was my mistake. I have fixed up >>>>> the tests >>>>> now. Bill noticed the same issue. Sorry for the think-o! >>>>> >>>>>> ==== >>>>>> >>>>>> i.e, the value of p->foo is NOT synced with the number of >>>>>> elements allocated for the array p->array. >>>>>> >>>>>> I think that this should be considered as an user error, and >>>>>> the documentation of the attribute should include >>>>>> this requirement. (In the LLVM’s RFC, such requirement was >>>>>> included in the programing model: >>>>>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 >>>>>> ) >>>>>> >>>>>> We can add a new warning option -Wcounted-by to report such >>>>>> user error if needed. >>>>>> >>>>>> What’s your opinion on this? >>>>> >>>>> I think it is correct to allow mismatch between allocation and >>>>> counted_by as long as only the least of the two is used. >>>> >>>> What’s your mean by “only the least of the two is used”? >>> >>> I was just restating the above: if size information is available >>> via >>> both __alloc_size and __counted_by, the smaller of the two should >>> be >>> used. >> >> If we are consistent with LLVM’s RFC, __alloc_size >= __counted_by >> all the time. >> Then we can always use the counted_by info for the array size. >>> >>>> >>>>> This may be >>>>> desirable in a few situations. One example would be a large >>>>> allocation >>>>> that is slowly filled up by the program. >>>> >>>> So, for such situation, whenever the allocation is filled up, the >>>> field that hold the “counted_by” attribute should be increased at >>>> the same time, >>>> Then, the “counted_by” value always sync with the real >>>> allocation. >>>>> I.e. the counted_by member is >>>>> slowly increased during runtime (but not beyond the true >>>>> allocation size). >>>> >>>> Then there should be source code to increase the “counted_by” >>>> field whenever the allocated space increased too. >>>>> >>>>> Of course allocation size is only available in limited >>>>> situations, so >>>>> the loss of that info is fine: we have counted_by for >>>>> everything else. >>>> >>>> The point is: allocation size should synced with the value of >>>> “counted_by”. LLVM’s RFC also have the similar requirement: >>>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 >>> >>> Right, I'm saying it would be nice if __alloc_size was checked as >>> well, >>> in the sense that if it is available, it knows without question >>> what the >>> size of the allocation is. If __alloc_size and __counted_by >>> conflict, >>> the smaller of the two should be the truth. >> >>> >>> But, as I said, if there is some need to explicitly ignore >>> __alloc_size >>> when __counted_by is present, I can live with it; we just need to >>> document it. >>> >>> If the RFC and you agree that the __counted_by variable can only >>> ever be >>> (re)assigned after the flex array has been (re)allocated, then I >>> guess >>> we'll see how it goes. :) I think most places in the kernel using >>> __counted_by will be fine, but I suspect we may have cases where we >>> need >>> to update it like in the loop I described above. If that's true, we >>> can >>> revisit the requirement then. :) >> >> I guess if we can always keep the relationship: __alloc_size >= >> __counted_by all the time. Should be fine. >> >> Please check whether this is enough for kernel, I will check whether >> this is doable For GCC. >> >> thanks. >> >> >> Qing >>> >>> -Kees >>> >>> -- >>> Kees Cook >> > > -- > Univ.-Prof. Dr. rer. nat. Martin Uecker > Graz University of Technology > Institute of Biomedical Imaging
Am Dienstag, dem 18.07.2023 um 16:25 +0000 schrieb Qing Zhao: > > > > On Jul 18, 2023, at 12:03 PM, Martin Uecker <uecker@tugraz.at> > > wrote: > > > > Am Dienstag, dem 18.07.2023 um 15:37 +0000 schrieb Qing Zhao: > > > > > > > > > > On Jul 17, 2023, at 7:40 PM, Kees Cook <keescook@chromium.org> > > > > wrote: > > > > > > > > On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: > > > > > > > > > > > On Jul 13, 2023, at 4:31 PM, Kees Cook > > > > > > <keescook@chromium.org> > > > > > > wrote: > > > > > > > > > > > > In the bug, the problem is that "p" isn't known to be > > > > > > allocated, if I'm > > > > > > reading that correctly? > > > > > > > > > > I think that the major point in PR109557 > > > > > (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): > > > > > > > > > > for the following pointer p.3_1, > > > > > > > > > > p.3_1 = p; > > > > > _2 = __builtin_object_size (p.3_1, 0); > > > > > > > > > > Question: why the size of p.3_1 cannot use the TYPE_SIZE of > > > > > the > > > > > pointee of p when the TYPE_SIZE can be determined at compile > > > > > time? > > > > > > > > > > Answer: From just knowing the type of the pointee of p, the > > > > > compiler cannot determine the size of the object. > > > > > > > > Why is that? "p" points to "struct P", which has a fixed size. > > > > There > > > > must be an assumption somewhere that a pointer is allocated, > > > > otherwise > > > > __bos would almost never work? > > > > > > My understanding from the comments in PR109557 was: > > > > > > In general the pointer could point to the first object of an > > > array > > > that has more elements, or to an object of a different type. > > > Without seeing the real allocation to the pointer, the compiler > > > cannot assume that the pointer point to an object that has > > > the exact same type as its declaration. > > > > > > Sid and Martin, is the above understand correctly? > > > > Yes. > > > > In the example, it *could* work because the compiler > > could inline 'store' or otherwise use its knowledge about > > the function definition to conclude that 'p' points to > > an object of size 'sizeof (struct P)'. But this is fragile > > because it relies on optimization and will not work across > > TUs. > > > > > Honestly, I am still not 100% clear on this yet. > > > > > Jakub, Sid and Martin, could you please explain a little bit > > > more > > > here, especially for the following small example? > > > > > > [opc@qinzhao-ol8u3-x86 109557]$ cat t.c > > > #include <stdlib.h> > > > #include <assert.h> > > > struct P { > > > int k; > > > int x[10]; > > > } *p; > > > > > > void store(int a, int b) > > > { > > > p = (struct P *)malloc (sizeof (struct P)); > > > p->k = a; > > > p->x[b] = 0; > > > assert (__builtin_dynamic_object_size (p->x, 1) == sizeof > > > (int[10])); > > > assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct > > > P)); > > > return; > > > } > > > > > > int main() > > > { > > > store(7, 7); > > > assert (__builtin_dynamic_object_size (p->x, 1) == sizeof > > > (int[10])); > > > assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct > > > P)); > > > free (p); > > > } > > > [opc@qinzhao-ol8u3-x86 109557]$ sh t > > > /home/opc/Install/latest/bin/gcc -O -fdump-tree-all t.c > > > a.out: t.c:21: main: Assertion `__builtin_dynamic_object_size (p- > > > >x, > > > 1) == sizeof (int[10])' failed. > > > t: line 19: 859944 Aborted (core dumped) ./a.out > > > > > > > > > In the above, among the 4 assertions, only the last one failed. > > > > I don't know why this is the case. > > > > > > > > Why GCC can use the TYPE_SIZE of the pointee of the pointer “p- > > > >x” as > > > the size of the object, > > > > I do not think it can do this in general. Is this how it > > is implemented? > > No. -:) > > I guess that the implementation of this should base on your > following case, “observed accesses”: > Although I am not 100% sure on the definition of “observed accesses”. > > p->x is an access to the field of the object, so compiler can assume > that the object exist and have > the type associate with this access? > Only if the access happens at run-time, but the argument to BDOS is not evaluated, so there is no access. At least, this is my guess based on C's semantics. > On the other hand, “p” is just a plain pointer, no observed access. > > > Thus would then seem incorrect to me. > > > > > but cannot use the TYPE_SIZE of the pointee of the pointer “p” as > > > the > > > size of the object? > > > > In general, the type of a pointer does not say anything about the > > object it points to, because you could cast the pointer to a > > different > > type, pass it around, and then cast it back before use. > > Okay, I see. > > > > Only observed allocations or observed accesses provide information > > about the type / existence of an object at the corresponding > > address. > > What will be included in “observed accesses”? Any read or write access can be used to determine that there must be an object of the corresponding type at this location. (A write access could possibly create an object.) This still does not tell one anything about the size of the storage region, because it could be larger than one object of this type. Martin > > > > 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]); > > Thanks for the info. > > Qing > > > > > > > > Martin > > > > > > > > > > > > > > > > Therefore the bug has been closed. > > > > > > > > > > In your following testing 5: > > > > > > > > > > > I'm not sure this is a reasonable behavior, but > > > > > > let me get into the specific test, which looks like this: > > > > > > > > > > > > TEST(counted_by_seen_by_bdos) > > > > > > { > > > > > > struct annotated *p; > > > > > > int index = MAX_INDEX + unconst; > > > > > > > > > > > > p = alloc_annotated(index); > > > > > > > > > > > > REPORT_SIZE(p->array); > > > > > > /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); > > > > > > /* Check array size alone. */ > > > > > > /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), > > > > > > SIZE_MAX); > > > > > > /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, > > > > > > 1), > > > > > > p->foo * sizeof(*p->array)); > > > > > > /* Check check entire object size. */ > > > > > > /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); > > > > > > /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), > > > > > > sizeof(*p) + p->foo * sizeof(*p->array)); > > > > > > } > > > > > > > > > > > > Test 5 should pass as well, since, again, p can be > > > > > > examined. > > > > > > Passing p > > > > > > to __bdos implies it is allocated and the __counted_by > > > > > > annotation can be > > > > > > examined. > > > > > > > > > > Since the call to the routine “alloc_annotated" cannot be > > > > > inlined, GCC does not see any allocation calls for the > > > > > pointer p. > > > > > > > > Correct. > > > > > > > > > At the same time, due to the same reason as PR109986, GCC > > > > > cannot > > > > > determine the size of the object by just knowing the > > > > > TYPE_SIZE > > > > > of the pointee of p. > > > > > > > > So the difference between test 3 and test 5 is that "p" is > > > > explicitly > > > > dereferenced to find "array", and therefore an assumption is > > > > established > > > > that "p" is allocated? > > > > > > Yes, this might be the assumption that GCC made -:) > > > > > > > > > So, this is exactly the same issue as PR109557. It’s an > > > > > existing > > > > > behavior per the current __buitlin_object_size algorithm. > > > > > I am still not very sure whether the situation in PR109557 > > > > > can be > > > > > improved or not, but either way, it’s a separate issue. > > > > > > > > Okay, so the issue is one of object allocation visibility (or > > > > assumptions there in)? > > > > > > Might be, let’s see what Sid or Martin will say on this. > > > > > > > > > Please see the new testing case I added for PR109557, you > > > > > will > > > > > see that the above case 5 is a similar case as the new > > > > > testing > > > > > case in PR109557. > > > > > > > > I will ponder this a bit more to see if I can come up with a > > > > useful > > > > test case to replace the part from "test 5" above. > > > > > > > > > > > > > > > > If "return p->array[index];" would be caught by the > > > > > > sanitizer, > > > > > > then > > > > > > it follows that __builtin_dynamic_object_size(p, 1) must > > > > > > also > > > > > > know the > > > > > > size. i.e. both must examine "p" and its trailing flexible > > > > > > array and > > > > > > __counted_by annotation. > > > > > > > > > > > > > > > > > > > > 2. The common issue for the failed testing 3, 4, 9, 10 > > > > > > > is: > > > > > > > > > > > > > > for the following annotated structure: > > > > > > > > > > > > > > ==== > > > > > > > struct annotated { > > > > > > > unsigned long flags; > > > > > > > size_t foo; > > > > > > > int array[] __attribute__((counted_by (foo))); > > > > > > > }; > > > > > > > > > > > > > > > > > > > > > struct annotated *p; > > > > > > > int index = 16; > > > > > > > > > > > > > > p = malloc(sizeof(*p) + index * sizeof(*p->array)); // > > > > > > > allocated real size > > > > > > > > > > > > > > p->foo = index + 2; // p->foo was set by a different > > > > > > > value > > > > > > > than the real size of p->array as in test 9 and 10 > > > > > > > > > > > > Right, tests 9 and 10 are checking that the _smallest_ > > > > > > possible > > > > > > value of > > > > > > the array is used. (There are two sources of information: > > > > > > the > > > > > > allocation > > > > > > size and the size calculated by counted_by. The smaller of > > > > > > the > > > > > > two > > > > > > should be used when both are available.) > > > > > > > > > > The counted_by attribute is used to annotate a Flexible array > > > > > member on how many elements it will have. > > > > > However, if this information can not accurately reflect the > > > > > real > > > > > number of elements for the array allocated, > > > > > What’s the purpose of such information? > > > > > > > > For example, imagine code that allocates space for 100 elements > > > > since > > > > the common case is that the number of elements will grow over > > > > time. > > > > Elements are added as it goes. For example: > > > > > > > > struct grows { > > > > int alloc_count; > > > > int valid_count; > > > > struct element item[] __counted_by(valid_count); > > > > } *p; > > > > > > > > void something(void) > > > > { > > > > p = malloc(sizeof(*p) + sizeof(*p->item) * 100); > > > > p->alloc_count = 100; > > > > p->valid_count = 0; > > > > > > > > /* this loop doesn't check that we don't go over 100. > > > > */ > > > > while (items_to_copy) { > > > > struct element *item_ptr = get_next_item(); > > > > /* __counted_by stays in sync: */ > > > > p->valid_count++; > > > > p->item[p->valid_count - 1] = *item_ptr; > > > > } > > > > } > > > > > > > > We would want to catch cases there p->item[] is accessed with > > > > an > > > > index > > > > that is >= p->valid_count, even though the allocation is > > > > (currently) > > > > larger. > > > > > > > > However, if we ever reached valid_count >= alloc_count, we need > > > > to > > > > trap > > > > too, since we can still "see" the true allocation size. > > > > > > > > Now, the __alloc_size hint is visible in very few places, so if > > > > there is > > > > a strong reason to do so, I can live with saying that > > > > __counted_by > > > > takes > > > > full precedence over __alloc_size. It seems it should be > > > > possible > > > > to > > > > compare when both are present, but I can live with __counted_by > > > > being > > > > the universal truth. :) > > > > > > > > > > Thanks for the example and the explanation. Understood now. > > > > > > LLVM’s RFC requires the following relationship: > > > ( > > > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbou > > > nd > > > s-safety/70854#maintaining-correctness-of-bounds-annotations-18) > > > > > > Buffer’s real allocated size >= counted_by value > > > > > > Should be true all the time. > > > > > > I think that this is a reasonable requirement. > > > > > > (Otherwise, if counted_by > buffer’s real allocated size, > > > overflow > > > might happen) > > > > > > Is the above enough to cover your use cases? > > > > > > If so, I will study a little bit more to see how to implement > > > this. > > > > > > > > > > > > or > > > > > > > p->foo was not set to any value as in test 3 and 4 > > > > > > > > > > > > For tests 3 and 4, yes, this was my mistake. I have fixed > > > > > > up > > > > > > the tests > > > > > > now. Bill noticed the same issue. Sorry for the think-o! > > > > > > > > > > > > > ==== > > > > > > > > > > > > > > i.e, the value of p->foo is NOT synced with the number of > > > > > > > elements allocated for the array p->array. > > > > > > > > > > > > > > I think that this should be considered as an user error, > > > > > > > and > > > > > > > the documentation of the attribute should include > > > > > > > this requirement. (In the LLVM’s RFC, such requirement > > > > > > > was > > > > > > > included in the programing model: > > > > > > > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > > > > > > ) > > > > > > > > > > > > > > We can add a new warning option -Wcounted-by to report > > > > > > > such > > > > > > > user error if needed. > > > > > > > > > > > > > > What’s your opinion on this? > > > > > > > > > > > > I think it is correct to allow mismatch between allocation > > > > > > and > > > > > > counted_by as long as only the least of the two is used. > > > > > > > > > > What’s your mean by “only the least of the two is used”? > > > > > > > > I was just restating the above: if size information is > > > > available > > > > via > > > > both __alloc_size and __counted_by, the smaller of the two > > > > should > > > > be > > > > used. > > > > > > If we are consistent with LLVM’s RFC, __alloc_size >= > > > __counted_by > > > all the time. > > > Then we can always use the counted_by info for the array size. > > > > > > > > > > > > > > > This may be > > > > > > desirable in a few situations. One example would be a large > > > > > > allocation > > > > > > that is slowly filled up by the program. > > > > > > > > > > So, for such situation, whenever the allocation is filled up, > > > > > the > > > > > field that hold the “counted_by” attribute should be > > > > > increased at > > > > > the same time, > > > > > Then, the “counted_by” value always sync with the real > > > > > allocation. > > > > > > I.e. the counted_by member is > > > > > > slowly increased during runtime (but not beyond the true > > > > > > allocation size). > > > > > > > > > > Then there should be source code to increase the “counted_by” > > > > > field whenever the allocated space increased too. > > > > > > > > > > > > Of course allocation size is only available in limited > > > > > > situations, so > > > > > > the loss of that info is fine: we have counted_by for > > > > > > everything else. > > > > > > > > > > The point is: allocation size should synced with the value of > > > > > “counted_by”. LLVM’s RFC also have the similar requirement: > > > > > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > > > > > > > Right, I'm saying it would be nice if __alloc_size was checked > > > > as > > > > well, > > > > in the sense that if it is available, it knows without question > > > > what the > > > > size of the allocation is. If __alloc_size and __counted_by > > > > conflict, > > > > the smaller of the two should be the truth. > > > > > > > > > > > But, as I said, if there is some need to explicitly ignore > > > > __alloc_size > > > > when __counted_by is present, I can live with it; we just need > > > > to > > > > document it. > > > > > > > > If the RFC and you agree that the __counted_by variable can > > > > only > > > > ever be > > > > (re)assigned after the flex array has been (re)allocated, then > > > > I > > > > guess > > > > we'll see how it goes. :) I think most places in the kernel > > > > using > > > > __counted_by will be fine, but I suspect we may have cases > > > > where we > > > > need > > > > to update it like in the loop I described above. If that's > > > > true, we > > > > can > > > > revisit the requirement then. :) > > > > > > I guess if we can always keep the relationship: __alloc_size > > > >= > > > __counted_by all the time. Should be fine. > > > > > > Please check whether this is enough for kernel, I will check > > > whether > > > this is doable For GCC. > > > > > > thanks. > > > > > > > > > Qing > > > > > > > > -Kees > > > > > > > > -- > > > > Kees Cook > > > > > > > -- > > Univ.-Prof. Dr. rer. nat. Martin Uecker > > Graz University of Technology > > Institute of Biomedical Imaging >
> On Jul 18, 2023, at 11:37 AM, Qing Zhao via Gcc-patches <gcc-patches@gcc.gnu.org> wrote: > > > >> On Jul 17, 2023, at 7:40 PM, Kees Cook <keescook@chromium.org> wrote: >> >> On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: >>> >>>> On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> wrote: >>>> >>>> In the bug, the problem is that "p" isn't known to be allocated, if I'm >>>> reading that correctly? >>> >>> I think that the major point in PR109557 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): >>> >>> for the following pointer p.3_1, >>> >>> p.3_1 = p; >>> _2 = __builtin_object_size (p.3_1, 0); >>> >>> Question: why the size of p.3_1 cannot use the TYPE_SIZE of the pointee of p when the TYPE_SIZE can be determined at compile time? >>> >>> Answer: From just knowing the type of the pointee of p, the compiler cannot determine the size of the object. >> >> Why is that? "p" points to "struct P", which has a fixed size. There >> must be an assumption somewhere that a pointer is allocated, otherwise >> __bos would almost never work? > > My understanding from the comments in PR109557 was: > > In general the pointer could point to the first object of an array that has more elements, or to an object of a different type. > Without seeing the real allocation to the pointer, the compiler cannot assume that the pointer point to an object that has > the exact same type as its declaration. > > Sid and Martin, is the above understand correctly? > > Honestly, I am still not 100% clear on this yet. > > Jakub, Sid and Martin, could you please explain a little bit more here, especially for the following small example? > > [opc@qinzhao-ol8u3-x86 109557]$ cat t.c > #include <stdlib.h> > #include <assert.h> > struct P { > int k; > int x[10]; > } *p; > > void store(int a, int b) > { > p = (struct P *)malloc (sizeof (struct P)); > p->k = a; > p->x[b] = 0; > assert (__builtin_dynamic_object_size (p->x, 1) == sizeof (int[10])); > assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); > return; > } > > int main() > { > store(7, 7); > assert (__builtin_dynamic_object_size (p->x, 1) == sizeof (int[10])); > assert (__builtin_dynamic_object_size (p, 1) == sizeof (struct P)); > free (p); > } > [opc@qinzhao-ol8u3-x86 109557]$ sh t > /home/opc/Install/latest/bin/gcc -O -fdump-tree-all t.c > a.out: t.c:21: main: Assertion `__builtin_dynamic_object_size (p->x, 1) == sizeof (int[10])' failed. > t: line 19: 859944 Aborted (core dumped) ./a.out > > A correction to the above compilation option: /home/opc/Install/latest-d/bin/gcc -O -fstrict-flex-arrays=3 t.c a.out: t.c:22: main: Assertion `__builtin_dynamic_object_size (p, 1) == sizeof (struct P)' failed. t: line 19: 918833 Aborted (core dumped) ./a.out (All others keep the same). Sorry for the mistake. Qing > In the above, among the 4 assertions, only the last one failed. > > Why GCC can use the TYPE_SIZE of the pointee of the pointer “p->x” as the size of the object, > but cannot use the TYPE_SIZE of the pointee of the pointer “p” as the size of the object? > > >> >>> Therefore the bug has been closed. >>> >>> In your following testing 5: >>> >>>> I'm not sure this is a reasonable behavior, but >>>> let me get into the specific test, which looks like this: >>>> >>>> TEST(counted_by_seen_by_bdos) >>>> { >>>> struct annotated *p; >>>> int index = MAX_INDEX + unconst; >>>> >>>> p = alloc_annotated(index); >>>> >>>> REPORT_SIZE(p->array); >>>> /* 1 */ EXPECT_EQ(sizeof(*p), offsetof(typeof(*p), array)); >>>> /* Check array size alone. */ >>>> /* 2 */ EXPECT_EQ(__builtin_object_size(p->array, 1), SIZE_MAX); >>>> /* 3 */ EXPECT_EQ(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(*p->array)); >>>> /* Check check entire object size. */ >>>> /* 4 */ EXPECT_EQ(__builtin_object_size(p, 1), SIZE_MAX); >>>> /* 5 */ EXPECT_EQ(__builtin_dynamic_object_size(p, 1), sizeof(*p) + p->foo * sizeof(*p->array)); >>>> } >>>> >>>> Test 5 should pass as well, since, again, p can be examined. Passing p >>>> to __bdos implies it is allocated and the __counted_by annotation can be >>>> examined. >>> >>> Since the call to the routine “alloc_annotated" cannot be inlined, GCC does not see any allocation calls for the pointer p. >> >> Correct. >> >>> At the same time, due to the same reason as PR109986, GCC cannot determine the size of the object by just knowing the TYPE_SIZE >>> of the pointee of p. >> >> So the difference between test 3 and test 5 is that "p" is explicitly >> dereferenced to find "array", and therefore an assumption is established >> that "p" is allocated? > > Yes, this might be the assumption that GCC made -:) >> >>> So, this is exactly the same issue as PR109557. It’s an existing behavior per the current __buitlin_object_size algorithm. >>> I am still not very sure whether the situation in PR109557 can be improved or not, but either way, it’s a separate issue. >> >> Okay, so the issue is one of object allocation visibility (or >> assumptions there in)? > > Might be, let’s see what Sid or Martin will say on this. >> >>> Please see the new testing case I added for PR109557, you will see that the above case 5 is a similar case as the new testing case in PR109557. >> >> I will ponder this a bit more to see if I can come up with a useful >> test case to replace the part from "test 5" above. >> >>>> >>>> If "return p->array[index];" would be caught by the sanitizer, then >>>> it follows that __builtin_dynamic_object_size(p, 1) must also know the >>>> size. i.e. both must examine "p" and its trailing flexible array and >>>> __counted_by annotation. >>>> >>>>> >>>>> 2. The common issue for the failed testing 3, 4, 9, 10 is: >>>>> >>>>> for the following annotated structure: >>>>> >>>>> ==== >>>>> struct annotated { >>>>> unsigned long flags; >>>>> size_t foo; >>>>> int array[] __attribute__((counted_by (foo))); >>>>> }; >>>>> >>>>> >>>>> struct annotated *p; >>>>> int index = 16; >>>>> >>>>> p = malloc(sizeof(*p) + index * sizeof(*p->array)); // allocated real size >>>>> >>>>> p->foo = index + 2; // p->foo was set by a different value than the real size of p->array as in test 9 and 10 >>>> >>>> Right, tests 9 and 10 are checking that the _smallest_ possible value of >>>> the array is used. (There are two sources of information: the allocation >>>> size and the size calculated by counted_by. The smaller of the two >>>> should be used when both are available.) >>> >>> The counted_by attribute is used to annotate a Flexible array member on how many elements it will have. >>> However, if this information can not accurately reflect the real number of elements for the array allocated, >>> What’s the purpose of such information? >> >> For example, imagine code that allocates space for 100 elements since >> the common case is that the number of elements will grow over time. >> Elements are added as it goes. For example: >> >> struct grows { >> int alloc_count; >> int valid_count; >> struct element item[] __counted_by(valid_count); >> } *p; >> >> void something(void) >> { >> p = malloc(sizeof(*p) + sizeof(*p->item) * 100); >> p->alloc_count = 100; >> p->valid_count = 0; >> >> /* this loop doesn't check that we don't go over 100. */ >> while (items_to_copy) { >> struct element *item_ptr = get_next_item(); >> /* __counted_by stays in sync: */ >> p->valid_count++; >> p->item[p->valid_count - 1] = *item_ptr; >> } >> } >> >> We would want to catch cases there p->item[] is accessed with an index >> that is >= p->valid_count, even though the allocation is (currently) >> larger. >> >> However, if we ever reached valid_count >= alloc_count, we need to trap >> too, since we can still "see" the true allocation size. >> >> Now, the __alloc_size hint is visible in very few places, so if there is >> a strong reason to do so, I can live with saying that __counted_by takes >> full precedence over __alloc_size. It seems it should be possible to >> compare when both are present, but I can live with __counted_by being >> the universal truth. :) >> > > Thanks for the example and the explanation. Understood now. > > LLVM’s RFC requires the following relationship: (https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) > > Buffer’s real allocated size >= counted_by value > > Should be true all the time. > > I think that this is a reasonable requirement. > > (Otherwise, if counted_by > buffer’s real allocated size, overflow might happen) > > Is the above enough to cover your use cases? > > If so, I will study a little bit more to see how to implement this. >>> >>>>> or >>>>> p->foo was not set to any value as in test 3 and 4 >>>> >>>> For tests 3 and 4, yes, this was my mistake. I have fixed up the tests >>>> now. Bill noticed the same issue. Sorry for the think-o! >>>> >>>>> ==== >>>>> >>>>> i.e, the value of p->foo is NOT synced with the number of elements allocated for the array p->array. >>>>> >>>>> I think that this should be considered as an user error, and the documentation of the attribute should include >>>>> this requirement. (In the LLVM’s RFC, such requirement was included in the programing model: >>>>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18) >>>>> >>>>> We can add a new warning option -Wcounted-by to report such user error if needed. >>>>> >>>>> What’s your opinion on this? >>>> >>>> I think it is correct to allow mismatch between allocation and >>>> counted_by as long as only the least of the two is used. >>> >>> What’s your mean by “only the least of the two is used”? >> >> I was just restating the above: if size information is available via >> both __alloc_size and __counted_by, the smaller of the two should be >> used. > > If we are consistent with LLVM’s RFC, __alloc_size >= __counted_by all the time. > Then we can always use the counted_by info for the array size. >> >>> >>>> This may be >>>> desirable in a few situations. One example would be a large allocation >>>> that is slowly filled up by the program. >>> >>> So, for such situation, whenever the allocation is filled up, the field that hold the “counted_by” attribute should be increased at the same time, >>> Then, the “counted_by” value always sync with the real allocation. >>>> I.e. the counted_by member is >>>> slowly increased during runtime (but not beyond the true allocation size). >>> >>> Then there should be source code to increase the “counted_by” field whenever the allocated space increased too. >>>> >>>> Of course allocation size is only available in limited situations, so >>>> the loss of that info is fine: we have counted_by for everything else. >>> >>> The point is: allocation size should synced with the value of “counted_by”. LLVM’s RFC also have the similar requirement: >>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 >> >> Right, I'm saying it would be nice if __alloc_size was checked as well, >> in the sense that if it is available, it knows without question what the >> size of the allocation is. If __alloc_size and __counted_by conflict, >> the smaller of the two should be the truth. > >> >> But, as I said, if there is some need to explicitly ignore __alloc_size >> when __counted_by is present, I can live with it; we just need to >> document it. >> >> If the RFC and you agree that the __counted_by variable can only ever be >> (re)assigned after the flex array has been (re)allocated, then I guess >> we'll see how it goes. :) I think most places in the kernel using >> __counted_by will be fine, but I suspect we may have cases where we need >> to update it like in the loop I described above. If that's true, we can >> revisit the requirement then. :) > > I guess if we can always keep the relationship: __alloc_size >= __counted_by all the time. Should be fine. > > Please check whether this is enough for kernel, I will check whether this is doable For GCC. > > thanks. > > > Qing >> >> -Kees >> >> -- >> Kees Cook
Am Montag, dem 17.07.2023 um 16:40 -0700 schrieb Kees Cook: > On Mon, Jul 17, 2023 at 09:17:48PM +0000, Qing Zhao wrote: > > > > > On Jul 13, 2023, at 4:31 PM, Kees Cook <keescook@chromium.org> > > > wrote: > > > > > > In the bug, the problem is that "p" isn't known to be allocated, > > > if I'm > > > reading that correctly? > > > > I think that the major point in PR109557 > > (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109557): > > > > for the following pointer p.3_1, > > > > p.3_1 = p; > > _2 = __builtin_object_size (p.3_1, 0); > > > > Question: why the size of p.3_1 cannot use the TYPE_SIZE of the > > pointee of p when the TYPE_SIZE can be determined at compile time? > > > > Answer: From just knowing the type of the pointee of p, the > > compiler cannot determine the size of the object. > > Why is that? "p" points to "struct P", which has a fixed size. There > must be an assumption somewhere that a pointer is allocated, > otherwise > __bos would almost never work? It often does not work, because it relies on the optimizer propagating the information instead of the type system. This is why it would be better to have proper *bounds* checks, and not just object size checks. It is not quite clear to me how BOS and bounds checking is supposed to work together, but FAMs should be bounds checked. ... > > > > > > This may be > > > desirable in a few situations. One example would be a large > > > allocation > > > that is slowly filled up by the program. > > > > So, for such situation, whenever the allocation is filled up, the > > field that hold the “counted_by” attribute should be increased at > > the same time, > > Then, the “counted_by” value always sync with the real allocation. > > > I.e. the counted_by member is > > > slowly increased during runtime (but not beyond the true > > > allocation size). > > > > Then there should be source code to increase the “counted_by” field > > whenever the allocated space increased too. > > > > > > Of course allocation size is only available in limited > > > situations, so > > > the loss of that info is fine: we have counted_by for everything > > > else. > > > > The point is: allocation size should synced with the value of > > “counted_by”. LLVM’s RFC also have the similar requirement: > > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > Right, I'm saying it would be nice if __alloc_size was checked as > well, > in the sense that if it is available, it knows without question what > the > size of the allocation is. If __alloc_size and __counted_by conflict, > the smaller of the two should be the truth. > > But, as I said, if there is some need to explicitly ignore > __alloc_size > when __counted_by is present, I can live with it; we just need to > document it. > > If the RFC and you agree that the __counted_by variable can only ever > be > (re)assigned after the flex array has been (re)allocated, then I > guess > we'll see how it goes. :) I think most places in the kernel using > __counted_by will be fine, but I suspect we may have cases where we > need > to update it like in the loop I described above. If that's true, we > can > revisit the requirement then. :) It should be the other way round: You should first set 'count' and then reassign the pointer, because you can then often check the pointer assignment (reading 'count'). The other way round this works only sometimes, i.e. if both assignments are close together and the optimizer can see this. Martin
More thoughts on the following example Kees provided: > On Jul 17, 2023, at 7:40 PM, Kees Cook <keescook@chromium.org> wrote: >> >> The counted_by attribute is used to annotate a Flexible array member on how many elements it will have. >> However, if this information can not accurately reflect the real number of elements for the array allocated, >> What’s the purpose of such information? > > For example, imagine code that allocates space for 100 elements since > the common case is that the number of elements will grow over time. > Elements are added as it goes. For example: > > struct grows { > int alloc_count; > int valid_count; > struct element item[] __counted_by(valid_count); > } *p; > > void something(void) > { > p = malloc(sizeof(*p) + sizeof(*p->item) * 100); > p->alloc_count = 100; > p->valid_count = 0; > > /* this loop doesn't check that we don't go over 100. */ > while (items_to_copy) { > struct element *item_ptr = get_next_item(); > /* __counted_by stays in sync: */ > p->valid_count++; > p->item[p->valid_count - 1] = *item_ptr; > } > } > > We would want to catch cases there p->item[] is accessed with an index > that is >= p->valid_count, even though the allocation is (currently) > larger. > > However, if we ever reached valid_count >= alloc_count, we need to trap > too, since we can still "see" the true allocation size. > > Now, the __alloc_size hint is visible in very few places, so if there is > a strong reason to do so, I can live with saying that __counted_by takes > full precedence over __alloc_size. It seems it should be possible to > compare when both are present, but I can live with __counted_by being > the universal truth. :) In the above use case (not sure how popular such user case is?), the major questions are: for one object with flexible array member, 1. Shall we allow the situation when the allocated size for the object and the number of element for the contained FAM are mismatched? If the answer to 1 is YES (to support such user cases), then 2. If there is a mismatch between these two, should the number of element impact the allocated size for the object? (__builtin_object_size()) From the doc of object size checking: (https://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html) ===== Built-in Function: size_t __builtin_object_size (const void * ptr, int type) is a built-in construct that returns a constant number of bytes from ptr to the end of the object ptr pointer points to (if known at compile time). To determine the sizes of dynamically allocated objects the function relies on the allocation functions called to obtain the storage to be declared with the alloc_size attribute (see Common Function Attributes). __builtin_object_size never evaluates its arguments for side effects. If there are any side effects in them, it returns (size_t) -1 for type 0 or 1 and (size_t) 0 for type 2 or 3. If there are multiple objects ptr can point to and all of them are known at compile time, the returned number is the maximum of remaining byte counts in those objects if type & 2 is 0 and minimum if nonzero. If it is not possible to determine which objects ptr points to at compile time, __builtin_object_size should return (size_t) -1 for type 0 or 1 and (size_t) 0 for type 2 or 3. ===== Based on the current documentation for __bos, I think that the answer should be NO, i.e, we should not use the counted_by info to change the REAL allocated size for the object. 3. Then, As pointed out also by Martin, only the bounds check (including -Warray-bounds or -fsanitizer=bounds) should be impacted by the counted_by information, since these checks are based on the TYPE system, and “counted_by” info should be treated as a complement to the TYPE system. Let me know your opinions. Qing
>> >> The point is: allocation size should synced with the value of “counted_by”. LLVM’s RFC also have the similar requirement: >> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > Right, I'm saying it would be nice if __alloc_size was checked as well, > in the sense that if it is available, it knows without question what the > size of the allocation is. If __alloc_size and __counted_by conflict, > the smaller of the two should be the truth. I don’t think that “if __alloc_size and __counted_by conflict, the smaller of the two should be the truth” will work correctly. When __alloc_size is larger than the value of __counted_by, it’s okay. But when the value of __counted_by is larger than the __alloc_size, the array bound check or object size sanitizer might not work correctly. Please see the following example: struct grows { int alloc_count; int valid_count; int item[] __counted_by(valid_count); } *p; void __attribute__((__noinline__)) something (int n) { p = malloc(sizeof(*p) + sizeof(*p->item) * 100); p->alloc_count = 100; p->valid_count = 102; p->item[n] = 10; // both _alloc_size and the value of __counted_by are available in this routine, the smaller one is , 100; } void __attribute__((__noinline__)) something_2 (int n) { p->item[n] = 10; // only the value of __counted_by is available in this routine, which is 102; } Int main { Something (101); Something_2 (101); } For the above example, the out-of-bound array access in routine “something” should be able to be caught by the compiler. However, the out-of-bound array access in the routine “something_2” will NOT be able to be caught by the compiler. Since in the routine “something_2” , the compiler don’t know the alloc_size, the only available info is the counted_by value through the attribute. But this value is bigger than the REAL size of the array. Therefore the compiler cannot detect the out-of-bound array access in the routine something_2 Based on the above observation, I think we should add the following requirement: The value of “counted_by” should be equal or SMALLER than the real alloc_size for the flexible array member. This is the same requirement as the LLVM RFC. https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 "the compiler inserts additional checks to ensure the new buf has at least as many elements as the new count indicates.” LLVM has additional requirement in addition to this, we might need to consider those requirement too. Qing > But, as I said, if there is some need to explicitly ignore __alloc_size > when __counted_by is present, I can live with it; we just need to > document it. > > If the RFC and you agree that the __counted_by variable can only ever be > (re)assigned after the flex array has been (re)allocated, then I guess > we'll see how it goes. :) I think most places in the kernel using > __counted_by will be fine, but I suspect we may have cases where we need > to update it like in the loop I described above. If that's true, we can > revisit the requirement then. :) > > -Kees > > -- > Kees Cook
Hi, After some detailed study and consideration on how to use the new attribute “counted_by” in __builtin_dynamic_object_size, I came up with the following example with detailed explanation on the expected behavior from GCC on using this new attribute. Please take a look on this example and the explanation embedded, and let me know if you have further Comments or suggestions. Thanks a lot. Qing =========================================== #include <stdint.h> #include <malloc.h> #include <string.h> #include <stdio.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); \ } \ } while (0); #define noinline __attribute__((__noinline__)) #define SIZE_BUMP 2 /* 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 (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 MAXIMUM sub-object size: chose the smaller of A and B. * Please see https://gcc.gnu.org/pipermail/gcc-patches/2023-July/625891.html * for details on why. */ expect(__builtin_dynamic_object_size(p->array, 1), (p->foo) * sizeof(int)); expect(__builtin_dynamic_object_size(p->array, 0), sizeof (*p) + (p->foo) * sizeof(int)); /* for MINIMUM sub-object size: chose the smaller of A and B too. */ expect(__builtin_dynamic_object_size(p->array, 3), p->foo * sizeof(int)); expect(__builtin_dynamic_object_size(p->array, 2), sizeof (*p) + 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) + (p->foo + SIZE_BUMP) * sizeof(int)); expect(__builtin_dynamic_object_size(p, 0), sizeof (*p) + (p->foo + SIZE_BUMP) * sizeof(int)); expect(__builtin_dynamic_object_size(p, 3), sizeof (*p) + (p->foo + SIZE_BUMP) * sizeof(int)); expect(__builtin_dynamic_object_size(p, 2), sizeof (*p) + (p->foo + SIZE_BUMP) * sizeof(int)); return p; } int main () { struct annotated *p; p = alloc_buf (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. */ /*For MAXIMUM size, We know the SIZE info of the TYPE from the access to the sub-object p->array. but don't know the whole object the pointer p points to. */ expect(__builtin_dynamic_object_size(p->array, 1), p->foo * sizeof(int)); expect(__builtin_dynamic_object_size(p->array, 0), -1); /*for MINIMUM size, We know the TYPE_SIZE from the access to the sub-oject p->array. but don't know the whole object the pointer p points to. */ 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); return 0; } > On Jul 19, 2023, at 2:52 PM, Qing Zhao via Gcc-patches <gcc-patches@gcc.gnu.org> wrote: > > >>> >>> The point is: allocation size should synced with the value of “counted_by”. LLVM’s RFC also have the similar requirement: >>> https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 >> >> Right, I'm saying it would be nice if __alloc_size was checked as well, >> in the sense that if it is available, it knows without question what the >> size of the allocation is. If __alloc_size and __counted_by conflict, >> the smaller of the two should be the truth. > > I don’t think that “if __alloc_size and __counted_by conflict, the smaller of the two should be the truth” will work correctly. > > When __alloc_size is larger than the value of __counted_by, it’s okay. > But when the value of __counted_by is larger than the __alloc_size, the array bound check or object size sanitizer might not work correctly. > > > Please see the following example: > > struct grows { > int alloc_count; > int valid_count; > int item[] __counted_by(valid_count); > } *p; > > void __attribute__((__noinline__)) something (int n) > { > p = malloc(sizeof(*p) + sizeof(*p->item) * 100); > p->alloc_count = 100; > p->valid_count = 102; > p->item[n] = 10; // both _alloc_size and the value of __counted_by are available in this routine, the smaller one is , 100; > > } > > void __attribute__((__noinline__)) something_2 (int n) > { > p->item[n] = 10; // only the value of __counted_by is available in this routine, which is 102; > } > > Int main > { > Something (101); > Something_2 (101); > } > > > For the above example, the out-of-bound array access in routine “something” should be able to be caught by the compiler. > However, the out-of-bound array access in the routine “something_2” will NOT be able to be caught by the compiler. > > Since in the routine “something_2” , the compiler don’t know the alloc_size, the only available info is the counted_by value > through the attribute. But this value is bigger than the REAL size of the array. Therefore the compiler cannot detect the > out-of-bound array access in the routine something_2 > > > Based on the above observation, I think we should add the following requirement: > > The value of “counted_by” should be equal or SMALLER than the real alloc_size for the flexible array member. > > This is the same requirement as the LLVM RFC. > https://discourse.llvm.org/t/rfc-enforcing-bounds-safety-in-c-fbounds-safety/70854#maintaining-correctness-of-bounds-annotations-18 > > "the compiler inserts additional checks to ensure the new buf has at least as many elements as the new count indicates.” > LLVM has additional requirement in addition to this, we might need to consider those requirement too. > > Qing > >> But, as I said, if there is some need to explicitly ignore __alloc_size >> when __counted_by is present, I can live with it; we just need to >> document it. >> >> If the RFC and you agree that the __counted_by variable can only ever be >> (re)assigned after the flex array has been (re)allocated, then I guess >> we'll see how it goes. :) I think most places in the kernel using >> __counted_by will be fine, but I suspect we may have cases where we need >> to update it like in the loop I described above. If that's true, we can >> revisit the requirement then. :) >> >> -Kees >> >> -- >> Kees Cook >
On Mon, Jul 31, 2023 at 08:14:42PM +0000, Qing Zhao wrote: > /* 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. */ This is a great explanation; thank you! In the future I might want to have a new builtin that will allow a program to query a pointer when neither A nor B have happened. But for the first version of the __counted_by infrastructure, the above limitations seen fine. For example, maybe __builtin_counted_size(p) (which returns sizeof(*p) + sizeof(*p->flex_array_member) * p->counted_by_member). Though since there might be multiple flex array members, maybe this can't work. :) -Kees
Am Dienstag, dem 01.08.2023 um 15:45 -0700 schrieb Kees Cook: > On Mon, Jul 31, 2023 at 08:14:42PM +0000, Qing Zhao wrote: > > /* 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. */ > > This is a great explanation; thank you! > > In the future I might want to have a new builtin that will allow > a program to query a pointer when neither A nor B have happened. But > for the first version of the __counted_by infrastructure, the above > limitations seen fine. > > For example, maybe __builtin_counted_size(p) (which returns sizeof(*p) + > sizeof(*p->flex_array_member) * p->counted_by_member). Though since > there might be multiple flex array members, maybe this can't work. :) We had a _Lengthof proposal for arrays (instead of sizeof/sizeof) and thought about how to extend this to structs with FAM. The problem is that it can not rely on an attribute. With GCC's VLA in structs you could do struct foo { int n; char buf[n_init]; } *p = malloc(sizeof *p); p->n_init = n; and get sizeof and bounds checking with UBSan https://godbolt.org/z/d4nneqs3P (but also compiler bugs and other issues) Also see my experimental container library, where you can do: vec_decl(int); vec(int)* v = vec_alloc(int); vec_push(&v, 1); vec_push(&v, 3); auto p = &vec_array(v); (*p)[1] = 1; // bounds check Here, "vec_array()" would give you a regular C array view of the vector contant and with correct dynamic size, so you can apply "sizeof" and have bounds checking with UBSan and it just works (with clang / GCC without changes). https://github.com/uecker/noplate Martin
> On Aug 2, 2023, at 2:25 AM, Martin Uecker <uecker@tugraz.at> wrote: > > Am Dienstag, dem 01.08.2023 um 15:45 -0700 schrieb Kees Cook: >> On Mon, Jul 31, 2023 at 08:14:42PM +0000, Qing Zhao wrote: >>> /* 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. */ >> >> This is a great explanation; thank you! >> >> In the future I might want to have a new builtin that will allow >> a program to query a pointer when neither A nor B have happened. But >> for the first version of the __counted_by infrastructure, the above >> limitations seen fine. >> >> For example, maybe __builtin_counted_size(p) (which returns sizeof(*p) + >> sizeof(*p->flex_array_member) * p->counted_by_member). Though since >> there might be multiple flex array members, maybe this can't work. :) > > We had a _Lengthof proposal for arrays (instead of sizeof/sizeof) > and thought about how to extend this to structs with FAM. The > problem is that it can not rely on an attribute. > > With GCC's VLA in structs you could do > > struct foo { int n; char buf[n_init]; } *p = malloc(sizeof *p); > p->n_init = n; > > and get sizeof and bounds checking with UBSan > https://godbolt.org/z/d4nneqs3P > > (but also compiler bugs and other issues) This works great! If later the bounds information for the FAM can be integrated into TYPE system just like the VLA, That will be ideal, then we don’t need to hack the compiler here and there to handle the FMA specially. > > > Also see my experimental container library, where you can do: > > vec_decl(int); > vec(int)* v = vec_alloc(int); > > vec_push(&v, 1); > vec_push(&v, 3); > > auto p = &vec_array(v); > (*p)[1] = 1; // bounds check > > Here, "vec_array()" would give you a regular C array view > of the vector contant and with correct dynamic size, so you > can apply "sizeof" and have bounds checking with UBSan and > it just works (with clang / GCC without changes). > https://github.com/uecker/noplate Yes, the idea of providing a type-safe library for C also looks promising. thanks Qing > > > > Martin
> On Aug 1, 2023, at 6:45 PM, Kees Cook <keescook@chromium.org> wrote: > > On Mon, Jul 31, 2023 at 08:14:42PM +0000, Qing Zhao wrote: >> /* 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. */ > > This is a great explanation; thank you! > > In the future I might want to have a new builtin that will allow > a program to query a pointer when neither A nor B have happened. But > for the first version of the __counted_by infrastructure, the above > limitations seen fine. > > For example, maybe __builtin_counted_size(p) (which returns sizeof(*p) + > sizeof(*p->flex_array_member) * p->counted_by_member). Though since > there might be multiple flex array members, maybe this can't work. :) What do you mean by “there might be multiple flex array members”? Do you mean the following example: struct annotated { size_t foo; int array[] __attribute__((counted_by (foo))); }; static struct annotated * noinline alloc_buf (int index) { struct annotated *p; p = malloc(sizeof (*p) + (index) * sizeof (int)); p->foo = index; return p; } Int main () { struct annotated *p1, *p2; p1 = alloc_buf (10); p2 = alloc_buf (20); __builtin_counted_size(p1)??? __builtin_counted_size(p2)??? } Or something else? Qing > > -Kees > > -- > Kees Cook