Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/nio/cs/FindEncoderBugs.java
38839 views
/*1* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 6233345 6381699 6381702 6381705 638170626* @summary Encode many char sequences in many ways27* @run main/timeout=1200 FindEncoderBugs28* @author Martin Buchholz29* @key randomness30*/3132import java.util.*;33import java.util.regex.*;34import java.nio.*;35import java.nio.charset.*;3637public class FindEncoderBugs {3839static boolean isBroken(String csn) {40if (csn.equals("x-COMPOUND_TEXT")) return true;41return false;42}4344static <T extends Comparable<? super T>> List<T> sort(Collection<T> c) {45List<T> list = new ArrayList<T>(c);46Collections.sort(list);47return list;48}4950static class TooManyFailures extends RuntimeException {51private static final long serialVersionUID = 0L;52}5354static String string(byte[] a) {55final StringBuilder sb = new StringBuilder();56for (byte b : a) {57if (sb.length() != 0) sb.append(' ');58sb.append(String.format("%02x", b & 0xff));59}60return sb.toString();61}6263static String string(char[] a) {64final StringBuilder sb = new StringBuilder();65for (char c : a) {66if (sb.length() != 0) sb.append(' ');67sb.append(String.format("\\u%04x", (int) c));68}69return sb.toString();70}7172static class Reporter {73// Some machinery to make sure only a small number of errors74// that are "too similar" are reported.75static class Counts extends HashMap<String, Long> {76private static final long serialVersionUID = -1;77long inc(String signature) {78Long count = get(signature);79if (count == null) count = 0L;80put(signature, count+1);81return count+1;82}83}8485final Counts failureCounts = new Counts();86final static long maxFailures = 2;8788final static Pattern hideBytes = Pattern.compile("\"[0-9a-f ]+\"");89final static Pattern hideChars = Pattern.compile("\\\\u[0-9a-f]{4}");9091boolean bug(String format, Object... args) {92String signature = String.format(format, args);93// signature = hideBytes.matcher(signature).replaceAll("\"??\"");94// signature = hideChars.matcher(signature).replaceAll("\\u????");95failed++;96if (failureCounts.inc(signature) <= maxFailures) {97System.out.printf(format, args);98System.out.println();99return true;100}101return false;102}103104void summarize() {105for (String key : sort(failureCounts.keySet()))106System.out.printf("-----%n%s%nfailures=%d%n",107key, failureCounts.get(key));108}109}110111static final Reporter reporter = new Reporter();112113static class Result {114final int limit;115final int ipos;116final boolean direct;117final char[] ia;118final byte[] oa;119final CoderResult cr;120121private static byte[] toByteArray(ByteBuffer bb) {122byte[] bytes = new byte[bb.position()];123for (int i = 0; i < bytes.length; i++)124bytes[i] = bb.get(i);125return bytes;126}127128Result(CharBuffer ib, ByteBuffer ob, CoderResult cr) {129ipos = ib.position();130ia = toArray(ib);131oa = toArray(ob);132direct = ib.isDirect();133limit = ob.limit();134this.cr = cr;135}136137static char[] toArray(CharBuffer b) {138int pos = b.position();139char[] a = new char[b.limit()];140b.position(0);141b.get(a);142b.position(pos);143return a;144}145146static byte[] toArray(ByteBuffer b) {147byte[] a = new byte[b.position()];148b.position(0);149b.get(a);150return a;151}152153static boolean eq(Result x, Result y) {154return x == y ||155(x != null && y != null &&156(Arrays.equals(x.oa, y.oa) &&157x.ipos == y.ipos &&158x.cr == y.cr));159}160161public String toString() {162return String.format("\"%s\"[%d/%d] => %s \"%s\"[%d/%d]%s",163string(ia), ipos, ia.length,164cr, string(oa), oa.length, limit,165(direct ? " (direct)" : ""));166}167}168169static class CharsetTester {170private final Charset cs;171private final boolean hasBom;172private static final int maxFailures = 5;173private int failures = 0;174// private static final long maxCharsetFailures = Long.MAX_VALUE;175private static final long maxCharsetFailures = 10000L;176private final long failed0 = failed;177178// legend: r=regular d=direct In=Input Ou=Output179static final int maxBufSize = 20;180static final CharBuffer[] rInBuffers = new CharBuffer[maxBufSize];181static final CharBuffer[] dInBuffers = new CharBuffer[maxBufSize];182183static final ByteBuffer[] rOuBuffers = new ByteBuffer[maxBufSize];184static final ByteBuffer[] dOuBuffers = new ByteBuffer[maxBufSize];185static {186for (int i = 0; i < maxBufSize; i++) {187rInBuffers[i] = CharBuffer.allocate(i);188dInBuffers[i] = ByteBuffer.allocateDirect(i*2).asCharBuffer();189rOuBuffers[i] = ByteBuffer.allocate(i);190dOuBuffers[i] = ByteBuffer.allocateDirect(i);191}192}193194CharsetTester(Charset cs) {195this.cs = cs;196this.hasBom =197cs.name().matches(".*BOM.*") ||198cs.name().equals("UTF-16");199}200201static boolean bug(String format, Object... args) {202return reporter.bug(format, args);203}204205static boolean hasBom(byte[] a) {206switch (a.length) {207case 2: case 4:208int sum = 0;209for (byte x : a)210sum += x;211return sum == (byte) 0xfe + (byte) 0xff;212default: return false;213}214}215216void testSurrogates() {217int failures = 0;218for (int i = 0; i < 10; i++) {219Result r = test(new char[] { randomHighSurrogate() });220if (r == null) break;221if (! (r.cr.isUnderflow() &&222r.ipos == 0))223bug("Lone high surrogate not UNDERFLOW: %s %s",224cs, r);225}226for (int i = 0; i < 10; i++) {227Result r = test(new char[] { randomLowSurrogate() });228if (r == null) break;229if (! (r.cr.isMalformed() && r.cr.length() == 1))230bug("Lone low surrogate not MALFORMED[1]: %s %s",231cs, r);232}233char[] chars = new char[2];234for (int i = 0; i < 10; i++) {235chars[0] = randomLowSurrogate(); // Always illegal236chars[1] = randomChar();237Result r = test(chars);238if (r == null) break;239if (! (r.cr.isMalformed() &&240r.cr.length() == 1 &&241(r.ipos == 0 || (hasBom && hasBom(r.oa))))) {242if (failures++ > 5) return;243bug("Unpaired low surrogate not MALFORMED[1]: %s %s",244cs, r);245}246}247for (int i = 0; i < 10; i++) {248chars[0] = randomHighSurrogate();249do {250chars[1] = randomChar();251} while (Character.isLowSurrogate(chars[1]));252Result r = test(chars);253if (r == null) break;254if (! (r.cr.isMalformed() &&255r.cr.length() == 1 &&256(r.ipos == 0 || (hasBom && hasBom(r.oa))))) {257if (failures++ > 5) return;258bug("Unpaired high surrogate not MALFORMED[1]: %s %s",259cs, r);260}261}262for (int i = 0; i < 1000; i++) {263chars[0] = randomHighSurrogate();264chars[1] = randomLowSurrogate();265Result r = test(chars);266if (r == null) break;267if (! ((r.cr.isUnmappable() &&268r.cr.length() == 2 &&269r.oa.length == 0)270||271(r.cr.isUnderflow() &&272r.oa.length > 0 &&273r.ipos == 2))) {274if (failures++ > 5) return;275bug("Legal supplementary character bug: %s %s",276cs, r);277}278}279}280281// if (! (r.cr.isMalformed() &&282// r.cr.length() == 1 &&283// (rob.position() == 0 || hasBom(rob)))) {284// if (failures++ > 5) return;285// bug("Unpaired surrogate not malformed: %s %s",286// cs, r);287// }288// }289290// dib.clear(); dib.put(chars); dib.flip();291// rib.position(0);292// rob.clear(); rob.limit(lim);293// for (CharBuffer ib : new CharBuffer[] { rib, dib }) {294// Result r = recode(ib, rob);295// if (! (r.cr.isMalformed() &&296// r.cr.length() == 1 &&297// (rob.position() == 0 || hasBom(rob)))) {298// if (failures++ > 5) return;299// bug("Unpaired surrogate not malformed: %s %s",300// cs, r);301// }302// }303// //}304// for (int i = 0; i < 10000; i++) {305// chars[0] = randomHighSurrogate();306// chars[1] = randomLowSurrogate();307// dib.clear(); dib.put(chars); dib.flip();308// rib.position(0);309// rob.clear(); rob.limit(lim);310// for (CharBuffer ib : new CharBuffer[] { rib, dib }) {311// Result r = recode(ib, rob);312// if (! ((r.cr.isUnmappable() &&313// r.cr.length() == 2 &&314// rob.position() == 0)315// ||316// (r.cr.isUnderflow() &&317// rob.position() > 0 &&318// ib.position() == 2))) {319// if (failures++ > 5) return;320// bug("Legal supplementary character bug: %s %s",321// cs, r);322// }323// }324// }325// }326// }327328Result recode(CharBuffer ib, ByteBuffer ob) {329try {330byte canary = 22;331ib.clear(); // Prepare to read332ob.clear(); // Prepare to write333for (int i = 0; i < ob.limit(); i++)334ob.put(i, canary);335CharsetEncoder coder = cs.newEncoder();336CoderResult cr = coder.encode(ib, ob, false);337equal(ib.limit(), ib.capacity());338equal(ob.limit(), ob.capacity());339Result r = new Result(ib, ob, cr);340if (cr.isError())341check(cr.length() > 0);342if (cr.isOverflow() && ob.remaining() > 10)343bug("OVERFLOW, but there's lots of room: %s %s",344cs, r);345// if (cr.isOverflow() && ib.remaining() == 0 && ! hasBom)346// bug("OVERFLOW, yet remaining() == 0: %s %s",347// cs, r);348if (cr.isError() && ib.remaining() < cr.length())349bug("remaining() < CoderResult.length(): %s %s",350cs, r);351// if (ib.position() == 0352// && ob.position() > 0353// && ! hasBom(r.oa))354// bug("output only if input consumed: %s %s",355// cs, r);356CoderResult cr2 = coder.encode(ib, ob, false);357if (ib.position() != r.ipos ||358ob.position() != r.oa.length ||359cr != cr2)360bug("Coding operation not idempotent: %s%n %s%n %s",361cs, r, new Result(ib, ob, cr2));362if (ob.position() < ob.limit() &&363ob.get(ob.position()) != canary)364bug("Buffer overrun: %s %s %s",365cs, r, ob.get(ob.position()));366return r;367} catch (Throwable t) {368if (bug("Unexpected exception: %s %s %s",369cs, t.getClass().getSimpleName(),370new Result(ib, ob, null)))371t.printStackTrace();372return null;373}374}375376Result recode2(char[] ia, int n) {377int len = ia.length;378CharBuffer rib = CharBuffer.wrap(ia);379CharBuffer dib = dInBuffers[len];380dib.clear(); dib.put(ia); dib.clear();381ByteBuffer rob = rOuBuffers[n];382ByteBuffer dob = dOuBuffers[n];383equal(rob.limit(), n);384equal(dob.limit(), n);385check(dib.isDirect());386check(dob.isDirect());387Result r1 = recode(rib, rob);388Result r2 = recode(dib, dob);389if (r1 != null && r2 != null && ! Result.eq(r1, r2))390bug("Results differ for direct buffers: %s%n %s%n %s",391cs, r1, r2);392return r1;393}394395Result test(char[] ia) {396if (failed - failed0 >= maxCharsetFailures)397throw new TooManyFailures();398399Result roomy = recode2(ia, maxBufSize - 1);400if (roomy == null) return roomy;401int olen = roomy.oa.length;402if (olen > 0) {403if (roomy.ipos == roomy.ia.length) {404Result perfectFit = recode2(ia, olen);405if (! Result.eq(roomy, perfectFit))406bug("Results differ: %s%n %s%n %s",407cs, roomy, perfectFit);408}409for (int i = 0; i < olen; i++) {410Result claustrophobic = recode2(ia, i);411if (claustrophobic == null) return roomy;412if (roomy.cr.isUnderflow() &&413! claustrophobic.cr.isOverflow())414bug("Expected OVERFLOW: %s%n %s%n %s",415cs, roomy, claustrophobic);416}417}418return roomy;419}420421void testExhaustively(char[] prefix, int n) {422int len = prefix.length;423char[] ia = Arrays.copyOf(prefix, len + 1);424for (int i = 0; i < 0x10000; i++) {425ia[len] = (char) i;426if (n == 1)427test(ia);428else429testExhaustively(ia, n - 1);430}431}432433void testRandomly(char[] prefix, int n) {434int len = prefix.length;435char[] ia = Arrays.copyOf(prefix, len + n);436for (int i = 0; i < 10000; i++) {437for (int j = 0; j < n; j++)438ia[len + j] = randomChar();439test(ia);440}441}442443void testPrefix(char[] prefix) {444if (prefix.length > 0)445System.out.printf("Testing prefix %s%n", string(prefix));446447test(prefix);448449testExhaustively(prefix, 1);450// Can you spare a year of CPU time?451//testExhaustively(prefix, 2);452453testRandomly(prefix, 2);454testRandomly(prefix, 3);455}456}457458private final static Random rnd = new Random();459private static char randomChar() {460return (char) rnd.nextInt(Character.MAX_VALUE);461}462private static char randomHighSurrogate() {463return (char) (Character.MIN_HIGH_SURROGATE + rnd.nextInt(1024));464}465private static char randomLowSurrogate() {466return (char) (Character.MIN_LOW_SURROGATE + rnd.nextInt(1024));467}468469private static void testCharset(Charset cs) throws Throwable {470if (! cs.canEncode())471return;472473final String csn = cs.name();474475if (isBroken(csn)) {476System.out.printf("Skipping possibly broken charset %s%n", csn);477return;478}479System.out.println(csn);480481CharsetTester tester = new CharsetTester(cs);482483tester.testSurrogates();484485tester.testPrefix(new char[] {});486487if (csn.equals("x-ISCII91")) {488System.out.println("More ISCII testing...");489new CharsetTester(cs).testPrefix(new char[]{'\u094d'}); // Halant490new CharsetTester(cs).testPrefix(new char[]{'\u093c'}); // Nukta491}492}493494private static void realMain(String[] args) {495for (Charset cs : sort(Charset.availableCharsets().values())) {496try {497testCharset(cs);498} catch (TooManyFailures e) {499System.out.printf("Too many failures for %s%n", cs);500} catch (Throwable t) {501unexpected(t);502}503}504reporter.summarize();505}506507//--------------------- Infrastructure ---------------------------508static volatile long passed = 0, failed = 0;509static void pass() {passed++;}510static void fail() {failed++; Thread.dumpStack();}511static void fail(String format, Object... args) {512System.out.println(String.format(format, args)); failed++;}513static void fail(String msg) {System.out.println(msg); fail();}514static void unexpected(Throwable t) {failed++; t.printStackTrace();}515static void check(boolean cond) {if (cond) pass(); else fail();}516static void equal(Object x, Object y) {517if (x == null ? y == null : x.equals(y)) pass();518else fail(x + " not equal to " + y);}519public static void main(String[] args) throws Throwable {520try {realMain(args);} catch (Throwable t) {unexpected(t);}521System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);522if (failed > 0) throw new AssertionError("Some tests failed");}523}524525526