From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from cventin.lip.ens-lyon.fr (cventin.lip.ens-lyon.fr [140.77.13.17]) by sourceware.org (Postfix) with ESMTPS id 2560A3858C2C for ; Mon, 20 Mar 2023 13:36:26 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 2560A3858C2C Authentication-Results: sourceware.org; dmarc=none (p=none dis=none) header.from=vinc17.net Authentication-Results: sourceware.org; spf=none smtp.mailfrom=vinc17.net Received: from vlefevre by cventin.lip.ens-lyon.fr with local (Exim 4.96) (envelope-from ) id 1peFgW-001B8c-2O; Mon, 20 Mar 2023 14:36:24 +0100 Date: Mon, 20 Mar 2023 14:36:24 +0100 From: Vincent Lefevre To: libc-alpha@sourceware.org Subject: Re: UB status of snprintf on invalid ptr+size combination? Message-ID: <20230320133624.GA203866@cventin.lip.ens-lyon.fr> Mail-Followup-To: Vincent Lefevre , libc-alpha@sourceware.org References: <9d7ca3d8-6998-e741-b669-03ef42bc99f1@gmail.com> <20230319230722.GD390223@zira.vinc17.org> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: 8bit In-Reply-To: X-Mailer-Info: https://www.vinc17.net/mutt/ User-Agent: Mutt/2.2.9+71 (caea3018) vl-149028 (2023-03-14) X-Spam-Status: No, score=-3.3 required=5.0 tests=BAYES_00,KAM_DMARC_STATUS,KAM_LAZY_DOMAIN_SECURITY,SPF_HELO_NONE,SPF_NONE,TXREP autolearn=no autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org List-Id: On 2023-03-20 13:17:11 +0100, Alejandro Colomar wrote: > On 3/20/23 13:05, Siddhesh Poyarekar wrote: > > On 2023-03-19 19:07, Vincent Lefevre wrote: > >> The function may not know the buffer size if `checked` is true, > >> so that it uses a known bound. Thanks to common code factorized, > >> this is more readable than > >> > >> if (checked) > >> sprintf (buf, "%s", s); > >> else > >> snprintf(buf, n, "%s", s); > >> > >> in particular in the cases where the format string is complex. > > That pattern looks like _FORTIFY_SOURCE, doesn't it? If so, the correct > action would be to call sprintf(3) and rely on the compiler to do the > checks. Not necessarily. Here, this is the programmer who would do the check, though he may add code (e.g. assertions) on the caller side to give enough information to the compiler so that a smart compiler could prove that the call is valid. But this may need an analysis across different compilation units. If the compiler cannot check, the validity relies on the proof of the code; but not that in any case, the code needs to be proved: for instance, snprintf() may yield data loss and potential security issues if string truncation is not expected (or if the string is truncation too early). -- Vincent Lefèvre - Web: 100% accessible validated (X)HTML - Blog: Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)