From b967ae4aaec57079e486ec0a67b6c5ef20cb54d1 Mon Sep 17 00:00:00 2001 From: Project Nayuki Date: Sun, 7 Oct 2018 07:00:35 +0000 Subject: [PATCH] Added and updated some strict overflow checks. --- src/io/nayuki/fastqrcodegen/BitBuffer.java | 6 ++++-- src/io/nayuki/fastqrcodegen/QrSegment.java | 4 +++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/io/nayuki/fastqrcodegen/BitBuffer.java b/src/io/nayuki/fastqrcodegen/BitBuffer.java index 7031914..4a2faf1 100644 --- a/src/io/nayuki/fastqrcodegen/BitBuffer.java +++ b/src/io/nayuki/fastqrcodegen/BitBuffer.java @@ -92,7 +92,7 @@ final class BitBuffer { public void appendBits(int val, int len) { if (len < 0 || len > 31 || val >>> len != 0) throw new IllegalArgumentException("Value out of range"); - if (Integer.MAX_VALUE - bitLength < len) + if (len > Integer.MAX_VALUE - bitLength) throw new IllegalStateException("Maximum length reached"); if (bitLength + len + 1 > data.length << 5) @@ -118,12 +118,14 @@ final class BitBuffer { Objects.requireNonNull(vals); if (len == 0) return; - if (len < 0 || len > vals.length * 32) + if (len < 0 || len > vals.length * 32L) throw new IllegalArgumentException("Value out of range"); int wholeWords = len / 32; int tailBits = len % 32; if (tailBits > 0 && vals[wholeWords] << tailBits != 0) throw new IllegalArgumentException("Last word must have low bits clear"); + if (len > Integer.MAX_VALUE - bitLength) + throw new IllegalStateException("Maximum length reached"); while (bitLength + len > data.length * 32) data = Arrays.copyOf(data, data.length * 2); diff --git a/src/io/nayuki/fastqrcodegen/QrSegment.java b/src/io/nayuki/fastqrcodegen/QrSegment.java index cf0d655..bf7d5ef 100644 --- a/src/io/nayuki/fastqrcodegen/QrSegment.java +++ b/src/io/nayuki/fastqrcodegen/QrSegment.java @@ -57,6 +57,8 @@ public final class QrSegment { */ public static QrSegment makeBytes(byte[] data) { Objects.requireNonNull(data); + if (data.length * 8L > Integer.MAX_VALUE) + throw new IllegalArgumentException("Data too long"); int[] bits = new int[(data.length + 3) / 4]; for (int i = 0; i < data.length; i++) bits[i >>> 2] |= (data[i] & 0xFF) << (~i << 3); @@ -243,7 +245,7 @@ public final class QrSegment { public QrSegment(Mode md, int numCh, int[] data, int bitLen) { mode = Objects.requireNonNull(md); this.data = Objects.requireNonNull(data); - if (numCh < 0 || bitLen < 0 || bitLen > data.length * 32) + if (numCh < 0 || bitLen < 0 || bitLen > data.length * 32L) throw new IllegalArgumentException("Invalid value"); numChars = numCh; bitLength = bitLen;