Path: blob/master/test/hotspot/jtreg/compiler/intrinsics/base64/TestBase64.java
41153 views
/*1* Copyright (c) 2018, 2021, 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* @author Eric Wang <[email protected]>26* @summary tests java.util.Base6427* @library /test/lib /28* @build sun.hotspot.WhiteBox29* @run driver jdk.test.lib.helpers.ClassFileInstaller sun.hotspot.WhiteBox30*31* @run main/othervm/timeout=600 -Xbatch -DcheckOutput=true32* -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -Xbootclasspath/a:.33* compiler.intrinsics.base64.TestBase6434*/3536package compiler.intrinsics.base64;3738import java.io.BufferedReader;39import java.io.FileReader;40import java.nio.ByteBuffer;41import java.nio.charset.Charset;42import java.nio.charset.StandardCharsets;43import java.nio.file.Files;44import java.nio.file.Paths;45import java.util.Base64;46import java.util.Base64.Decoder;47import java.util.Base64.Encoder;48import java.util.Objects;49import java.util.Random;5051import compiler.whitebox.CompilerWhiteBoxTest;52import sun.hotspot.code.Compiler;53import jtreg.SkippedException;54import jdk.test.lib.Utils;5556public class TestBase64 {57static boolean checkOutput = Boolean.getBoolean("checkOutput");5859public static void main(String[] args) throws Exception {60if (!Compiler.isIntrinsicAvailable(CompilerWhiteBoxTest.COMP_LEVEL_FULL_OPTIMIZATION, "java.util.Base64$Encoder", "encodeBlock", byte[].class, int.class, int.class, byte[].class, int.class, boolean.class)) {61throw new SkippedException("Base64 intrinsic is not available");62}63int iters = (args.length > 0 ? Integer.valueOf(args[0]) : 5_000);64System.out.println(iters + " iterations");6566initNonBase64Arrays();6768warmup();6970test0(FileType.ASCII, Base64Type.BASIC, Base64.getEncoder(), Base64.getDecoder(),"plain.txt", "baseEncode.txt", iters);71test0(FileType.ASCII, Base64Type.URLSAFE, Base64.getUrlEncoder(), Base64.getUrlDecoder(),"plain.txt", "urlEncode.txt", iters);72test0(FileType.ASCII, Base64Type.MIME, Base64.getMimeEncoder(), Base64.getMimeDecoder(),"plain.txt", "mimeEncode.txt", iters);7374test0(FileType.HEXASCII, Base64Type.BASIC, Base64.getEncoder(), Base64.getDecoder(),"longLineHEX.txt", "longLineBaseEncode.txt", iters);75test0(FileType.HEXASCII, Base64Type.URLSAFE, Base64.getUrlEncoder(), Base64.getUrlDecoder(),"longLineHEX.txt", "longLineUrlEncode.txt", iters);76test0(FileType.HEXASCII, Base64Type.MIME, Base64.getMimeEncoder(), Base64.getMimeDecoder(),"longLineHEX.txt", "longLineMimeEncode.txt", iters);77}7879private static void warmup() {80final int warmupCount = 20_000;81final int bufSize = 60;82byte[] srcBuf = new byte[bufSize];83byte[] encBuf = new byte[(bufSize / 3) * 4];84byte[] decBuf = new byte[bufSize];8586ran.nextBytes(srcBuf);8788// This should be enough to get both encode and decode compiled on89// the highest tier.90for (int i = 0; i < warmupCount; i++) {91Base64.getEncoder().encode(srcBuf, encBuf);92Base64.getDecoder().decode(encBuf, decBuf);93}94}9596public static void test0(FileType inputFileType, Base64Type type, Encoder encoder, Decoder decoder, String srcFile, String encodedFile, int numIterations) throws Exception {9798String[] srcLns = Files.readAllLines(Paths.get(SRCDIR, srcFile), DEF_CHARSET)99.toArray(new String[0]);100String[] encodedLns = Files.readAllLines(Paths.get(SRCDIR, encodedFile), DEF_CHARSET)101.toArray(new String[0]);102103for (int i = 0; i < numIterations; i++) {104int lns = 0;105for (String srcStr : srcLns) {106String encodedStr = null;107if (type != Base64Type.MIME) {108encodedStr = encodedLns[lns++];109} else {110while (lns < encodedLns.length) {111String s = encodedLns[lns++];112if (s.length() == 0)113break;114if (encodedStr != null) {115encodedStr += DEFAULT_CRLF + s;116} else {117encodedStr = s;118}119}120if (encodedStr == null && srcStr.length() == 0) {121encodedStr = "";122}123}124125byte[] srcArr;126switch (inputFileType) {127case ASCII:128srcArr = srcStr.getBytes(DEF_CHARSET);129break;130case HEXASCII:131srcArr = Utils.toByteArray(srcStr);132break;133default:134throw new IllegalStateException();135}136137byte[] encodedArr = encodedStr.getBytes(DEF_CHARSET);138139ByteBuffer srcBuf = ByteBuffer.wrap(srcArr);140ByteBuffer encodedBuf = ByteBuffer.wrap(encodedArr);141byte[] resArr = new byte[encodedArr.length];142143// test int encode(byte[], byte[])144int len = encoder.encode(srcArr, resArr);145assertEqual(len, encodedArr.length);146assertEqual(resArr, encodedArr);147148// test byte[] encode(byte[])149resArr = encoder.encode(srcArr);150assertEqual(resArr, encodedArr);151152// test ByteBuffer encode(ByteBuffer)153int limit = srcBuf.limit();154ByteBuffer resBuf = encoder.encode(srcBuf);155assertEqual(srcBuf.position(), limit);156assertEqual(srcBuf.limit(), limit);157assertEqual(resBuf, encodedBuf);158srcBuf.rewind(); // reset for next test159160// test String encodeToString(byte[])161String resEncodeStr = encoder.encodeToString(srcArr);162assertEqual(resEncodeStr, encodedStr);163164// test int decode(byte[], byte[])165resArr = new byte[srcArr.length];166len = decoder.decode(encodedArr, resArr);167assertEqual(len, srcArr.length);168assertEqual(resArr, srcArr);169170// test byte[] decode(byte[])171resArr = decoder.decode(encodedArr);172assertEqual(resArr, srcArr);173174// test that an illegal Base64 character is detected175if ((type != Base64Type.MIME) && (encodedArr.length > 0)) {176int bytePosToCorrupt = ran.nextInt(encodedArr.length);177byte orig = encodedArr[bytePosToCorrupt];178encodedArr[bytePosToCorrupt] = getBadBase64Char(type);179boolean caught = false;180try {181// resArr is already allocated182len = decoder.decode(encodedArr, resArr);183} catch (IllegalArgumentException e) {184caught = true;185}186if (!caught) {187throw new RuntimeException(String.format("Decoder did not catch an illegal base64 character: 0x%02x at position: %d in encoded buffer of length %d",188encodedArr[bytePosToCorrupt], bytePosToCorrupt, encodedArr.length));189}190encodedArr[bytePosToCorrupt] = orig;191}192193// test ByteBuffer decode(ByteBuffer)194limit = encodedBuf.limit();195resBuf = decoder.decode(encodedBuf);196assertEqual(encodedBuf.position(), limit);197assertEqual(encodedBuf.limit(), limit);198assertEqual(resBuf, srcBuf);199encodedBuf.rewind(); // reset for next test200201// test byte[] decode(String)202resArr = decoder.decode(encodedStr);203assertEqual(resArr, srcArr);204205}206}207}208209// Data type in the input file210enum FileType {211ASCII, HEXASCII212}213214// helper215enum Base64Type {216BASIC, URLSAFE, MIME217}218219private static final String SRCDIR = System.getProperty("test.src", "compiler/intrinsics/base64/");220private static final Charset DEF_CHARSET = StandardCharsets.US_ASCII;221private static final String DEF_EXCEPTION_MSG =222"Assertion failed! The result is not same as expected\n";223private static final String DEFAULT_CRLF = "\r\n";224private static final Random ran = new Random(1000); // Constant seed for repeatability225226private static void assertEqual(Object result, Object expect) {227if (checkOutput) {228if (!Objects.deepEquals(result, expect)) {229String resultStr = result.toString();230String expectStr = expect.toString();231if (result instanceof byte[]) {232resultStr = new String((byte[]) result, DEF_CHARSET);233}234if (expect instanceof byte[]) {235expectStr = new String((byte[]) expect, DEF_CHARSET);236}237throw new RuntimeException(DEF_EXCEPTION_MSG +238" result: " + resultStr + " expected: " + expectStr);239}240}241}242243// This array will contain all possible 8-bit values *except* those244// that are legal Base64 characters: A-Z a-z 0-9 + / =245private static final byte[] nonBase64 = new byte[256 - 65];246247// This array will contain all possible 8-bit values *except* those248// that are legal URL-safe Base64 characters: A-Z a-z 0-9 - _ =249private static final byte[] nonBase64URL = new byte[256 - 65];250251private static final byte[] legalBase64 = new byte[] {252'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',253'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',254'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',255'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',256'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',257'+', '/', '=' };258259private static final byte[] legalBase64URL = new byte[] {260'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',261'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',262'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',263'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',264'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',265'-', '_', '=' };266267private static final boolean contains(byte[] ary, byte b) {268for (int i = 0; i < ary.length; i++) {269if (ary[i] == b) {270return true;271}272}273return false;274}275276private static final void initNonBase64Arrays() {277int i0 = 0, i1 = 0;278for (int val = 0; val < 256; val++) {279if (! contains(legalBase64, (byte)val)) {280nonBase64[i0++] = (byte)val;281}282if (! contains(legalBase64URL, (byte)val)) {283nonBase64URL[i1++] = (byte)val;284}285}286}287288private static final byte getBadBase64Char(Base64Type b64Type) {289int ch = ran.nextInt(256 - 65); // 64 base64 characters, and one for the '=' padding character290switch (b64Type) {291case MIME:292case BASIC:293return nonBase64[ch];294case URLSAFE:295return nonBase64URL[ch];296default:297throw new InternalError("Internal test error: getBadBase64Char called with unknown Base64Type value");298}299}300}301302303