From patchwork Fri Mar 16 17:33:11 2018 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Joseph Myers X-Patchwork-Id: 26341 Received: (qmail 121991 invoked by alias); 16 Mar 2018 17:33:18 -0000 Mailing-List: contact libc-alpha-help@sourceware.org; run by ezmlm Precedence: bulk List-Id: List-Unsubscribe: List-Subscribe: List-Archive: List-Post: List-Help: , Sender: libc-alpha-owner@sourceware.org Delivered-To: mailing list libc-alpha@sourceware.org Received: (qmail 121976 invoked by uid 89); 16 Mar 2018 17:33:17 -0000 Authentication-Results: sourceware.org; auth=none X-Virus-Found: No X-Spam-SWARE-Status: No, score=-24.5 required=5.0 tests=AWL, BAYES_00, GIT_PATCH_0, GIT_PATCH_1, GIT_PATCH_2, GIT_PATCH_3, RCVD_IN_DNSWL_NONE, SPF_PASS, URIBL_RED autolearn=ham version=3.3.2 spammy= X-HELO: relay1.mentorg.com Date: Fri, 16 Mar 2018 17:33:11 +0000 From: Joseph Myers To: Subject: Fix signed integer overflow in random_r (bug 17343) Message-ID: User-Agent: Alpine 2.20 (DEB 67 2015-01-07) MIME-Version: 1.0 X-ClientProxiedBy: svr-ies-mbx-02.mgc.mentorg.com (139.181.222.2) To svr-ies-mbx-01.mgc.mentorg.com (139.181.222.1) Bug 17343 reports that stdlib/random_r.c has code with undefined behavior because of signed integer overflow on int32_t. This patch changes the code so that the possibly overflowing computations use unsigned arithmetic instead. Note that the bug report refers to "Most code" in that file. The places changed in this patch are the only ones I found where I think such overflow can occur. Tested for x86_64 and x86. 2018-03-16 Joseph Myers [BZ #17343] * stdlib/random_r.c (__random_r): Use unsigned arithmetic for possibly overflowing computations. diff --git a/stdlib/random_r.c b/stdlib/random_r.c index 4d2f0d4..996f624 100644 --- a/stdlib/random_r.c +++ b/stdlib/random_r.c @@ -362,7 +362,7 @@ __random_r (struct random_data *buf, int32_t *result) if (buf->rand_type == TYPE_0) { int32_t val = state[0]; - val = ((state[0] * 1103515245) + 12345) & 0x7fffffff; + val = ((state[0] * 1103515245U) + 12345U) & 0x7fffffff; state[0] = val; *result = val; } @@ -371,9 +371,9 @@ __random_r (struct random_data *buf, int32_t *result) int32_t *fptr = buf->fptr; int32_t *rptr = buf->rptr; int32_t *end_ptr = buf->end_ptr; - int32_t val; + uint32_t val; - val = *fptr += *rptr; + val = *fptr += (uint32_t) *rptr; /* Chucking least random bit. */ *result = (val >> 1) & 0x7fffffff; ++fptr;