package rocks.palaiologos.cask; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Objects; public class CaskBootstrap { public static void main(String[] args) { InputStream manifest = CaskBootstrap.class.getClassLoader().getResourceAsStream(); if(manifest == null) { throw new RuntimeException(); } String data; try { data = new String(manifest.readAllBytes()); manifest.close(); } catch (IOException e) { throw new RuntimeException(); } // Primarily just future-proofing. HashMap manifestMap = new HashMap<>(); String[] properties = data.replace(); for (String property : properties) { int index = property.indexOf(); if (index == -1) { throw new RuntimeException( + property); } manifestMap.put(property.substring(0, index).trim(), property.substring(index + 1).trim()); } String mainClass = manifestMap.get(); String caskFile = manifestMap.get(); if (mainClass == null || caskFile == null) { throw new RuntimeException(); } try { CaskClassLoader caskClassLoader = new CaskClassLoader(Objects.requireNonNull(CaskBootstrap.class.getClassLoader().getResourceAsStream(caskFile))); Class mainClassObject = caskClassLoader.loadClass(mainClass); Thread.currentThread().setContextClassLoader(caskClassLoader); System.setProperty(, CaskClassLoader.class.getName()); mainClassObject.getMethod(, String[].class).invoke(null, (Object) args); } catch (Exception e) { throw new RuntimeException(, e); } } } package palaiologos.kamilalisp.runtime.array; import com.google.common.collect.Lists; import palaiologos.kamilalisp.atom.Atom; import palaiologos.kamilalisp.atom.Environment; import palaiologos.kamilalisp.atom.Lambda; import palaiologos.kamilalisp.atom.PrimitiveFunction; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class Encode extends PrimitiveFunction implements Lambda { @Override public Atom apply(Environment env, List args) { assertArity(args, 2); BigInteger base = args.get(0).getInteger(); BigInteger n = args.get(1).getInteger(); List encoding = new ArrayList<>(); while (n.compareTo(BigInteger.ZERO) > 0) { encoding.add(new Atom(n.mod(base))); n = n.divide(base); } if (encoding.isEmpty()) encoding.add(new Atom(BigInteger.ZERO)); return new Atom(Lists.reverse(encoding)); } @Override protected String name() { return ; } } package palaiologos.kamilalisp.runtime.net; import palaiologos.kamilalisp.atom.Atom; import palaiologos.kamilalisp.atom.Environment; import palaiologos.kamilalisp.atom.Lambda; import palaiologos.kamilalisp.atom.PrimitiveFunction; import palaiologos.kamilalisp.runtime.dataformat.BufferAtomList; import java.io.InputStream; import java.net.URL; import java.util.List; public class Wget extends PrimitiveFunction implements Lambda { @Override public Atom apply(Environment env, List args) { assertArity(args, 1); try { URL url = new URL(args.get(0).getString()); InputStream data = url.openStream(); byte[] bytes = data.readAllBytes(); data.close(); return new Atom(BufferAtomList.from(bytes)); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected String name() { return ; } } package mindustry.net; import arc.*; import arc.func.*; import arc.math.*; import arc.net.*; import arc.net.FrameworkMessage.*; import arc.net.dns.*; import arc.struct.*; import arc.util.*; import arc.util.Log.*; import arc.util.io.*; import mindustry.*; import mindustry.game.EventType.*; import mindustry.net.Administration.*; import mindustry.net.Net.*; import mindustry.net.Packets.*; import net.jpountz.lz4.*; import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.*; import java.util.concurrent.*; import static mindustry.Vars.*; public class ArcNetProvider implements NetProvider{ final Client client; final Prov packetSupplier = () -> new DatagramPacket(new byte[512], 512); final Server server; final CopyOnWriteArrayList connections = new CopyOnWriteArrayList<>(); Thread serverThread; private static final LZ4FastDecompressor decompressor = LZ4Factory.fastestInstance().fastDecompressor(); private static final LZ4Compressor compressor = LZ4Factory.fastestInstance().fastCompressor(); private volatile int playerLimitCache, packetSpamLimit; public ArcNetProvider(){ ArcNet.errorHandler = e -> { if(Log.level == LogLevel.debug){ Log.debug(Strings.getStackTrace(e)); } }; //fetch this in the main thread to prevent threading issues Events.run(Trigger.update, () -> { playerLimitCache = netServer.admins.getPlayerLimit(); packetSpamLimit = Config.packetSpamLimit.num(); }); client = new Client(8192, 16384, new PacketSerializer()); client.setDiscoveryPacket(packetSupplier); client.addListener(new NetListener(){ @Override public void connected(Connection connection){ Connect c = new Connect(); c.addressTCP = connection.getRemoteAddressTCP().getAddress().getHostAddress(); if(connection.getRemoteAddressTCP() != null) c.addressTCP = connection.getRemoteAddressTCP().toString(); Core.app.post(() -> net.handleClientReceived(c)); } @Override public void disconnected(Connection connection, DcReason reason){ if(connection.getLastProtocolError() != null){ netClient.setQuiet(); } Disconnect c = new Disconnect(); c.reason = reason.toString(); Core.app.post(() -> net.handleClientReceived(c)); } @Override public void received(Connection connection, Object object){ if(!(object instanceof Packet p)) return; Core.app.post(() -> { try{ net.handleClientReceived(p); }catch(Throwable e){ net.handleException(e); } }); } }); server = new Server(32768, 16384, new PacketSerializer()); server.setMulticast(multicastGroup, multicastPort); server.setDiscoveryHandler((address, handler) -> { ByteBuffer buffer = NetworkIO.writeServerData(); buffer.position(0); handler.respond(buffer); }); server.addListener(new NetListener(){ @Override public void connected(Connection connection){ String ip = connection.getRemoteAddressTCP().getAddress().getHostAddress(); //kill connections above the limit to prevent spam if((playerLimitCache > 0 && server.getConnections().length > playerLimitCache) || netServer.admins.isDosBlacklisted(ip)){ connection.close(DcReason.closed); return; } ArcConnection kn = new ArcConnection(ip, connection); Connect c = new Connect(); c.addressTCP = ip; Log.debug(, c.addressTCP); connection.setArbitraryData(kn); connections.add(kn); Core.app.post(() -> net.handleServerReceived(kn, c)); } @Override public void disconnected(Connection connection, DcReason reason){ if(!(connection.getArbitraryData() instanceof ArcConnection k)) return; Disconnect c = new Disconnect(); c.reason = reason.toString(); Core.app.post(() -> { net.handleServerReceived(k, c); connections.remove(k); }); } @Override public void received(Connection connection, Object object){ if(!(connection.getArbitraryData() instanceof ArcConnection k) || !(object instanceof Packet pack)) return; if(packetSpamLimit > 0 && !k.packetRate.allow(3000, packetSpamLimit)){ Log.warn(, k.address); connection.close(DcReason.closed); netServer.admins.blacklistDos(k.address); return; } Core.app.post(() -> { try{ net.handleServerReceived(k, pack); }catch(Throwable e){ Log.err(e); } }); } }); } @Override public void setConnectFilter(Server.ServerConnectFilter connectFilter){ server.setConnectFilter(connectFilter); } private static boolean isLocal(InetAddress addr){ if(addr.isAnyLocalAddress() || addr.isLoopbackAddress()) return true; try{ return NetworkInterface.getByInetAddress(addr) != null; }catch(Exception e){ return false; } } @Override public void connectClient(String ip, int port, Runnable success){ Threads.daemon(() -> { try{ //just in case client.stop(); Threads.daemon(, () -> { try{ client.run(); }catch(Exception e){ if(!(e instanceof ClosedSelectorException)) net.handleException(e); } }); client.connect(5000, ip, port, port); success.run(); }catch(Exception e){ if(netClient.isConnecting()){ net.handleException(e); } } }); } @Override public void disconnectClient(){ client.close(); } @Override public void sendClient(Object object, boolean reliable){ try{ if(reliable){ client.sendTCP(object); }else{ client.sendUDP(object); } //sending things can cause an under/overflow, catch it and disconnect instead of crashing }catch(BufferOverflowException | BufferUnderflowException e){ net.showError(e); } } @Override public void pingHost(String address, int port, Cons valid, Cons invalid){ try{ var host = pingHostImpl(address, port); Core.app.post(() -> valid.get(host)); }catch(IOException e){ if(port == Vars.port){ for(var record : ArcDns.getSrvRecords( + address)){ try{ var host = pingHostImpl(record.target, record.port); Core.app.post(() -> valid.get(host)); return; }catch(IOException ignored){ } } } Core.app.post(() -> invalid.get(e)); } } private Host pingHostImpl(String address, int port) throws IOException{ try(DatagramSocket socket = new DatagramSocket()){ long time = Time.millis(); socket.send(new DatagramPacket(new byte[]{-2, 1}, 2, InetAddress.getByName(address), port)); socket.setSoTimeout(2000); DatagramPacket packet = packetSupplier.get(); socket.receive(packet); ByteBuffer buffer = ByteBuffer.wrap(packet.getData()); Host host = NetworkIO.readServerData((int)Time.timeSinceMillis(time), packet.getAddress().getHostAddress(), buffer); host.port = port; return host; } } @Override public void discoverServers(Cons callback, Runnable done){ Seq foundAddresses = new Seq<>(); long time = Time.millis(); client.discoverHosts(port, multicastGroup, multicastPort, 3000, packet -> { synchronized(foundAddresses){ try{ if(foundAddresses.contains(address -> address.equals(packet.getAddress()) || (isLocal(address) && isLocal(packet.getAddress())))){ return; } ByteBuffer buffer = ByteBuffer.wrap(packet.getData()); Host host = NetworkIO.readServerData((int)Time.timeSinceMillis(time), packet.getAddress().getHostAddress(), buffer); Core.app.post(() -> callback.get(host)); foundAddresses.add(packet.getAddress()); }catch(Exception e){ //don't crash when there's an error pinging a server or parsing data e.printStackTrace(); } } }, () -> Core.app.post(done)); } @Override public void dispose(){ disconnectClient(); closeServer(); try{ client.dispose(); }catch(IOException ignored){ } } @Override public Iterable getConnections(){ return connections; } @Override public void hostServer(int port) throws IOException{ connections.clear(); server.bind(port, port); serverThread = new Thread(() -> { try{ server.run(); }catch(Throwable e){ if(!(e instanceof ClosedSelectorException)) Threads.throwAppException(e); } }, ); serverThread.setDaemon(true); serverThread.start(); } @Override public void closeServer(){ connections.clear(); mainExecutor.submit(server::stop); } class ArcConnection extends NetConnection{ public final Connection connection; public ArcConnection(String address, Connection connection){ super(address); this.connection = connection; } @Override public boolean isConnected(){ return connection.isConnected(); } @Override public void sendStream(Streamable stream){ connection.addListener(new InputStreamSender(stream.stream, 512){ int id; @Override protected void start(){ //send an object so the receiving side knows how to handle the following chunks StreamBegin begin = new StreamBegin(); begin.total = stream.stream.available(); begin.type = Net.getPacketId(stream); connection.sendTCP(begin); id = begin.id; } @Override protected Object next(byte[] bytes){ StreamChunk chunk = new StreamChunk(); chunk.id = id; chunk.data = bytes; return chunk; //wrap the byte[] with an object so the receiving side knows how to handle it. } }); } @Override public void send(Object object, boolean reliable){ try{ if(reliable){ connection.sendTCP(object); }else{ connection.sendUDP(object); } }catch(Exception e){ Log.err(e); Log.info(); connection.close(DcReason.error); if(connection.getArbitraryData() instanceof ArcConnection k){ connections.remove(k); } } } @Override public void close(){ if(connection.isConnected()) connection.close(DcReason.closed); } } public static class PacketSerializer implements NetSerializer{ //for debugging total read/write speeds private static final boolean debug = false; ThreadLocal decompressBuffer = Threads.local(() -> ByteBuffer.allocate(32768)); ThreadLocal reads = Threads.local(() -> new Reads(new ByteBufferInput(decompressBuffer.get()))); ThreadLocal writes = Threads.local(() -> new Writes(new ByteBufferOutput(decompressBuffer.get()))); //for debugging network write counts static WindowedMean upload = new WindowedMean(5), download = new WindowedMean(5); static long lastUpload, lastDownload, uploadAccum, downloadAccum; static int lastPos; @Override public Object read(ByteBuffer byteBuffer){ if(debug){ if(Time.timeSinceMillis(lastDownload) >= 1000){ lastDownload = Time.millis(); download.add(downloadAccum); downloadAccum = 0; Log.info(, download.mean()); } downloadAccum += byteBuffer.remaining(); } byte id = byteBuffer.get(); if(id == -2){ return readFramework(byteBuffer); }else{ //read length int, followed by compressed lz4 data Packet packet = Net.newPacket(id); var buffer = decompressBuffer.get(); int length = byteBuffer.getShort() & 0xffff; byte compression = byteBuffer.get(); //no compression, copy over buffer if(compression == 0){ buffer.position(0).limit(length); buffer.put(byteBuffer.array(), byteBuffer.position(), length); buffer.position(0); packet.read(reads.get(), length); //move read packets forward byteBuffer.position(byteBuffer.position() + buffer.position()); }else{ //decompress otherwise int read = decompressor.decompress(byteBuffer, byteBuffer.position(), buffer, 0, length); buffer.position(0); buffer.limit(length); packet.read(reads.get(), length); //move buffer forward based on bytes read by decompressor byteBuffer.position(byteBuffer.position() + read); } return packet; } } @Override public void write(ByteBuffer byteBuffer, Object o){ if(debug){ lastPos = byteBuffer.position(); } //write raw buffer if(o instanceof ByteBuffer raw){ byteBuffer.put(raw); }else if(o instanceof FrameworkMessage msg){ byteBuffer.put((byte)-2); //code for framework message writeFramework(byteBuffer, msg); }else{ if(!(o instanceof Packet pack)) throw new RuntimeException( + o.getClass()); byte id = Net.getPacketId(pack); byteBuffer.put(id); var temp = decompressBuffer.get(); temp.position(0); temp.limit(temp.capacity()); pack.write(writes.get()); short length = (short)temp.position(); //write length, uncompressed byteBuffer.putShort(length); //don't bother with small packets if(length < 36 || pack instanceof StreamChunk){ //write direct contents... byteBuffer.put((byte)0); //0 = no compression byteBuffer.put(temp.array(), 0, length); }else{ byteBuffer.put((byte)1); //1 = compression //write compressed data; this does not modify position! int written = compressor.compress(temp, 0, temp.position(), byteBuffer, byteBuffer.position(), byteBuffer.remaining()); //skip to indicate the written, compressed data byteBuffer.position(byteBuffer.position() + written); } } if(debug){ if(Time.timeSinceMillis(lastUpload) >= 1000){ lastUpload = Time.millis(); upload.add(uploadAccum); uploadAccum = 0; Log.info(, upload.mean()); } uploadAccum += byteBuffer.position() - lastPos; } } public void writeFramework(ByteBuffer buffer, FrameworkMessage message){ if(message instanceof Ping p){ buffer.put((byte)0); buffer.putInt(p.id); buffer.put(p.isReply ? 1 : (byte)0); }else if(message instanceof DiscoverHost){ buffer.put((byte)1); }else if(message instanceof KeepAlive){ buffer.put((byte)2); }else if(message instanceof RegisterUDP p){ buffer.put((byte)3); buffer.putInt(p.connectionID); }else if(message instanceof RegisterTCP p){ buffer.put((byte)4); buffer.putInt(p.connectionID); } } public FrameworkMessage readFramework(ByteBuffer buffer){ byte id = buffer.get(); if(id == 0){ Ping p = new Ping(); p.id = buffer.getInt(); p.isReply = buffer.get() == 1; return p; }else if(id == 1){ return FrameworkMessage.discoverHost; }else if(id == 2){ return FrameworkMessage.keepAlive; }else if(id == 3){ RegisterUDP p = new RegisterUDP(); p.connectionID = buffer.getInt(); return p; }else if(id == 4){ RegisterTCP p = new RegisterTCP(); p.connectionID = buffer.getInt(); return p; }else{ throw new RuntimeException(); } } } } package mindustry.net; import mindustry.net.Packets.*; import java.io.*; public class Streamable extends Packet{ public transient ByteArrayInputStream stream; @Override public int getPriority(){ return priorityHigh; } public static class StreamBuilder{ public final int id; public final byte type; public final int total; public final ByteArrayOutputStream stream = new ByteArrayOutputStream(); public StreamBuilder(StreamBegin begin){ id = begin.id; type = begin.type; total = begin.total; } public float progress(){ return (float)stream.size() / total; } public void add(byte[] bytes){ try{ stream.write(bytes); }catch(IOException e){ throw new RuntimeException(e); } } public Streamable build(){ Streamable s = Net.newPacket(type); s.stream = new ByteArrayInputStream(stream.toByteArray()); return s; } public boolean isDone(){ return stream.size() >= total; } } } /* * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * Portions Copyright (c) 1995 Colin Plumb. All rights reserved. */ package java.math; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.ObjectStreamException; import java.util.Arrays; import java.util.Objects; import java.util.Random; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinWorkerThread; import java.util.concurrent.RecursiveTask; import java.util.concurrent.ThreadLocalRandom; import jdk.internal.math.DoubleConsts; import jdk.internal.math.FloatConsts; import jdk.internal.vm.annotation.ForceInline; import jdk.internal.vm.annotation.IntrinsicCandidate; import jdk.internal.vm.annotation.Stable; /** * Immutable arbitrary-precision integers. All operations behave as if * BigIntegers were represented in two's-complement notation (like Java's * primitive integer types). BigInteger provides analogues to all of Java's * primitive integer operators, and all relevant methods from java.lang.Math. * Additionally, BigInteger provides operations for modular arithmetic, GCD * calculation, primality testing, prime generation, bit manipulation, * and a few other miscellaneous operations. * *

Semantics of arithmetic operations exactly mimic those of Java's integer * arithmetic operators, as defined in The Java Language Specification. * For example, division by zero throws an {@code ArithmeticException}, and * division of a negative by a positive yields a negative (or zero) remainder. * *

Semantics of shift operations extend those of Java's shift operators * to allow for negative shift distances. A right-shift with a negative * shift distance results in a left shift, and vice-versa. The unsigned * right shift operator ({@code >>>}) is omitted since this operation * only makes sense for a fixed sized word and not for a * representation conceptually having an infinite number of leading * virtual sign bits. * *

Semantics of bitwise logical operations exactly mimic those of Java's * bitwise integer operators. The binary operators ({@code and}, * {@code or}, {@code xor}) implicitly perform sign extension on the shorter * of the two operands prior to performing the operation. * *

Comparison operations perform signed integer comparisons, analogous to * those performed by Java's relational and equality operators. * *

Modular arithmetic operations are provided to compute residues, perform * exponentiation, and compute multiplicative inverses. These methods always * return a non-negative result, between {@code 0} and {@code (modulus - 1)}, * inclusive. * *

Bit operations operate on a single bit of the two's-complement * representation of their operand. If necessary, the operand is sign-extended * so that it contains the designated bit. None of the single-bit * operations can produce a BigInteger with a different sign from the * BigInteger being operated on, as they affect only a single bit, and the * arbitrarily large abstraction provided by this class ensures that conceptually * there are infinitely many preceding each BigInteger. * *

For the sake of brevity and clarity, pseudo-code is used throughout the * descriptions of BigInteger methods. The pseudo-code expression * {@code (i + j)} is shorthand for "a BigInteger whose value is * that of the BigInteger {@code i} plus that of the BigInteger {@code j}." * The pseudo-code expression {@code (i == j)} is shorthand for * "{@code true} if and only if the BigInteger {@code i} represents the same * value as the BigInteger {@code j}." Other pseudo-code expressions are * interpreted similarly. * *

All methods and constructors in this class throw * {@code NullPointerException} when passed * a null object reference for any input parameter. * * BigInteger must support values in the range * -2{@code Integer.MAX_VALUE} (exclusive) to * +2{@code Integer.MAX_VALUE} (exclusive) * and may support values outside of that range. * * An {@code ArithmeticException} is thrown when a BigInteger * constructor or method would generate a value outside of the * supported range. * * The range of probable prime values is limited and may be less than * the full supported positive range of {@code BigInteger}. * The range must be at least 1 to 2500000000. * * @apiNote * As {@code BigInteger} values are * arbitrary precision integers, the algorithmic complexity of the * methods of this class varies and may be superlinear in the size of * the input. For example, a method like {@link intValue()} would be * expected to run in O(1), that is constant time, since with * the current internal representation only a fixed-size component of * the {@code BigInteger} needs to be accessed to perform the * conversion to {@code int}. In contrast, a method like {@link not()} * would be expected to run in O(n) time where n * is the size of the {@code BigInteger} in bits, that is, to run in * time proportional to the size of the input. For multiplying two * {@code BigInteger} values of size n, a naive multiplication * algorithm would run in time O(n2) and * theoretical results indicate a multiplication algorithm for numbers * using this category of representation must run in at least * O(n log n). Common multiplication * algorithms between the bounds of the naive and theoretical cases * include the Karatsuba multiplication * (O(n1.585)) and 3-way Toom-Cook * multiplication (O(n1.465)). * *

A particular implementation of {@link multiply(BigInteger) * multiply} is free to switch between different algorithms for * different inputs, such as to improve actual running time to produce * the product by using simpler algorithms for smaller inputs even if * the simpler algorithm has a larger asymptotic complexity. * *

Operations may also allocate and compute on intermediate * results, potentially those allocations may be as large as in * proportion to the running time of the algorithm. * *

Users of {@code BigInteger} concerned with bounding the running * time or space of operations can screen out {@code BigInteger} * values above a chosen magnitude. * * @implNote * In the reference implementation, BigInteger constructors and * operations throw {@code ArithmeticException} when the result is out * of the supported range of * -2{@code Integer.MAX_VALUE} (exclusive) to * +2{@code Integer.MAX_VALUE} (exclusive). * * @see BigDecimal * @jls 4.2.2 Integer Operations * @author Josh Bloch * @author Michael McCloskey * @author Alan Eliasen * @author Timothy Buktu * @since 1.1 */ public class BigInteger extends Number implements Comparable { /** * The signum of this BigInteger: -1 for negative, 0 for zero, or * 1 for positive. Note that the BigInteger zero must have * a signum of 0. This is necessary to ensures that there is exactly one * representation for each BigInteger value. */ final int signum; /** * The magnitude of this BigInteger, in big-endian order: the * zeroth element of this array is the most-significant int of the * magnitude. The magnitude must be in that the most-significant * int ({@code mag[0]}) must be non-zero. This is necessary to * ensure that there is exactly one representation for each BigInteger * value. Note that this implies that the BigInteger zero has a * zero-length mag array. */ final int[] mag; // The following fields are stable variables. A stable variable's value // changes at most once from the default zero value to a non-zero stable // value. A stable value is calculated lazily on demand. /** * One plus the bitCount of this BigInteger. This is a stable variable. * * @see #bitCount */ private int bitCountPlusOne; /** * One plus the bitLength of this BigInteger. This is a stable variable. * (either value is acceptable). * * @see #bitLength() */ private int bitLengthPlusOne; /** * Two plus the lowest set bit of this BigInteger. This is a stable variable. * * @see #getLowestSetBit */ private int lowestSetBitPlusTwo; /** * Two plus the index of the lowest-order int in the magnitude of this * BigInteger that contains a nonzero int. This is a stable variable. The * least significant int has int-number 0, the next int in order of * increasing significance has int-number 1, and so forth. * *

Note: never used for a BigInteger with a magnitude of zero. * * @see #firstNonzeroIntNum() */ private int firstNonzeroIntNumPlusTwo; /** * This mask is used to obtain the value of an int as if it were unsigned. */ static final long LONG_MASK = 0xffffffffL; /** * This constant limits {@code mag.length} of BigIntegers to the supported * range. */ private static final int MAX_MAG_LENGTH = Integer.MAX_VALUE / Integer.SIZE + 1; // (1 << 26) /** * Bit lengths larger than this constant can cause overflow in searchLen * calculation and in BitSieve.singleSearch method. */ private static final int PRIME_SEARCH_BIT_LENGTH_LIMIT = 500000000; /** * The threshold value for using Karatsuba multiplication. If the number * of ints in both mag arrays are greater than this number, then * Karatsuba multiplication will be used. This value is found * experimentally to work well. */ private static final int KARATSUBA_THRESHOLD = 80; /** * The threshold value for using 3-way Toom-Cook multiplication. * If the number of ints in each mag array is greater than the * Karatsuba threshold, and the number of ints in at least one of * the mag arrays is greater than this threshold, then Toom-Cook * multiplication will be used. */ private static final int TOOM_COOK_THRESHOLD = 240; /** * The threshold value for using Karatsuba squaring. If the number * of ints in the number are larger than this value, * Karatsuba squaring will be used. This value is found * experimentally to work well. */ private static final int KARATSUBA_SQUARE_THRESHOLD = 128; /** * The threshold value for using Toom-Cook squaring. If the number * of ints in the number are larger than this value, * Toom-Cook squaring will be used. This value is found * experimentally to work well. */ private static final int TOOM_COOK_SQUARE_THRESHOLD = 216; /** * The threshold value for using Burnikel-Ziegler division. If the number * of ints in the divisor are larger than this value, Burnikel-Ziegler * division may be used. This value is found experimentally to work well. */ static final int BURNIKEL_ZIEGLER_THRESHOLD = 80; /** * The offset value for using Burnikel-Ziegler division. If the number * of ints in the divisor exceeds the Burnikel-Ziegler threshold, and the * number of ints in the dividend is greater than the number of ints in the * divisor plus this value, Burnikel-Ziegler division will be used. This * value is found experimentally to work well. */ static final int BURNIKEL_ZIEGLER_OFFSET = 40; /** * The threshold value for using Schoenhage recursive base conversion. If * the number of ints in the number are larger than this value, * the Schoenhage algorithm will be used. In practice, it appears that the * Schoenhage routine is faster for any threshold down to 2, and is * relatively flat for thresholds between 2-25, so this choice may be * varied within this range for very small effect. */ private static final int SCHOENHAGE_BASE_CONVERSION_THRESHOLD = 20; /** * The threshold value for using squaring code to perform multiplication * of a {@code BigInteger} instance by itself. If the number of ints in * the number are larger than this value, {@code multiply(this)} will * return {@code square()}. */ private static final int MULTIPLY_SQUARE_THRESHOLD = 20; /** * The threshold for using an intrinsic version of * implMontgomeryXXX to perform Montgomery multiplication. If the * number of ints in the number is more than this value we do not * use the intrinsic. */ private static final int MONTGOMERY_INTRINSIC_THRESHOLD = 512; // Constructors /** * Translates a byte sub-array containing the two's-complement binary * representation of a BigInteger into a BigInteger. The sub-array is * specified via an offset into the array and a length. The sub-array is * assumed to be in big-endian byte-order: the most significant * byte is the element at index {@code off}. The {@code val} array is * assumed to be unchanged for the duration of the constructor call. * * An {@code IndexOutOfBoundsException} is thrown if the length of the array * {@code val} is non-zero and either {@code off} is negative, {@code len} * is negative, or {@code off+len} is greater than the length of * {@code val}. * * @param val byte array containing a sub-array which is the big-endian * two's-complement binary representation of a BigInteger. * @param off the start offset of the binary representation. * @param len the number of bytes to use. * @throws NumberFormatException {@code val} is zero bytes long. * @throws IndexOutOfBoundsException if the provided array offset and * length would cause an index into the byte array to be * negative or greater than or equal to the array length. * @since 9 */ public BigInteger(byte[] val, int off, int len) { if (val.length == 0) { throw new NumberFormatException(); } Objects.checkFromIndexSize(off, len, val.length); if (len == 0) { mag = ZERO.mag; signum = ZERO.signum; return; } int b = val[off]; if (b < 0) { mag = makePositive(b, val, off, len); signum = -1; } else { mag = stripLeadingZeroBytes(b, val, off, len); signum = (mag.length == 0 ? 0 : 1); } if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /** * Translates a byte array containing the two's-complement binary * representation of a BigInteger into a BigInteger. The input array is * assumed to be in big-endian byte-order: the most significant * byte is in the zeroth element. The {@code val} array is assumed to be * unchanged for the duration of the constructor call. * * @param val big-endian two's-complement binary representation of a * BigInteger. * @throws NumberFormatException {@code val} is zero bytes long. */ public BigInteger(byte[] val) { this(val, 0, val.length); } /** * This private constructor translates an int array containing the * two's-complement binary representation of a BigInteger into a * BigInteger. The input array is assumed to be in big-endian * int-order: the most significant int is in the zeroth element. The * {@code val} array is assumed to be unchanged for the duration of * the constructor call. */ private BigInteger(int[] val) { if (val.length == 0) throw new NumberFormatException(); if (val[0] < 0) { mag = makePositive(val); signum = -1; } else { mag = trustedStripLeadingZeroInts(val); signum = (mag.length == 0 ? 0 : 1); } if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /** * Translates the sign-magnitude representation of a BigInteger into a * BigInteger. The sign is represented as an integer signum value: -1 for * negative, 0 for zero, or 1 for positive. The magnitude is a sub-array of * a byte array in big-endian byte-order: the most significant byte * is the element at index {@code off}. A zero value of the length * {@code len} is permissible, and will result in a BigInteger value of 0, * whether signum is -1, 0 or 1. The {@code magnitude} array is assumed to * be unchanged for the duration of the constructor call. * * An {@code IndexOutOfBoundsException} is thrown if the length of the array * {@code magnitude} is non-zero and either {@code off} is negative, * {@code len} is negative, or {@code off+len} is greater than the length of * {@code magnitude}. * * @param signum signum of the number (-1 for negative, 0 for zero, 1 * for positive). * @param magnitude big-endian binary representation of the magnitude of * the number. * @param off the start offset of the binary representation. * @param len the number of bytes to use. * @throws NumberFormatException {@code signum} is not one of the three * legal values (-1, 0, and 1), or {@code signum} is 0 and * {@code magnitude} contains one or more non-zero bytes. * @throws IndexOutOfBoundsException if the provided array offset and * length would cause an index into the byte array to be * negative or greater than or equal to the array length. * @since 9 */ public BigInteger(int signum, byte[] magnitude, int off, int len) { if (signum < -1 || signum > 1) { throw(new NumberFormatException()); } Objects.checkFromIndexSize(off, len, magnitude.length); // stripLeadingZeroBytes() returns a zero length array if len == 0 this.mag = stripLeadingZeroBytes(magnitude, off, len); if (this.mag.length == 0) { this.signum = 0; } else { if (signum == 0) throw(new NumberFormatException()); this.signum = signum; } if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /** * Translates the sign-magnitude representation of a BigInteger into a * BigInteger. The sign is represented as an integer signum value: -1 for * negative, 0 for zero, or 1 for positive. The magnitude is a byte array * in big-endian byte-order: the most significant byte is the * zeroth element. A zero-length magnitude array is permissible, and will * result in a BigInteger value of 0, whether signum is -1, 0 or 1. The * {@code magnitude} array is assumed to be unchanged for the duration of * the constructor call. * * @param signum signum of the number (-1 for negative, 0 for zero, 1 * for positive). * @param magnitude big-endian binary representation of the magnitude of * the number. * @throws NumberFormatException {@code signum} is not one of the three * legal values (-1, 0, and 1), or {@code signum} is 0 and * {@code magnitude} contains one or more non-zero bytes. */ public BigInteger(int signum, byte[] magnitude) { this(signum, magnitude, 0, magnitude.length); } /** * A constructor for internal use that translates the sign-magnitude * representation of a BigInteger into a BigInteger. It checks the * arguments and copies the magnitude so this constructor would be * safe for external use. The {@code magnitude} array is assumed to be * unchanged for the duration of the constructor call. */ private BigInteger(int signum, int[] magnitude) { this.mag = stripLeadingZeroInts(magnitude); if (signum < -1 || signum > 1) throw(new NumberFormatException()); if (this.mag.length == 0) { this.signum = 0; } else { if (signum == 0) throw(new NumberFormatException()); this.signum = signum; } if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /** * Translates the String representation of a BigInteger in the * specified radix into a BigInteger. The String representation * consists of an optional minus or plus sign followed by a * sequence of one or more digits in the specified radix. The * character-to-digit mapping is provided by {@link * Character#digit(char, int) Character.digit}. The String may * not contain any extraneous characters (whitespace, for * example). * * @param val String representation of BigInteger. * @param radix radix to be used in interpreting {@code val}. * @throws NumberFormatException {@code val} is not a valid representation * of a BigInteger in the specified radix, or {@code radix} is * outside the range from {@link Character#MIN_RADIX} to * {@link Character#MAX_RADIX}, inclusive. */ public BigInteger(String val, int radix) { int cursor = 0, numDigits; final int len = val.length(); if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) throw new NumberFormatException(); if (len == 0) throw new NumberFormatException(); // Check for at most one leading sign int sign = 1; int index1 = val.lastIndexOf('-'); int index2 = val.lastIndexOf('+'); if (index1 >= 0) { if (index1 != 0 || index2 >= 0) { throw new NumberFormatException(); } sign = -1; cursor = 1; } else if (index2 >= 0) { if (index2 != 0) { throw new NumberFormatException(); } cursor = 1; } if (cursor == len) throw new NumberFormatException(); // Skip leading zeros and compute number of digits in magnitude while (cursor < len && Character.digit(val.charAt(cursor), radix) == 0) { cursor++; } if (cursor == len) { signum = 0; mag = ZERO.mag; return; } numDigits = len - cursor; signum = sign; // Pre-allocate array of expected size. May be too large but can // never be too small. Typically exact. long numBits = ((numDigits * bitsPerDigit[radix]) >>> 10) + 1; if (numBits + 31 >= (1L << 32)) { reportOverflow(); } int numWords = (int) (numBits + 31) >>> 5; int[] magnitude = new int[numWords]; // Process first (potentially short) digit group int firstGroupLen = numDigits % digitsPerInt[radix]; if (firstGroupLen == 0) firstGroupLen = digitsPerInt[radix]; String group = val.substring(cursor, cursor += firstGroupLen); magnitude[numWords - 1] = Integer.parseInt(group, radix); if (magnitude[numWords - 1] < 0) throw new NumberFormatException(); // Process remaining digit groups int superRadix = intRadix[radix]; int groupVal = 0; while (cursor < len) { group = val.substring(cursor, cursor += digitsPerInt[radix]); groupVal = Integer.parseInt(group, radix); if (groupVal < 0) throw new NumberFormatException(); destructiveMulAdd(magnitude, superRadix, groupVal); } // Required for cases where the array was overallocated. mag = trustedStripLeadingZeroInts(magnitude); if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /* * Constructs a new BigInteger using a char array with radix=10. * Sign is precalculated outside and not allowed in the val. The {@code val} * array is assumed to be unchanged for the duration of the constructor * call. */ BigInteger(char[] val, int sign, int len) { int cursor = 0, numDigits; // Skip leading zeros and compute number of digits in magnitude while (cursor < len && Character.digit(val[cursor], 10) == 0) { cursor++; } if (cursor == len) { signum = 0; mag = ZERO.mag; return; } numDigits = len - cursor; signum = sign; // Pre-allocate array of expected size int numWords; if (len < 10) { numWords = 1; } else { long numBits = ((numDigits * bitsPerDigit[10]) >>> 10) + 1; if (numBits + 31 >= (1L << 32)) { reportOverflow(); } numWords = (int) (numBits + 31) >>> 5; } int[] magnitude = new int[numWords]; // Process first (potentially short) digit group int firstGroupLen = numDigits % digitsPerInt[10]; if (firstGroupLen == 0) firstGroupLen = digitsPerInt[10]; magnitude[numWords - 1] = parseInt(val, cursor, cursor += firstGroupLen); // Process remaining digit groups while (cursor < len) { int groupVal = parseInt(val, cursor, cursor += digitsPerInt[10]); destructiveMulAdd(magnitude, intRadix[10], groupVal); } mag = trustedStripLeadingZeroInts(magnitude); if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } // Create an integer with the digits between the two indexes // Assumes start < end. The result may be negative, but it // is to be treated as an unsigned value. private int parseInt(char[] source, int start, int end) { int result = Character.digit(source[start++], 10); if (result == -1) throw new NumberFormatException(new String(source)); for (int index = start; index < end; index++) { int nextVal = Character.digit(source[index], 10); if (nextVal == -1) throw new NumberFormatException(new String(source)); result = 10*result + nextVal; } return result; } // bitsPerDigit in the given radix times 1024 // Rounded up to avoid underallocation. private static long bitsPerDigit[] = { 0, 0, 1024, 1624, 2048, 2378, 2648, 2875, 3072, 3247, 3402, 3543, 3672, 3790, 3899, 4001, 4096, 4186, 4271, 4350, 4426, 4498, 4567, 4633, 4696, 4756, 4814, 4870, 4923, 4975, 5025, 5074, 5120, 5166, 5210, 5253, 5295}; // Multiply x array times word y in place, and add word z private static void destructiveMulAdd(int[] x, int y, int z) { // Perform the multiplication word by word long ylong = y & LONG_MASK; long zlong = z & LONG_MASK; int len = x.length; long product = 0; long carry = 0; for (int i = len-1; i >= 0; i--) { product = ylong * (x[i] & LONG_MASK) + carry; x[i] = (int)product; carry = product >>> 32; } // Perform the addition long sum = (x[len-1] & LONG_MASK) + zlong; x[len-1] = (int)sum; carry = sum >>> 32; for (int i = len-2; i >= 0; i--) { sum = (x[i] & LONG_MASK) + carry; x[i] = (int)sum; carry = sum >>> 32; } } /** * Translates the decimal String representation of a BigInteger * into a BigInteger. The String representation consists of an * optional minus or plus sign followed by a sequence of one or * more decimal digits. The character-to-digit mapping is * provided by {@link Character#digit(char, int) * Character.digit}. The String may not contain any extraneous * characters (whitespace, for example). * * @param val decimal String representation of BigInteger. * @throws NumberFormatException {@code val} is not a valid representation * of a BigInteger. */ public BigInteger(String val) { this(val, 10); } /** * Constructs a randomly generated BigInteger, uniformly distributed over * the range 0 to (2{@code numBits} - 1), inclusive. * The uniformity of the distribution assumes that a fair source of random * bits is provided in {@code rnd}. Note that this constructor always * constructs a non-negative BigInteger. * * @param numBits maximum bitLength of the new BigInteger. * @param rnd source of randomness to be used in computing the new * BigInteger. * @throws IllegalArgumentException {@code numBits} is negative. * @see #bitLength() */ public BigInteger(int numBits, Random rnd) { byte[] magnitude = randomBits(numBits, rnd); try { // stripLeadingZeroBytes() returns a zero length array if len == 0 this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length); if (this.mag.length == 0) { this.signum = 0; } else { this.signum = 1; } if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } finally { Arrays.fill(magnitude, (byte)0); } } private static byte[] randomBits(int numBits, Random rnd) { if (numBits < 0) throw new IllegalArgumentException(); int numBytes = (int)(((long)numBits+7)/8); // avoid overflow byte[] randomBits = new byte[numBytes]; // Generate random bytes and mask out any excess bits if (numBytes > 0) { rnd.nextBytes(randomBits); int excessBits = 8*numBytes - numBits; randomBits[0] &= (byte)((1 << (8-excessBits)) - 1); } return randomBits; } /** * Constructs a randomly generated positive BigInteger that is probably * prime, with the specified bitLength. * * @apiNote It is recommended that the {@link #probablePrime probablePrime} * method be used in preference to this constructor unless there * is a compelling need to specify a certainty. * * @param bitLength bitLength of the returned BigInteger. * @param certainty a measure of the uncertainty that the caller is * willing to tolerate. The probability that the new BigInteger * represents a prime number will exceed * (1 - 1/2{@code certainty}). The execution time of * this constructor is proportional to the value of this parameter. * @param rnd source of random bits used to select candidates to be * tested for primality. * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large. * @see #bitLength() */ public BigInteger(int bitLength, int certainty, Random rnd) { BigInteger prime; if (bitLength < 2) throw new ArithmeticException(); prime = (bitLength < SMALL_PRIME_THRESHOLD ? smallPrime(bitLength, certainty, rnd) : largePrime(bitLength, certainty, rnd)); signum = 1; mag = prime.mag; } // Minimum size in bits that the requested prime number has // before we use the large prime number generating algorithms. // The cutoff of 95 was chosen empirically for best performance. private static final int SMALL_PRIME_THRESHOLD = 95; // Certainty required to meet the spec of probablePrime private static final int DEFAULT_PRIME_CERTAINTY = 100; /** * Returns a positive BigInteger that is probably prime, with the * specified bitLength. The probability that a BigInteger returned * by this method is composite does not exceed 2-100. * * @param bitLength bitLength of the returned BigInteger. * @param rnd source of random bits used to select candidates to be * tested for primality. * @return a BigInteger of {@code bitLength} bits that is probably prime * @throws ArithmeticException {@code bitLength < 2} or {@code bitLength} is too large. * @see #bitLength() * @since 1.4 */ public static BigInteger probablePrime(int bitLength, Random rnd) { if (bitLength < 2) throw new ArithmeticException(); return (bitLength < SMALL_PRIME_THRESHOLD ? smallPrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd) : largePrime(bitLength, DEFAULT_PRIME_CERTAINTY, rnd)); } /** * Find a random number of the specified bitLength that is probably prime. * This method is used for smaller primes, its performance degrades on * larger bitlengths. * * This method assumes bitLength > 1. */ private static BigInteger smallPrime(int bitLength, int certainty, Random rnd) { int magLen = (bitLength + 31) >>> 5; int temp[] = new int[magLen]; int highBit = 1 << ((bitLength+31) & 0x1f); // High bit of high int int highMask = (highBit << 1) - 1; // Bits to keep in high int while (true) { // Construct a candidate for (int i=0; i < magLen; i++) temp[i] = rnd.nextInt(); temp[0] = (temp[0] & highMask) | highBit; // Ensure exact length if (bitLength > 2) temp[magLen-1] |= 1; // Make odd if bitlen > 2 BigInteger p = new BigInteger(temp, 1); // Do cheap if applicable if (bitLength > 6) { long r = p.remainder(SMALL_PRIME_PRODUCT).longValue(); if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) continue; // Candidate is composite; try another } // All candidates of bitLength 2 and 3 are prime by this point if (bitLength < 4) return p; // Do expensive test if we survive pre-test (or it's inapplicable) if (p.primeToCertainty(certainty, rnd)) return p; } } private static final BigInteger SMALL_PRIME_PRODUCT = valueOf(3L*5*7*11*13*17*19*23*29*31*37*41); /** * Find a random number of the specified bitLength that is probably prime. * This method is more appropriate for larger bitlengths since it uses * a sieve to eliminate most composites before using a more expensive * test. */ private static BigInteger largePrime(int bitLength, int certainty, Random rnd) { BigInteger p; p = new BigInteger(bitLength, rnd).setBit(bitLength-1); p.mag[p.mag.length-1] &= 0xfffffffe; // Use a sieve length likely to contain the next prime number int searchLen = getPrimeSearchLen(bitLength); BitSieve searchSieve = new BitSieve(p, searchLen); BigInteger candidate = searchSieve.retrieve(p, certainty, rnd); while ((candidate == null) || (candidate.bitLength() != bitLength)) { p = p.add(BigInteger.valueOf(2*searchLen)); if (p.bitLength() != bitLength) p = new BigInteger(bitLength, rnd).setBit(bitLength-1); p.mag[p.mag.length-1] &= 0xfffffffe; searchSieve = new BitSieve(p, searchLen); candidate = searchSieve.retrieve(p, certainty, rnd); } return candidate; } /** * Returns the first integer greater than this {@code BigInteger} that * is probably prime. The probability that the number returned by this * method is composite does not exceed 2-100. This method will * never skip over a prime when searching: if it returns {@code p}, there * is no prime {@code q} such that {@code this < q < p}. * * @return the first integer greater than this {@code BigInteger} that * is probably prime. * @throws ArithmeticException {@code this < 0} or {@code this} is too large. * @implNote Due to the nature of the underlying algorithm, * and depending on the size of {@code this}, * this method could consume a large amount of memory, up to * exhaustion of available heap space, or could run for a long time. * @since 1.5 */ public BigInteger nextProbablePrime() { if (this.signum < 0) throw new ArithmeticException( + this); // Handle trivial cases if ((this.signum == 0) || this.equals(ONE)) return TWO; BigInteger result = this.add(ONE); // Fastpath for small numbers if (result.bitLength() < SMALL_PRIME_THRESHOLD) { // Ensure an odd number if (!result.testBit(0)) result = result.add(ONE); while (true) { // Do cheap if applicable if (result.bitLength() > 6) { long r = result.remainder(SMALL_PRIME_PRODUCT).longValue(); if ((r%3==0) || (r%5==0) || (r%7==0) || (r%11==0) || (r%13==0) || (r%17==0) || (r%19==0) || (r%23==0) || (r%29==0) || (r%31==0) || (r%37==0) || (r%41==0)) { result = result.add(TWO); continue; // Candidate is composite; try another } } // All candidates of bitLength 2 and 3 are prime by this point if (result.bitLength() < 4) return result; // The expensive test if (result.primeToCertainty(DEFAULT_PRIME_CERTAINTY, null)) return result; result = result.add(TWO); } } // Start at previous even number if (result.testBit(0)) result = result.subtract(ONE); // Looking for the next large prime int searchLen = getPrimeSearchLen(result.bitLength()); while (true) { BitSieve searchSieve = new BitSieve(result, searchLen); BigInteger candidate = searchSieve.retrieve(result, DEFAULT_PRIME_CERTAINTY, null); if (candidate != null) return candidate; result = result.add(BigInteger.valueOf(2 * searchLen)); } } private static int getPrimeSearchLen(int bitLength) { if (bitLength > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) { throw new ArithmeticException(); } return bitLength / 20 * 64; } /** * Returns {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. * * This method assumes bitLength > 2. * * @param certainty a measure of the uncertainty that the caller is * willing to tolerate: if the call returns {@code true} * the probability that this BigInteger is prime exceeds * (1 - 1/2certainty). The execution time of * this method is proportional to the value of this parameter. * @return {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. */ boolean primeToCertainty(int certainty, Random random) { int rounds = 0; int n = (Math.min(certainty, Integer.MAX_VALUE-1)+1)/2; // The relationship between the certainty and the number of rounds // we perform is given in the draft standard ANSI X9.80, "PRIME // NUMBER GENERATION, PRIMALITY TESTING, AND PRIMALITY CERTIFICATES". int sizeInBits = this.bitLength(); if (sizeInBits < 100) { rounds = 50; rounds = n < rounds ? n : rounds; return passesMillerRabin(rounds, random); } if (sizeInBits < 256) { rounds = 27; } else if (sizeInBits < 512) { rounds = 15; } else if (sizeInBits < 768) { rounds = 8; } else if (sizeInBits < 1024) { rounds = 4; } else { rounds = 2; } rounds = n < rounds ? n : rounds; return passesMillerRabin(rounds, random) && passesLucasLehmer(); } /** * Returns true iff this BigInteger is a Lucas-Lehmer probable prime. * * The following assumptions are made: * This BigInteger is a positive, odd number. */ private boolean passesLucasLehmer() { BigInteger thisPlusOne = this.add(ONE); // Step 1 int d = 5; while (jacobiSymbol(d, this) != -1) { // 5, -7, 9, -11, ... d = (d < 0) ? Math.abs(d)+2 : -(d+2); } // Step 2 BigInteger u = lucasLehmerSequence(d, thisPlusOne, this); // Step 3 return u.mod(this).equals(ZERO); } /** * Computes Jacobi(p,n). * Assumes n positive, odd, n>=3. */ private static int jacobiSymbol(int p, BigInteger n) { if (p == 0) return 0; // Algorithm and comments adapted from Colin Plumb's C library. int j = 1; int u = n.mag[n.mag.length-1]; // Make p positive if (p < 0) { p = -p; int n8 = u & 7; if ((n8 == 3) || (n8 == 7)) j = -j; // 3 (011) or 7 (111) mod 8 } // Get rid of factors of 2 in p while ((p & 3) == 0) p >>= 2; if ((p & 1) == 0) { p >>= 1; if (((u ^ (u>>1)) & 2) != 0) j = -j; // 3 (011) or 5 (101) mod 8 } if (p == 1) return j; // Then, apply quadratic reciprocity if ((p & u & 2) != 0) // p = u = 3 (mod 4)? j = -j; // And reduce u mod p u = n.mod(BigInteger.valueOf(p)).intValue(); // Now compute Jacobi(u,p), u < p while (u != 0) { while ((u & 3) == 0) u >>= 2; if ((u & 1) == 0) { u >>= 1; if (((p ^ (p>>1)) & 2) != 0) j = -j; // 3 (011) or 5 (101) mod 8 } if (u == 1) return j; // Now both u and p are odd, so use quadratic reciprocity assert (u < p); int t = u; u = p; p = t; if ((u & p & 2) != 0) // u = p = 3 (mod 4)? j = -j; // Now u >= p, so it can be reduced u %= p; } return 0; } private static BigInteger lucasLehmerSequence(int z, BigInteger k, BigInteger n) { BigInteger d = BigInteger.valueOf(z); BigInteger u = ONE; BigInteger u2; BigInteger v = ONE; BigInteger v2; for (int i=k.bitLength()-2; i >= 0; i--) { u2 = u.multiply(v).mod(n); v2 = v.square().add(d.multiply(u.square())).mod(n); if (v2.testBit(0)) v2 = v2.subtract(n); v2 = v2.shiftRight(1); u = u2; v = v2; if (k.testBit(i)) { u2 = u.add(v).mod(n); if (u2.testBit(0)) u2 = u2.subtract(n); u2 = u2.shiftRight(1); v2 = v.add(d.multiply(u)).mod(n); if (v2.testBit(0)) v2 = v2.subtract(n); v2 = v2.shiftRight(1); u = u2; v = v2; } } return u; } /** * Returns true iff this BigInteger passes the specified number of * Miller-Rabin tests. This test is taken from the DSA spec (NIST FIPS * 186-2). * * The following assumptions are made: * This BigInteger is a positive, odd number greater than 2. * iterations<=50. */ private boolean passesMillerRabin(int iterations, Random rnd) { // Find a and m such that m is odd and this == 1 + 2**a * m BigInteger thisMinusOne = this.subtract(ONE); BigInteger m = thisMinusOne; int a = m.getLowestSetBit(); m = m.shiftRight(a); // Do the tests if (rnd == null) { rnd = ThreadLocalRandom.current(); } for (int i=0; i < iterations; i++) { // Generate a uniform random on (1, this) BigInteger b; do { b = new BigInteger(this.bitLength(), rnd); } while (b.compareTo(ONE) <= 0 || b.compareTo(this) >= 0); int j = 0; BigInteger z = b.modPow(m, this); while (!((j == 0 && z.equals(ONE)) || z.equals(thisMinusOne))) { if (j > 0 && z.equals(ONE) || ++j == a) return false; z = z.modPow(TWO, this); } } return true; } /** * This internal constructor differs from its public cousin * with the arguments reversed in two ways: it assumes that its * arguments are correct, and it doesn't copy the magnitude array. */ BigInteger(int[] magnitude, int signum) { this.signum = (magnitude.length == 0 ? 0 : signum); this.mag = magnitude; if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /** * This private constructor is for internal use and assumes that its * arguments are correct. The {@code magnitude} array is assumed to be * unchanged for the duration of the constructor call. */ private BigInteger(byte[] magnitude, int signum) { this.signum = (magnitude.length == 0 ? 0 : signum); this.mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length); if (mag.length >= MAX_MAG_LENGTH) { checkRange(); } } /** * Throws an {@code ArithmeticException} if the {@code BigInteger} would be * out of the supported range. * * @throws ArithmeticException if {@code this} exceeds the supported range. */ private void checkRange() { if (mag.length > MAX_MAG_LENGTH || mag.length == MAX_MAG_LENGTH && mag[0] < 0) { reportOverflow(); } } private static void reportOverflow() { throw new ArithmeticException(); } //Static Factory Methods /** * Returns a BigInteger whose value is equal to that of the * specified {@code long}. * * @apiNote This static factory method is provided in preference * to a ({@code long}) constructor because it allows for reuse of * frequently used BigIntegers. * * @param val value of the BigInteger to return. * @return a BigInteger with the specified value. */ public static BigInteger valueOf(long val) { // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant if (val == 0) return ZERO; if (val > 0 && val <= MAX_CONSTANT) return posConst[(int) val]; else if (val < 0 && val >= -MAX_CONSTANT) return negConst[(int) -val]; return new BigInteger(val); } /** * Constructs a BigInteger with the specified value, which may not be zero. */ private BigInteger(long val) { if (val < 0) { val = -val; signum = -1; } else { signum = 1; } int highWord = (int)(val >>> 32); if (highWord == 0) { mag = new int[1]; mag[0] = (int)val; } else { mag = new int[2]; mag[0] = highWord; mag[1] = (int)val; } } /** * Returns a BigInteger with the given two's complement representation. * Assumes that the input array will not be modified (the returned * BigInteger will reference the input array if feasible). */ private static BigInteger valueOf(int[] val) { return (val[0] > 0 ? new BigInteger(val, 1) : new BigInteger(val)); } // Constants /** * Initialize static constant array when class is loaded. */ private static final int MAX_CONSTANT = 16; @Stable private static final BigInteger[] posConst = new BigInteger[MAX_CONSTANT+1]; @Stable private static final BigInteger[] negConst = new BigInteger[MAX_CONSTANT+1]; /** * The cache of powers of each radix. This allows us to not have to * recalculate powers of radix^(2^n) more than once. This speeds * Schoenhage recursive base conversion significantly. */ private static volatile BigInteger[][] powerCache; /** The cache of logarithms of radices for base conversion. */ private static final double[] logCache; /** The natural log of 2. This is used in computing cache indices. */ private static final double LOG_TWO = Math.log(2.0); static { assert 0 < KARATSUBA_THRESHOLD && KARATSUBA_THRESHOLD < TOOM_COOK_THRESHOLD && TOOM_COOK_THRESHOLD < Integer.MAX_VALUE && 0 < KARATSUBA_SQUARE_THRESHOLD && KARATSUBA_SQUARE_THRESHOLD < TOOM_COOK_SQUARE_THRESHOLD && TOOM_COOK_SQUARE_THRESHOLD < Integer.MAX_VALUE : ; for (int i = 1; i <= MAX_CONSTANT; i++) { int[] magnitude = new int[1]; magnitude[0] = i; posConst[i] = new BigInteger(magnitude, 1); negConst[i] = new BigInteger(magnitude, -1); } /* * Initialize the cache of radix^(2^x) values used for base conversion * with just the very first value. Additional values will be created * on demand. */ BigInteger[][] cache = new BigInteger[Character.MAX_RADIX+1][]; logCache = new double[Character.MAX_RADIX+1]; for (int i=Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { cache[i] = new BigInteger[] { BigInteger.valueOf(i) }; logCache[i] = Math.log(i); } BigInteger.powerCache = cache; } /** * The BigInteger constant zero. * * @since 1.2 */ public static final BigInteger ZERO = new BigInteger(new int[0], 0); /** * The BigInteger constant one. * * @since 1.2 */ public static final BigInteger ONE = valueOf(1); /** * The BigInteger constant two. * * @since 9 */ public static final BigInteger TWO = valueOf(2); /** * The BigInteger constant -1. (Not exported.) */ private static final BigInteger NEGATIVE_ONE = valueOf(-1); /** * The BigInteger constant ten. * * @since 1.5 */ public static final BigInteger TEN = valueOf(10); // Arithmetic Operations /** * Returns a BigInteger whose value is {@code (this + val)}. * * @param val value to be added to this BigInteger. * @return {@code this + val} */ public BigInteger add(BigInteger val) { if (val.signum == 0) return this; if (signum == 0) return val; if (val.signum == signum) return new BigInteger(add(mag, val.mag), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) : subtract(val.mag, mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); } /** * Package private methods used by BigDecimal code to add a BigInteger * with a long. Assumes val is not equal to INFLATED. */ BigInteger add(long val) { if (val == 0) return this; if (signum == 0) return valueOf(val); if (Long.signum(val) == signum) return new BigInteger(add(mag, Math.abs(val)), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, Math.abs(val)) : subtract(Math.abs(val), mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); } /** * Adds the contents of the int array x and long value val. This * method allocates a new int array to hold the answer and returns * a reference to that array. Assumes x.length > 0 and val is * non-negative */ private static int[] add(int[] x, long val) { int[] y; long sum = 0; int xIndex = x.length; int[] result; int highWord = (int)(val >>> 32); if (highWord == 0) { result = new int[xIndex]; sum = (x[--xIndex] & LONG_MASK) + val; result[xIndex] = (int)sum; } else { if (xIndex == 1) { result = new int[2]; sum = val + (x[0] & LONG_MASK); result[1] = (int)sum; result[0] = (int)(sum >>> 32); return result; } else { result = new int[xIndex]; sum = (x[--xIndex] & LONG_MASK) + (val & LONG_MASK); result[xIndex] = (int)sum; sum = (x[--xIndex] & LONG_MASK) + (highWord & LONG_MASK) + (sum >>> 32); result[xIndex] = (int)sum; } } // Copy remainder of longer number while carry propagation is required boolean carry = (sum >>> 32 != 0); while (xIndex > 0 && carry) carry = ((result[--xIndex] = x[xIndex] + 1) == 0); // Copy remainder of longer number while (xIndex > 0) result[--xIndex] = x[xIndex]; // Grow result if necessary if (carry) { int bigger[] = new int[result.length + 1]; System.arraycopy(result, 0, bigger, 1, result.length); bigger[0] = 0x01; return bigger; } return result; } /** * Adds the contents of the int arrays x and y. This method allocates * a new int array to hold the answer and returns a reference to that * array. */ private static int[] add(int[] x, int[] y) { // If x is shorter, swap the two arrays if (x.length < y.length) { int[] tmp = x; x = y; y = tmp; } int xIndex = x.length; int yIndex = y.length; int result[] = new int[xIndex]; long sum = 0; if (yIndex == 1) { sum = (x[--xIndex] & LONG_MASK) + (y[0] & LONG_MASK) ; result[xIndex] = (int)sum; } else { // Add common parts of both numbers while (yIndex > 0) { sum = (x[--xIndex] & LONG_MASK) + (y[--yIndex] & LONG_MASK) + (sum >>> 32); result[xIndex] = (int)sum; } } // Copy remainder of longer number while carry propagation is required boolean carry = (sum >>> 32 != 0); while (xIndex > 0 && carry) carry = ((result[--xIndex] = x[xIndex] + 1) == 0); // Copy remainder of longer number while (xIndex > 0) result[--xIndex] = x[xIndex]; // Grow result if necessary if (carry) { int bigger[] = new int[result.length + 1]; System.arraycopy(result, 0, bigger, 1, result.length); bigger[0] = 0x01; return bigger; } return result; } private static int[] subtract(long val, int[] little) { int highWord = (int)(val >>> 32); if (highWord == 0) { int result[] = new int[1]; result[0] = (int)(val - (little[0] & LONG_MASK)); return result; } else { int result[] = new int[2]; if (little.length == 1) { long difference = ((int)val & LONG_MASK) - (little[0] & LONG_MASK); result[1] = (int)difference; // Subtract remainder of longer number while borrow propagates boolean borrow = (difference >> 32 != 0); if (borrow) { result[0] = highWord - 1; } else { // Copy remainder of longer number result[0] = highWord; } return result; } else { // little.length == 2 long difference = ((int)val & LONG_MASK) - (little[1] & LONG_MASK); result[1] = (int)difference; difference = (highWord & LONG_MASK) - (little[0] & LONG_MASK) + (difference >> 32); result[0] = (int)difference; return result; } } } /** * Subtracts the contents of the second argument (val) from the * first (big). The first int array (big) must represent a larger number * than the second. This method allocates the space necessary to hold the * answer. * assumes val >= 0 */ private static int[] subtract(int[] big, long val) { int highWord = (int)(val >>> 32); int bigIndex = big.length; int result[] = new int[bigIndex]; long difference = 0; if (highWord == 0) { difference = (big[--bigIndex] & LONG_MASK) - val; result[bigIndex] = (int)difference; } else { difference = (big[--bigIndex] & LONG_MASK) - (val & LONG_MASK); result[bigIndex] = (int)difference; difference = (big[--bigIndex] & LONG_MASK) - (highWord & LONG_MASK) + (difference >> 32); result[bigIndex] = (int)difference; } // Subtract remainder of longer number while borrow propagates boolean borrow = (difference >> 32 != 0); while (bigIndex > 0 && borrow) borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); // Copy remainder of longer number while (bigIndex > 0) result[--bigIndex] = big[bigIndex]; return result; } /** * Returns a BigInteger whose value is {@code (this - val)}. * * @param val value to be subtracted from this BigInteger. * @return {@code this - val} */ public BigInteger subtract(BigInteger val) { if (val.signum == 0) return this; if (signum == 0) return val.negate(); if (val.signum != signum) return new BigInteger(add(mag, val.mag), signum); int cmp = compareMagnitude(val); if (cmp == 0) return ZERO; int[] resultMag = (cmp > 0 ? subtract(mag, val.mag) : subtract(val.mag, mag)); resultMag = trustedStripLeadingZeroInts(resultMag); return new BigInteger(resultMag, cmp == signum ? 1 : -1); } /** * Subtracts the contents of the second int arrays (little) from the * first (big). The first int array (big) must represent a larger number * than the second. This method allocates the space necessary to hold the * answer. */ private static int[] subtract(int[] big, int[] little) { int bigIndex = big.length; int result[] = new int[bigIndex]; int littleIndex = little.length; long difference = 0; // Subtract common parts of both numbers while (littleIndex > 0) { difference = (big[--bigIndex] & LONG_MASK) - (little[--littleIndex] & LONG_MASK) + (difference >> 32); result[bigIndex] = (int)difference; } // Subtract remainder of longer number while borrow propagates boolean borrow = (difference >> 32 != 0); while (bigIndex > 0 && borrow) borrow = ((result[--bigIndex] = big[bigIndex] - 1) == -1); // Copy remainder of longer number while (bigIndex > 0) result[--bigIndex] = big[bigIndex]; return result; } /** * Returns a BigInteger whose value is {@code (this * val)}. * * @implNote An implementation may offer better algorithmic * performance when {@code val == this}. * * @param val value to be multiplied by this BigInteger. * @return {@code this * val} */ public BigInteger multiply(BigInteger val) { return multiply(val, false, false, 0); } /** * Returns a BigInteger whose value is {@code (this * val)}. * When both {@code this} and {@code val} are large, typically * in the thousands of bits, parallel multiply might be used. * This method returns the exact same mathematical result as * {@link #multiply}. * * @implNote This implementation may offer better algorithmic * performance when {@code val == this}. * * @implNote Compared to {@link #multiply}, an implementation's * parallel multiplication algorithm would typically use more * CPU resources to compute the result faster, and may do so * with a slight increase in memory consumption. * * @param val value to be multiplied by this BigInteger. * @return {@code this * val} * @see #multiply * @since 19 */ public BigInteger parallelMultiply(BigInteger val) { return multiply(val, false, true, 0); } /** * Returns a BigInteger whose value is {@code (this * val)}. If * the invocation is recursive certain overflow checks are skipped. * * @param val value to be multiplied by this BigInteger. * @param isRecursion whether this is a recursive invocation * @param parallel whether the multiply should be done in parallel * @return {@code this * val} */ private BigInteger multiply(BigInteger val, boolean isRecursion, boolean parallel, int depth) { if (val.signum == 0 || signum == 0) return ZERO; int xlen = mag.length; if (val == this && xlen > MULTIPLY_SQUARE_THRESHOLD) { return square(true, parallel, depth); } int ylen = val.mag.length; if ((xlen < KARATSUBA_THRESHOLD) || (ylen < KARATSUBA_THRESHOLD)) { int resultSign = signum == val.signum ? 1 : -1; if (val.mag.length == 1) { return multiplyByInt(mag,val.mag[0], resultSign); } if (mag.length == 1) { return multiplyByInt(val.mag,mag[0], resultSign); } int[] result = multiplyToLen(mag, xlen, val.mag, ylen, null); result = trustedStripLeadingZeroInts(result); return new BigInteger(result, resultSign); } else { if ((xlen < TOOM_COOK_THRESHOLD) && (ylen < TOOM_COOK_THRESHOLD)) { return multiplyKaratsuba(this, val); } else { // // In section 2-13, p.33, it is explained // that if x and y are unsigned 32-bit quantities and m and n // are their respective numbers of leading zeros within 32 bits, // then the number of leading zeros within their product as a // 64-bit unsigned quantity is either m + n or m + n + 1. If // their product is not to overflow, it cannot exceed 32 bits, // and so the number of leading zeros of the product within 64 // bits must be at least 32, i.e., the leftmost set bit is at // zero-relative position 31 or less. // // From the above there are three cases: // // m + n leftmost set bit condition // ----- ---------------- --------- // >= 32 x <= 64 - 32 = 32 no overflow // == 31 x >= 64 - 32 = 32 possible overflow // <= 30 x >= 64 - 31 = 33 definite overflow // // The condition cannot be detected by // examning data lengths alone and requires further calculation. // // By analogy, if 'this' and 'val' have m and n as their // respective numbers of leading zeros within 32*MAX_MAG_LENGTH // bits, then: // // m + n >= 32*MAX_MAG_LENGTH no overflow // m + n == 32*MAX_MAG_LENGTH - 1 possible overflow // m + n <= 32*MAX_MAG_LENGTH - 2 definite overflow // // Note however that if the number of ints in the result // were to be MAX_MAG_LENGTH and mag[0] < 0, then there would // be overflow. As a result the leftmost bit (of mag[0]) cannot // be used and the constraints must be adjusted by one bit to: // // m + n > 32*MAX_MAG_LENGTH no overflow // m + n == 32*MAX_MAG_LENGTH possible overflow // m + n < 32*MAX_MAG_LENGTH definite overflow // // The foregoing leading zero-based discussion is for clarity // only. The actual calculations use the estimated bit length // of the product as this is more natural to the internal // array representation of the magnitude which has no leading // zero elements. // if (!isRecursion) { // The bitLength() instance method is not used here as we // are only considering the magnitudes as non-negative. The // Toom-Cook multiplication algorithm determines the sign // at its end from the two signum values. if ((long)bitLength(mag, mag.length) + (long)bitLength(val.mag, val.mag.length) > 32L*MAX_MAG_LENGTH) { reportOverflow(); } } return multiplyToomCook3(this, val, parallel, depth); } } } private static BigInteger multiplyByInt(int[] x, int y, int sign) { if (Integer.bitCount(y) == 1) { return new BigInteger(shiftLeft(x,Integer.numberOfTrailingZeros(y)), sign); } int xlen = x.length; int[] rmag = new int[xlen + 1]; long carry = 0; long yl = y & LONG_MASK; int rstart = rmag.length - 1; for (int i = xlen - 1; i >= 0; i--) { long product = (x[i] & LONG_MASK) * yl + carry; rmag[rstart--] = (int)product; carry = product >>> 32; } if (carry == 0L) { rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length); } else { rmag[rstart] = (int)carry; } return new BigInteger(rmag, sign); } /** * Package private methods used by BigDecimal code to multiply a BigInteger * with a long. Assumes v is not equal to INFLATED. */ BigInteger multiply(long v) { if (v == 0 || signum == 0) return ZERO; if (v == BigDecimal.INFLATED) return multiply(BigInteger.valueOf(v)); int rsign = (v > 0 ? signum : -signum); if (v < 0) v = -v; long dh = v >>> 32; // higher order bits long dl = v & LONG_MASK; // lower order bits int xlen = mag.length; int[] value = mag; int[] rmag = (dh == 0L) ? (new int[xlen + 1]) : (new int[xlen + 2]); long carry = 0; int rstart = rmag.length - 1; for (int i = xlen - 1; i >= 0; i--) { long product = (value[i] & LONG_MASK) * dl + carry; rmag[rstart--] = (int)product; carry = product >>> 32; } rmag[rstart] = (int)carry; if (dh != 0L) { carry = 0; rstart = rmag.length - 2; for (int i = xlen - 1; i >= 0; i--) { long product = (value[i] & LONG_MASK) * dh + (rmag[rstart] & LONG_MASK) + carry; rmag[rstart--] = (int)product; carry = product >>> 32; } rmag[0] = (int)carry; } if (carry == 0L) rmag = java.util.Arrays.copyOfRange(rmag, 1, rmag.length); return new BigInteger(rmag, rsign); } /** * Multiplies int arrays x and y to the specified lengths and places * the result into z. There will be no leading zeros in the resultant array. */ private static int[] multiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { multiplyToLenCheck(x, xlen); multiplyToLenCheck(y, ylen); return implMultiplyToLen(x, xlen, y, ylen, z); } @IntrinsicCandidate private static int[] implMultiplyToLen(int[] x, int xlen, int[] y, int ylen, int[] z) { int xstart = xlen - 1; int ystart = ylen - 1; if (z == null || z.length < (xlen+ ylen)) z = new int[xlen+ylen]; long carry = 0; for (int j=ystart, k=ystart+1+xstart; j >= 0; j--, k--) { long product = (y[j] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry; z[k] = (int)product; carry = product >>> 32; } z[xstart] = (int)carry; for (int i = xstart-1; i >= 0; i--) { carry = 0; for (int j=ystart, k=ystart+1+i; j >= 0; j--, k--) { long product = (y[j] & LONG_MASK) * (x[i] & LONG_MASK) + (z[k] & LONG_MASK) + carry; z[k] = (int)product; carry = product >>> 32; } z[i] = (int)carry; } return z; } private static void multiplyToLenCheck(int[] array, int length) { if (length <= 0) { return; // not an error because multiplyToLen won't execute if len <= 0 } Objects.requireNonNull(array); if (length > array.length) { throw new ArrayIndexOutOfBoundsException(length - 1); } } /** * Multiplies two BigIntegers using the Karatsuba multiplication * algorithm. This is a recursive divide-and-conquer algorithm which is * more efficient for large numbers than what is commonly called the * algorithm used in multiplyToLen. If the numbers to be * multiplied have length n, the algorithm has an * asymptotic complexity of O(n^2). In contrast, the Karatsuba algorithm * has complexity of O(n^(log2(3))), or O(n^1.585). It achieves this * increased performance by doing 3 multiplies instead of 4 when * evaluating the product. As it has some overhead, should be used when * both numbers are larger than a certain threshold (found * experimentally). * * See: http://en.wikipedia.org/wiki/Karatsuba_algorithm */ private static BigInteger multiplyKaratsuba(BigInteger x, BigInteger y) { int xlen = x.mag.length; int ylen = y.mag.length; // The number of ints in each half of the number. int half = (Math.max(xlen, ylen)+1) / 2; // xl and yl are the lower halves of x and y respectively, // xh and yh are the upper halves. BigInteger xl = x.getLower(half); BigInteger xh = x.getUpper(half); BigInteger yl = y.getLower(half); BigInteger yh = y.getUpper(half); BigInteger p1 = xh.multiply(yh); // p1 = xh*yh BigInteger p2 = xl.multiply(yl); // p2 = xl*yl // p3=(xh+xl)*(yh+yl) BigInteger p3 = xh.add(xl).multiply(yh.add(yl)); // result = p1 * 2^(32*2*half) + (p3 - p1 - p2) * 2^(32*half) + p2 BigInteger result = p1.shiftLeft(32*half).add(p3.subtract(p1).subtract(p2)).shiftLeft(32*half).add(p2); if (x.signum != y.signum) { return result.negate(); } else { return result; } } @SuppressWarnings() private abstract static sealed class RecursiveOp extends RecursiveTask { /** * The threshold until when we should continue forking recursive ops * if parallel is true. This threshold is only relevant for Toom Cook 3 * multiply and square. */ private static final int PARALLEL_FORK_DEPTH_THRESHOLD = calculateMaximumDepth(ForkJoinPool.getCommonPoolParallelism()); private static final int calculateMaximumDepth(int parallelism) { return 32 - Integer.numberOfLeadingZeros(parallelism); } final boolean parallel; /** * The current recursing depth. Since it is a logarithmic algorithm, * we do not need an int to hold the number. */ final byte depth; private RecursiveOp(boolean parallel, int depth) { this.parallel = parallel; this.depth = (byte) depth; } private static int getParallelForkDepthThreshold() { if (Thread.currentThread() instanceof ForkJoinWorkerThread fjwt) { return calculateMaximumDepth(fjwt.getPool().getParallelism()); } else { return PARALLEL_FORK_DEPTH_THRESHOLD; } } protected RecursiveTask forkOrInvoke() { if (parallel && depth <= getParallelForkDepthThreshold()) fork(); else invoke(); return this; } @SuppressWarnings() private static final class RecursiveMultiply extends RecursiveOp { private final BigInteger a; private final BigInteger b; public RecursiveMultiply(BigInteger a, BigInteger b, boolean parallel, int depth) { super(parallel, depth); this.a = a; this.b = b; } @Override public BigInteger compute() { return a.multiply(b, true, parallel, depth); } } @SuppressWarnings() private static final class RecursiveSquare extends RecursiveOp { private final BigInteger a; public RecursiveSquare(BigInteger a, boolean parallel, int depth) { super(parallel, depth); this.a = a; } @Override public BigInteger compute() { return a.square(true, parallel, depth); } } private static RecursiveTask multiply(BigInteger a, BigInteger b, boolean parallel, int depth) { return new RecursiveMultiply(a, b, parallel, depth).forkOrInvoke(); } private static RecursiveTask square(BigInteger a, boolean parallel, int depth) { return new RecursiveSquare(a, parallel, depth).forkOrInvoke(); } } /** * Multiplies two BigIntegers using a 3-way Toom-Cook multiplication * algorithm. This is a recursive divide-and-conquer algorithm which is * more efficient for large numbers than what is commonly called the * algorithm used in multiplyToLen. If the numbers to be * multiplied have length n, the algorithm has an * asymptotic complexity of O(n^2). In contrast, 3-way Toom-Cook has a * complexity of about O(n^1.465). It achieves this increased asymptotic * performance by breaking each number into three parts and by doing 5 * multiplies instead of 9 when evaluating the product. Due to overhead * (additions, shifts, and one division) in the Toom-Cook algorithm, it * should only be used when both numbers are larger than a certain * threshold (found experimentally). This threshold is generally larger * than that for Karatsuba multiplication, so this algorithm is generally * only used when numbers become significantly larger. * * The algorithm used is the 3-way Toom-Cook algorithm outlined * by Marco Bodrato. * * See: http://bodrato.it/toom-cook/ * http://bodrato.it/papers/#WAIFI2007 * * "Towards Optimal Toom-Cook Multiplication for Univariate and * Multivariate Polynomials in Characteristic 2 and 0." by Marco BODRATO; * In C.Carlet and B.Sunar, Eds., , p. 116-133, * LNCS #4547. Springer, Madrid, Spain, June 21-22, 2007. * */ private static BigInteger multiplyToomCook3(BigInteger a, BigInteger b, boolean parallel, int depth) { int alen = a.mag.length; int blen = b.mag.length; int largest = Math.max(alen, blen); // k is the size (in ints) of the lower-order slices. int k = (largest+2)/3; // Equal to ceil(largest/3) // r is the size (in ints) of the highest-order slice. int r = largest - 2*k; // Obtain slices of the numbers. a2 and b2 are the most significant // bits of the numbers a and b, and a0 and b0 the least significant. BigInteger a0, a1, a2, b0, b1, b2; a2 = a.getToomSlice(k, r, 0, largest); a1 = a.getToomSlice(k, r, 1, largest); a0 = a.getToomSlice(k, r, 2, largest); b2 = b.getToomSlice(k, r, 0, largest); b1 = b.getToomSlice(k, r, 1, largest); b0 = b.getToomSlice(k, r, 2, largest); BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1, db1; depth++; var v0_task = RecursiveOp.multiply(a0, b0, parallel, depth); da1 = a2.add(a0); db1 = b2.add(b0); var vm1_task = RecursiveOp.multiply(da1.subtract(a1), db1.subtract(b1), parallel, depth); da1 = da1.add(a1); db1 = db1.add(b1); var v1_task = RecursiveOp.multiply(da1, db1, parallel, depth); v2 = da1.add(a2).shiftLeft(1).subtract(a0).multiply( db1.add(b2).shiftLeft(1).subtract(b0), true, parallel, depth); vinf = a2.multiply(b2, true, parallel, depth); v0 = v0_task.join(); vm1 = vm1_task.join(); v1 = v1_task.join(); // The algorithm requires two divisions by 2 and one by 3. // All divisions are known to be exact, that is, they do not produce // remainders, and all results are positive. The divisions by 2 are // implemented as right shifts which are relatively efficient, leaving // only an exact division by 3, which is done by a specialized // linear-time algorithm. t2 = v2.subtract(vm1).exactDivideBy3(); tm1 = v1.subtract(vm1).shiftRight(1); t1 = v1.subtract(v0); t2 = t2.subtract(t1).shiftRight(1); t1 = t1.subtract(tm1).subtract(vinf); t2 = t2.subtract(vinf.shiftLeft(1)); tm1 = tm1.subtract(t2); // Number of bits to shift left. int ss = k*32; BigInteger result = vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0); if (a.signum != b.signum) { return result.negate(); } else { return result; } } /** * Returns a slice of a BigInteger for use in Toom-Cook multiplication. * * @param lowerSize The size of the lower-order bit slices. * @param upperSize The size of the higher-order bit slices. * @param slice The index of which slice is requested, which must be a * number from 0 to size-1. Slice 0 is the highest-order bits, and slice * size-1 are the lowest-order bits. Slice 0 may be of different size than * the other slices. * @param fullsize The size of the larger integer array, used to align * slices to the appropriate position when multiplying different-sized * numbers. */ private BigInteger getToomSlice(int lowerSize, int upperSize, int slice, int fullsize) { int start, end, sliceSize, len, offset; len = mag.length; offset = fullsize - len; if (slice == 0) { start = 0 - offset; end = upperSize - 1 - offset; } else { start = upperSize + (slice-1)*lowerSize - offset; end = start + lowerSize - 1; } if (start < 0) { start = 0; } if (end < 0) { return ZERO; } sliceSize = (end-start) + 1; if (sliceSize <= 0) { return ZERO; } // While performing Toom-Cook, all slices are positive and // the sign is adjusted when the final number is composed. if (start == 0 && sliceSize >= len) { return this.abs(); } int intSlice[] = new int[sliceSize]; System.arraycopy(mag, start, intSlice, 0, sliceSize); return new BigInteger(trustedStripLeadingZeroInts(intSlice), 1); } /** * Does an exact division (that is, the remainder is known to be zero) * of the specified number by 3. This is used in Toom-Cook * multiplication. This is an efficient algorithm that runs in linear * time. If the argument is not exactly divisible by 3, results are * undefined. Note that this is expected to be called with positive * arguments only. */ private BigInteger exactDivideBy3() { int len = mag.length; int[] result = new int[len]; long x, w, q, borrow; borrow = 0L; for (int i=len-1; i >= 0; i--) { x = (mag[i] & LONG_MASK); w = x - borrow; if (borrow > x) { // Did we make the number go negative? borrow = 1L; } else { borrow = 0L; } // 0xAAAAAAAB is the modular inverse of 3 (mod 2^32). Thus, // the effect of this is to divide by 3 (mod 2^32). // This is much faster than division on most architectures. q = (w * 0xAAAAAAABL) & LONG_MASK; result[i] = (int) q; // Now check the borrow. The second check can of course be // eliminated if the first fails. if (q >= 0x55555556L) { borrow++; if (q >= 0xAAAAAAABL) borrow++; } } result = trustedStripLeadingZeroInts(result); return new BigInteger(result, signum); } /** * Returns a new BigInteger representing n lower ints of the number. * This is used by Karatsuba multiplication and Karatsuba squaring. */ private BigInteger getLower(int n) { int len = mag.length; if (len <= n) { return abs(); } int lowerInts[] = new int[n]; System.arraycopy(mag, len-n, lowerInts, 0, n); return new BigInteger(trustedStripLeadingZeroInts(lowerInts), 1); } /** * Returns a new BigInteger representing mag.length-n upper * ints of the number. This is used by Karatsuba multiplication and * Karatsuba squaring. */ private BigInteger getUpper(int n) { int len = mag.length; if (len <= n) { return ZERO; } int upperLen = len - n; int upperInts[] = new int[upperLen]; System.arraycopy(mag, 0, upperInts, 0, upperLen); return new BigInteger(trustedStripLeadingZeroInts(upperInts), 1); } // Squaring /** * Returns a BigInteger whose value is (this2). * * @return this2 */ private BigInteger square() { return square(false, false, 0); } /** * Returns a BigInteger whose value is (this2). If * the invocation is recursive certain overflow checks are skipped. * * @param isRecursion whether this is a recursive invocation * @return this2 */ private BigInteger square(boolean isRecursion, boolean parallel, int depth) { if (signum == 0) { return ZERO; } int len = mag.length; if (len < KARATSUBA_SQUARE_THRESHOLD) { int[] z = squareToLen(mag, len, null); return new BigInteger(trustedStripLeadingZeroInts(z), 1); } else { if (len < TOOM_COOK_SQUARE_THRESHOLD) { return squareKaratsuba(); } else { // // For a discussion of overflow detection see multiply() // if (!isRecursion) { if (bitLength(mag, mag.length) > 16L*MAX_MAG_LENGTH) { reportOverflow(); } } return squareToomCook3(parallel, depth); } } } /** * Squares the contents of the int array x. The result is placed into the * int array z. The contents of x are not changed. */ private static final int[] squareToLen(int[] x, int len, int[] z) { int zlen = len << 1; if (z == null || z.length < zlen) z = new int[zlen]; // Execute checks before calling intrinsified method. implSquareToLenChecks(x, len, z, zlen); return implSquareToLen(x, len, z, zlen); } /** * Parameters validation. */ private static void implSquareToLenChecks(int[] x, int len, int[] z, int zlen) throws RuntimeException { if (len < 1) { throw new IllegalArgumentException( + len); } if (len > x.length) { throw new IllegalArgumentException( + len + + x.length); } if (len * 2 > z.length) { throw new IllegalArgumentException( + (len * 2) + + z.length); } if (zlen < 1) { throw new IllegalArgumentException( + zlen); } if (zlen > z.length) { throw new IllegalArgumentException( + len + + z.length); } } /** * Java Runtime may use intrinsic for this method. */ @IntrinsicCandidate private static final int[] implSquareToLen(int[] x, int len, int[] z, int zlen) { /* * The algorithm used here is adapted from Colin Plumb's C library. * Technique: Consider the partial products in the multiplication * of by itself: * * a b c d e * * a b c d e * ================== * ae be ce de ee * ad bd cd dd de * ac bc cc cd ce * ab bb bc bd be * aa ab ac ad ae * * Note that everything above the main diagonal: * ae be ce de = (abcd) * e * ad bd cd = (abc) * d * ac bc = (ab) * c * ab = (a) * b * * is a copy of everything below the main diagonal: * de * cd ce * bc bd be * ab ac ad ae * * Thus, the sum is 2 * (off the diagonal) + diagonal. * * This is accumulated beginning with the diagonal (which * consist of the squares of the digits of the input), which is then * divided by two, the off-diagonal added, and multiplied by two * again. The low bit is simply a copy of the low bit of the * input, so it doesn't need special care. */ // Store the squares, right shifted one bit (i.e., divided by 2) int lastProductLowWord = 0; for (int j=0, i=0; j < len; j++) { long piece = (x[j] & LONG_MASK); long product = piece * piece; z[i++] = (lastProductLowWord << 31) | (int)(product >>> 33); z[i++] = (int)(product >>> 1); lastProductLowWord = (int)product; } // Add in off-diagonal sums for (int i=len, offset=1; i > 0; i--, offset+=2) { int t = x[i-1]; t = mulAdd(z, x, offset, i-1, t); addOne(z, offset-1, i, t); } // Shift back up and set low bit primitiveLeftShift(z, zlen, 1); z[zlen-1] |= x[len-1] & 1; return z; } /** * Squares a BigInteger using the Karatsuba squaring algorithm. It should * be used when both numbers are larger than a certain threshold (found * experimentally). It is a recursive divide-and-conquer algorithm that * has better asymptotic performance than the algorithm used in * squareToLen. */ private BigInteger squareKaratsuba() { int half = (mag.length+1) / 2; BigInteger xl = getLower(half); BigInteger xh = getUpper(half); BigInteger xhs = xh.square(); // xhs = xh^2 BigInteger xls = xl.square(); // xls = xl^2 // xh^2 << 64 + (((xl+xh)^2 - (xh^2 + xl^2)) << 32) + xl^2 return xhs.shiftLeft(half*32).add(xl.add(xh).square().subtract(xhs.add(xls))).shiftLeft(half*32).add(xls); } /** * Squares a BigInteger using the 3-way Toom-Cook squaring algorithm. It * should be used when both numbers are larger than a certain threshold * (found experimentally). It is a recursive divide-and-conquer algorithm * that has better asymptotic performance than the algorithm used in * squareToLen or squareKaratsuba. */ private BigInteger squareToomCook3(boolean parallel, int depth) { int len = mag.length; // k is the size (in ints) of the lower-order slices. int k = (len+2)/3; // Equal to ceil(largest/3) // r is the size (in ints) of the highest-order slice. int r = len - 2*k; // Obtain slices of the numbers. a2 is the most significant // bits of the number, and a0 the least significant. BigInteger a0, a1, a2; a2 = getToomSlice(k, r, 0, len); a1 = getToomSlice(k, r, 1, len); a0 = getToomSlice(k, r, 2, len); BigInteger v0, v1, v2, vm1, vinf, t1, t2, tm1, da1; depth++; var v0_fork = RecursiveOp.square(a0, parallel, depth); da1 = a2.add(a0); var vm1_fork = RecursiveOp.square(da1.subtract(a1), parallel, depth); da1 = da1.add(a1); var v1_fork = RecursiveOp.square(da1, parallel, depth); vinf = a2.square(true, parallel, depth); v2 = da1.add(a2).shiftLeft(1).subtract(a0).square(true, parallel, depth); v0 = v0_fork.join(); vm1 = vm1_fork.join(); v1 = v1_fork.join(); // The algorithm requires two divisions by 2 and one by 3. // All divisions are known to be exact, that is, they do not produce // remainders, and all results are positive. The divisions by 2 are // implemented as right shifts which are relatively efficient, leaving // only a division by 3. // The division by 3 is done by an optimized algorithm for this case. t2 = v2.subtract(vm1).exactDivideBy3(); tm1 = v1.subtract(vm1).shiftRight(1); t1 = v1.subtract(v0); t2 = t2.subtract(t1).shiftRight(1); t1 = t1.subtract(tm1).subtract(vinf); t2 = t2.subtract(vinf.shiftLeft(1)); tm1 = tm1.subtract(t2); // Number of bits to shift left. int ss = k*32; return vinf.shiftLeft(ss).add(t2).shiftLeft(ss).add(t1).shiftLeft(ss).add(tm1).shiftLeft(ss).add(v0); } // Division /** * Returns a BigInteger whose value is {@code (this / val)}. * * @param val value by which this BigInteger is to be divided. * @return {@code this / val} * @throws ArithmeticException if {@code val} is zero. */ public BigInteger divide(BigInteger val) { if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { return divideKnuth(val); } else { return divideBurnikelZiegler(val); } } /** * Returns a BigInteger whose value is {@code (this / val)} using an O(n^2) algorithm from Knuth. * * @param val value by which this BigInteger is to be divided. * @return {@code this / val} * @throws ArithmeticException if {@code val} is zero. * @see MutableBigInteger#divideKnuth(MutableBigInteger, MutableBigInteger, boolean) */ private BigInteger divideKnuth(BigInteger val) { MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); a.divideKnuth(b, q, false); return q.toBigInteger(this.signum * val.signum); } /** * Returns an array of two BigIntegers containing {@code (this / val)} * followed by {@code (this % val)}. * * @param val value by which this BigInteger is to be divided, and the * remainder computed. * @return an array of two BigIntegers: the quotient {@code (this / val)} * is the initial element, and the remainder {@code (this % val)} * is the final element. * @throws ArithmeticException if {@code val} is zero. */ public BigInteger[] divideAndRemainder(BigInteger val) { if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { return divideAndRemainderKnuth(val); } else { return divideAndRemainderBurnikelZiegler(val); } } /** Long division */ private BigInteger[] divideAndRemainderKnuth(BigInteger val) { BigInteger[] result = new BigInteger[2]; MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); MutableBigInteger r = a.divideKnuth(b, q); result[0] = q.toBigInteger(this.signum == val.signum ? 1 : -1); result[1] = r.toBigInteger(this.signum); return result; } /** * Returns a BigInteger whose value is {@code (this % val)}. * * @param val value by which this BigInteger is to be divided, and the * remainder computed. * @return {@code this % val} * @throws ArithmeticException if {@code val} is zero. */ public BigInteger remainder(BigInteger val) { if (val.mag.length < BURNIKEL_ZIEGLER_THRESHOLD || mag.length - val.mag.length < BURNIKEL_ZIEGLER_OFFSET) { return remainderKnuth(val); } else { return remainderBurnikelZiegler(val); } } /** Long division */ private BigInteger remainderKnuth(BigInteger val) { MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(this.mag), b = new MutableBigInteger(val.mag); return a.divideKnuth(b, q).toBigInteger(this.signum); } /** * Calculates {@code this / val} using the Burnikel-Ziegler algorithm. * @param val the divisor * @return {@code this / val} */ private BigInteger divideBurnikelZiegler(BigInteger val) { return divideAndRemainderBurnikelZiegler(val)[0]; } /** * Calculates {@code this % val} using the Burnikel-Ziegler algorithm. * @param val the divisor * @return {@code this % val} */ private BigInteger remainderBurnikelZiegler(BigInteger val) { return divideAndRemainderBurnikelZiegler(val)[1]; } /** * Computes {@code this / val} and {@code this % val} using the * Burnikel-Ziegler algorithm. * @param val the divisor * @return an array containing the quotient and remainder */ private BigInteger[] divideAndRemainderBurnikelZiegler(BigInteger val) { MutableBigInteger q = new MutableBigInteger(); MutableBigInteger r = new MutableBigInteger(this).divideAndRemainderBurnikelZiegler(new MutableBigInteger(val), q); BigInteger qBigInt = q.isZero() ? ZERO : q.toBigInteger(signum*val.signum); BigInteger rBigInt = r.isZero() ? ZERO : r.toBigInteger(signum); return new BigInteger[] {qBigInt, rBigInt}; } /** * Returns a BigInteger whose value is (thisexponent). * Note that {@code exponent} is an integer rather than a BigInteger. * * @param exponent exponent to which this BigInteger is to be raised. * @return thisexponent * @throws ArithmeticException {@code exponent} is negative. (This would * cause the operation to yield a non-integer value.) */ public BigInteger pow(int exponent) { if (exponent < 0) { throw new ArithmeticException(); } if (signum == 0) { return (exponent == 0 ? ONE : this); } BigInteger partToSquare = this.abs(); // Factor out powers of two from the base, as the exponentiation of // these can be done by left shifts only. // The remaining part can then be exponentiated faster. The // powers of two will be multiplied back at the end. int powersOfTwo = partToSquare.getLowestSetBit(); long bitsToShiftLong = (long)powersOfTwo * exponent; if (bitsToShiftLong > Integer.MAX_VALUE) { reportOverflow(); } int bitsToShift = (int)bitsToShiftLong; int remainingBits; // Factor the powers of two out quickly by shifting right, if needed. if (powersOfTwo > 0) { partToSquare = partToSquare.shiftRight(powersOfTwo); remainingBits = partToSquare.bitLength(); if (remainingBits == 1) { // Nothing left but +/- 1? if (signum < 0 && (exponent&1) == 1) { return NEGATIVE_ONE.shiftLeft(bitsToShift); } else { return ONE.shiftLeft(bitsToShift); } } } else { remainingBits = partToSquare.bitLength(); if (remainingBits == 1) { // Nothing left but +/- 1? if (signum < 0 && (exponent&1) == 1) { return NEGATIVE_ONE; } else { return ONE; } } } // This is a quick way to approximate the size of the result, // similar to doing log2[n] * exponent. This will give an upper bound // of how big the result can be, and which algorithm to use. long scaleFactor = (long)remainingBits * exponent; // Use slightly different algorithms for small and large operands. // See if the result will safely fit into a long. (Largest 2^63-1) if (partToSquare.mag.length == 1 && scaleFactor <= 62) { // Small number algorithm. Everything fits into a long. int newSign = (signum <0 && (exponent&1) == 1 ? -1 : 1); long result = 1; long baseToPow2 = partToSquare.mag[0] & LONG_MASK; int workingExponent = exponent; // Perform exponentiation using repeated squaring trick while (workingExponent != 0) { if ((workingExponent & 1) == 1) { result = result * baseToPow2; } if ((workingExponent >>>= 1) != 0) { baseToPow2 = baseToPow2 * baseToPow2; } } // Multiply back the powers of two (quickly, by shifting left) if (powersOfTwo > 0) { if (bitsToShift + scaleFactor <= 62) { // Fits in long? return valueOf((result << bitsToShift) * newSign); } else { return valueOf(result*newSign).shiftLeft(bitsToShift); } } else { return valueOf(result*newSign); } } else { if ((long)bitLength() * exponent / Integer.SIZE > MAX_MAG_LENGTH) { reportOverflow(); } // Large number algorithm. This is basically identical to // the algorithm above, but calls multiply() and square() // which may use more efficient algorithms for large numbers. BigInteger answer = ONE; int workingExponent = exponent; // Perform exponentiation using repeated squaring trick while (workingExponent != 0) { if ((workingExponent & 1) == 1) { answer = answer.multiply(partToSquare); } if ((workingExponent >>>= 1) != 0) { partToSquare = partToSquare.square(); } } // Multiply back the (exponentiated) powers of two (quickly, // by shifting left) if (powersOfTwo > 0) { answer = answer.shiftLeft(bitsToShift); } if (signum < 0 && (exponent&1) == 1) { return answer.negate(); } else { return answer; } } } /** * Returns the integer square root of this BigInteger. The integer square * root of the corresponding mathematical integer {@code n} is the largest * mathematical integer {@code s} such that {@code s*s <= n}. It is equal * to the value of {@code floor(sqrt(n))}, where {@code sqrt(n)} denotes the * real square root of {@code n} treated as a real. Note that the integer * square root will be less than the real square root if the latter is not * representable as an integral value. * * @return the integer square root of {@code this} * @throws ArithmeticException if {@code this} is negative. (The square * root of a negative integer {@code val} is * {@code (i * sqrt(-val))} where i is the * imaginary unit and is equal to * {@code sqrt(-1)}.) * @since 9 */ public BigInteger sqrt() { if (this.signum < 0) { throw new ArithmeticException(); } return new MutableBigInteger(this.mag).sqrt().toBigInteger(); } /** * Returns an array of two BigIntegers containing the integer square root * {@code s} of {@code this} and its remainder {@code this - s*s}, * respectively. * * @return an array of two BigIntegers with the integer square root at * offset 0 and the remainder at offset 1 * @throws ArithmeticException if {@code this} is negative. (The square * root of a negative integer {@code val} is * {@code (i * sqrt(-val))} where i is the * imaginary unit and is equal to * {@code sqrt(-1)}.) * @see #sqrt() * @since 9 */ public BigInteger[] sqrtAndRemainder() { BigInteger s = sqrt(); BigInteger r = this.subtract(s.square()); assert r.compareTo(BigInteger.ZERO) >= 0; return new BigInteger[] {s, r}; } /** * Returns a BigInteger whose value is the greatest common divisor of * {@code abs(this)} and {@code abs(val)}. Returns 0 if * {@code this == 0 && val == 0}. * * @param val value with which the GCD is to be computed. * @return {@code GCD(abs(this), abs(val))} */ public BigInteger gcd(BigInteger val) { if (val.signum == 0) return this.abs(); else if (this.signum == 0) return val.abs(); MutableBigInteger a = new MutableBigInteger(this); MutableBigInteger b = new MutableBigInteger(val); MutableBigInteger result = a.hybridGCD(b); return result.toBigInteger(1); } /** * Package private method to return bit length for an integer. */ static int bitLengthForInt(int n) { return 32 - Integer.numberOfLeadingZeros(n); } /** * Left shift int array a up to len by n bits. Returns the array that * results from the shift since space may have to be reallocated. */ private static int[] leftShift(int[] a, int len, int n) { int nInts = n >>> 5; int nBits = n&0x1F; int bitsInHighWord = bitLengthForInt(a[0]); // If shift can be done without recopy, do so if (n <= (32-bitsInHighWord)) { primitiveLeftShift(a, len, nBits); return a; } else { // Array must be resized if (nBits <= (32-bitsInHighWord)) { int result[] = new int[nInts+len]; System.arraycopy(a, 0, result, 0, len); primitiveLeftShift(result, result.length, nBits); return result; } else { int result[] = new int[nInts+len+1]; System.arraycopy(a, 0, result, 0, len); primitiveRightShift(result, result.length, 32 - nBits); return result; } } } // shifts a up to len right n bits assumes no leading zeros, 0>>= n; } // shifts a up to len left n bits assumes no leading zeros, 0<=n<32 static void primitiveLeftShift(int[] a, int len, int n) { if (len == 0 || n == 0) return; Objects.checkFromToIndex(0, len, a.length); shiftLeftImplWorker(a, a, 0, n, len-1); a[len-1] <<= n; } /** * Calculate bitlength of contents of the first len elements an int array, * assuming there are no leading zero ints. */ private static int bitLength(int[] val, int len) { if (len == 0) return 0; return ((len - 1) << 5) + bitLengthForInt(val[0]); } /** * Returns a BigInteger whose value is the absolute value of this * BigInteger. * * @return {@code abs(this)} */ public BigInteger abs() { return (signum >= 0 ? this : this.negate()); } /** * Returns a BigInteger whose value is {@code (-this)}. * * @return {@code -this} */ public BigInteger negate() { return new BigInteger(this.mag, -this.signum); } /** * Returns the signum function of this BigInteger. * * @return -1, 0 or 1 as the value of this BigInteger is negative, zero or * positive. */ public int signum() { return this.signum; } // Modular Arithmetic Operations /** * Returns a BigInteger whose value is {@code (this mod m}). This method * differs from {@code remainder} in that it always returns a * non-negative BigInteger. * * @param m the modulus. * @return {@code this mod m} * @throws ArithmeticException {@code m} ≤ 0 * @see #remainder */ public BigInteger mod(BigInteger m) { if (m.signum <= 0) throw new ArithmeticException(); BigInteger result = this.remainder(m); return (result.signum >= 0 ? result : result.add(m)); } /** * Returns a BigInteger whose value is * (thisexponent mod m). (Unlike {@code pow}, this * method permits negative exponents.) * * @param exponent the exponent. * @param m the modulus. * @return thisexponent mod m * @throws ArithmeticException {@code m} ≤ 0 or the exponent is * negative and this BigInteger is not relatively * prime to {@code m}. * @see #modInverse */ public BigInteger modPow(BigInteger exponent, BigInteger m) { if (m.signum <= 0) throw new ArithmeticException(); // Trivial cases if (exponent.signum == 0) return (m.equals(ONE) ? ZERO : ONE); if (this.equals(ONE)) return (m.equals(ONE) ? ZERO : ONE); if (this.equals(ZERO) && exponent.signum >= 0) return ZERO; if (this.equals(negConst[1]) && (!exponent.testBit(0))) return (m.equals(ONE) ? ZERO : ONE); boolean invertResult; if ((invertResult = (exponent.signum < 0))) exponent = exponent.negate(); BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0 ? this.mod(m) : this); BigInteger result; if (m.testBit(0)) { // odd modulus result = base.oddModPow(exponent, m); } else { /* * Even modulus. Tear it into an (m1) and power of two * (m2), exponentiate mod m1, manually exponentiate mod m2, and * use Chinese Remainder Theorem to combine results. */ // Tear m apart into odd part (m1) and power of 2 (m2) int p = m.getLowestSetBit(); // Max pow of 2 that divides m BigInteger m1 = m.shiftRight(p); // m/2**p BigInteger m2 = ONE.shiftLeft(p); // 2**p // Calculate new base from m1 BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0 ? this.mod(m1) : this); // Calculate (base ** exponent) mod m1. BigInteger a1 = (m1.equals(ONE) ? ZERO : base2.oddModPow(exponent, m1)); // Calculate (this ** exponent) mod m2 BigInteger a2 = base.modPow2(exponent, p); // Combine results using Chinese Remainder Theorem BigInteger y1 = m2.modInverse(m1); BigInteger y2 = m1.modInverse(m2); if (m.mag.length < MAX_MAG_LENGTH / 2) { result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m); } else { MutableBigInteger t1 = new MutableBigInteger(); new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1); MutableBigInteger t2 = new MutableBigInteger(); new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2); t1.add(t2); MutableBigInteger q = new MutableBigInteger(); result = t1.divide(new MutableBigInteger(m), q).toBigInteger(); } } return (invertResult ? result.modInverse(m) : result); } // Montgomery multiplication. These are wrappers for // implMontgomeryXX routines which are expected to be replaced by // virtual machine intrinsics. We don't use the intrinsics for // very large operands: MONTGOMERY_INTRINSIC_THRESHOLD should be // larger than any reasonable crypto key. private static int[] montgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product) { implMontgomeryMultiplyChecks(a, b, n, len, product); if (len > MONTGOMERY_INTRINSIC_THRESHOLD) { // Very long argument: do not use an intrinsic product = multiplyToLen(a, len, b, len, product); return montReduce(product, n, len, (int)inv); } else { return implMontgomeryMultiply(a, b, n, len, inv, materialize(product, len)); } } private static int[] montgomerySquare(int[] a, int[] n, int len, long inv, int[] product) { implMontgomeryMultiplyChecks(a, a, n, len, product); if (len > MONTGOMERY_INTRINSIC_THRESHOLD) { // Very long argument: do not use an intrinsic product = squareToLen(a, len, product); return montReduce(product, n, len, (int)inv); } else { return implMontgomerySquare(a, n, len, inv, materialize(product, len)); } } // Range-check everything. private static void implMontgomeryMultiplyChecks (int[] a, int[] b, int[] n, int len, int[] product) throws RuntimeException { if (len % 2 != 0) { throw new IllegalArgumentException( + len); } if (len < 1) { throw new IllegalArgumentException( + len); } if (len > a.length || len > b.length || len > n.length || (product != null && len > product.length)) { throw new IllegalArgumentException( + len); } } // Make sure that the int array z (which is expected to contain // the result of a Montgomery multiplication) is present and // sufficiently large. private static int[] materialize(int[] z, int len) { if (z == null || z.length < len) z = new int[len]; return z; } // These methods are intended to be replaced by virtual machine // intrinsics. @IntrinsicCandidate private static int[] implMontgomeryMultiply(int[] a, int[] b, int[] n, int len, long inv, int[] product) { product = multiplyToLen(a, len, b, len, product); return montReduce(product, n, len, (int)inv); } @IntrinsicCandidate private static int[] implMontgomerySquare(int[] a, int[] n, int len, long inv, int[] product) { product = squareToLen(a, len, product); return montReduce(product, n, len, (int)inv); } static int[] bnExpModThreshTable = {7, 25, 81, 241, 673, 1793, Integer.MAX_VALUE}; // Sentinel public int getLowestSetBit() { int lsb = lowestSetBitPlusTwo - 2; if (lsb == -2) { // lowestSetBit not initialized yet lsb = 0; if (signum == 0) { lsb -= 1; } else { // Search for lowest order nonzero int int i,b; for (i=0; (b = getInt(i)) == 0; i++) ; lsb += (i << 5) + Integer.numberOfTrailingZeros(b); } lowestSetBitPlusTwo = lsb + 2; } return lsb; } // Miscellaneous Bit Operations /** * Returns the number of bits in the minimal two's-complement * representation of this BigInteger, excluding a sign bit. * For positive BigIntegers, this is equivalent to the number of bits in * the ordinary binary representation. For zero this method returns * {@code 0}. (Computes {@code (ceil(log2(this < 0 ? -this : this+1)))}.) * * @return number of bits in the minimal two's-complement * representation of this BigInteger, excluding a sign bit. */ public int bitLength() { int n = bitLengthPlusOne - 1; if (n == -1) { // bitLength not initialized yet int[] m = mag; int len = m.length; if (len == 0) { n = 0; // offset by one to initialize } else { // Calculate the bit length of the magnitude int magBitLength = ((len - 1) << 5) + bitLengthForInt(mag[0]); if (signum < 0) { // Check if magnitude is a power of two boolean pow2 = (Integer.bitCount(mag[0]) == 1); for (int i=1; i< len && pow2; i++) pow2 = (mag[i] == 0); n = (pow2 ? magBitLength - 1 : magBitLength); } else { n = magBitLength; } } bitLengthPlusOne = n + 1; } return n; } /** * Returns the number of bits in the two's complement representation * of this BigInteger that differ from its sign bit. This method is * useful when implementing bit-vector style sets atop BigIntegers. * * @return number of bits in the two's complement representation * of this BigInteger that differ from its sign bit. */ public int bitCount() { int bc = bitCountPlusOne - 1; if (bc == -1) { // bitCount not initialized yet bc = 0; // offset by one to initialize // Count the bits in the magnitude for (int i=0; i < mag.length; i++) bc += Integer.bitCount(mag[i]); if (signum < 0) { // Count the trailing zeros in the magnitude int magTrailingZeroCount = 0, j; for (j=mag.length-1; mag[j] == 0; j--) magTrailingZeroCount += 32; magTrailingZeroCount += Integer.numberOfTrailingZeros(mag[j]); bc += magTrailingZeroCount - 1; } bitCountPlusOne = bc + 1; } return bc; } // Primality Testing /** * Returns {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. If * {@code certainty} is ≤ 0, {@code true} is * returned. * * @param certainty a measure of the uncertainty that the caller is * willing to tolerate: if the call returns {@code true} * the probability that this BigInteger is prime exceeds * (1 - 1/2{@code certainty}). The execution time of * this method is proportional to the value of this parameter. * @return {@code true} if this BigInteger is probably prime, * {@code false} if it's definitely composite. * @throws ArithmeticException {@code this} is too large. * @implNote Due to the nature of the underlying primality test algorithm, * and depending on the size of {@code this} and {@code certainty}, * this method could consume a large amount of memory, up to * exhaustion of available heap space, or could run for a long time. */ public boolean isProbablePrime(int certainty) { if (certainty <= 0) return true; BigInteger w = this.abs(); if (w.equals(TWO)) return true; if (!w.testBit(0) || w.equals(ONE)) return false; if (w.bitLength() > PRIME_SEARCH_BIT_LENGTH_LIMIT + 1) { throw new ArithmeticException(); } return w.primeToCertainty(certainty, null); } // Comparison Operations /** * Compares this BigInteger with the specified BigInteger. This * method is provided in preference to individual methods for each * of the six boolean comparison operators ({@literal <}, ==, * {@literal >}, {@literal >=}, !=, {@literal <=}). The suggested * idiom for performing these comparisons is: {@code * (x.compareTo(y)} <op> {@code 0)}, where * <op> is one of the six comparison operators. * * @param val BigInteger to which this BigInteger is to be compared. * @return -1, 0 or 1 as this BigInteger is numerically less than, equal * to, or greater than {@code val}. */ public int compareTo(BigInteger val) { if (signum == val.signum) { return switch (signum) { case 1 -> compareMagnitude(val); case -1 -> val.compareMagnitude(this); default -> 0; }; } return signum > val.signum ? 1 : -1; } /** * Compares the magnitude array of this BigInteger with the specified * BigInteger's. This is the version of compareTo ignoring sign. * * @param val BigInteger whose magnitude array to be compared. * @return -1, 0 or 1 as this magnitude array is less than, equal to or * greater than the magnitude array for the specified BigInteger's. */ final int compareMagnitude(BigInteger val) { int[] m1 = mag; int len1 = m1.length; int[] m2 = val.mag; int len2 = m2.length; if (len1 < len2) return -1; if (len1 > len2) return 1; for (int i = 0; i < len1; i++) { int a = m1[i]; int b = m2[i]; if (a != b) return ((a & LONG_MASK) < (b & LONG_MASK)) ? -1 : 1; } return 0; } /** * Version of compareMagnitude that compares magnitude with long value. * val can't be Long.MIN_VALUE. */ final int compareMagnitude(long val) { assert val != Long.MIN_VALUE; int[] m1 = mag; int len = m1.length; if (len > 2) { return 1; } if (val < 0) { val = -val; } int highWord = (int)(val >>> 32); if (highWord == 0) { if (len < 1) return -1; if (len > 1) return 1; int a = m1[0]; int b = (int)val; if (a != b) { return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; } return 0; } else { if (len < 2) return -1; int a = m1[0]; int b = highWord; if (a != b) { return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; } a = m1[1]; b = (int)val; if (a != b) { return ((a & LONG_MASK) < (b & LONG_MASK))? -1 : 1; } return 0; } } /** * Compares this BigInteger with the specified Object for equality. * * @param x Object to which this BigInteger is to be compared. * @return {@code true} if and only if the specified Object is a * BigInteger whose value is numerically equal to this BigInteger. */ public boolean equals(Object x) { // This test is just an optimization, which may or may not help if (x == this) return true; if (!(x instanceof BigInteger xInt)) return false; if (xInt.signum != signum) return false; int[] m = mag; int len = m.length; int[] xm = xInt.mag; if (len != xm.length) return false; for (int i = 0; i < len; i++) if (xm[i] != m[i]) return false; return true; } /** * Returns the minimum of this BigInteger and {@code val}. * * @param val value with which the minimum is to be computed. * @return the BigInteger whose value is the lesser of this BigInteger and * {@code val}. If they are equal, either may be returned. */ public BigInteger min(BigInteger val) { return (compareTo(val) < 0 ? this : val); } /** * Returns the maximum of this BigInteger and {@code val}. * * @param val value with which the maximum is to be computed. * @return the BigInteger whose value is the greater of this and * {@code val}. If they are equal, either may be returned. */ public BigInteger max(BigInteger val) { return (compareTo(val) > 0 ? this : val); } // Hash Function /** * Returns the hash code for this BigInteger. * * @return hash code for this BigInteger. */ public int hashCode() { int hashCode = 0; for (int i=0; i < mag.length; i++) hashCode = (int)(31*hashCode + (mag[i] & LONG_MASK)); return hashCode * signum; } /** * Returns the String representation of this BigInteger in the * given radix. If the radix is outside the range from {@link * Character#MIN_RADIX} to {@link Character#MAX_RADIX} inclusive, * it will default to 10 (as is the case for * {@code Integer.toString}). The digit-to-character mapping * provided by {@code Character.forDigit} is used, and a minus * sign is prepended if appropriate. (This representation is * compatible with the {@link #BigInteger(String, int) (String, * int)} constructor.) * * @param radix radix of the String representation. * @return String representation of this BigInteger in the given radix. * @see Integer#toString * @see Character#forDigit * @see #BigInteger(java.lang.String, int) */ public String toString(int radix) { if (signum == 0) return ; if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; BigInteger abs = this.abs(); // Ensure buffer capacity sufficient to contain string representation // floor(bitLength*log(2)/log(radix)) + 1 // plus an additional character for the sign if negative. int b = abs.bitLength(); int numChars = (int)(Math.floor(b*LOG_TWO/logCache[radix]) + 1) + (signum < 0 ? 1 : 0); StringBuilder sb = new StringBuilder(numChars); if (signum < 0) { sb.append('-'); } // Use recursive toString. toString(abs, sb, radix, 0); return sb.toString(); } /** * If {@code numZeros > 0}, appends that many zeros to the * specified StringBuilder; otherwise, does nothing. * * @param buf The StringBuilder that will be appended to. * @param numZeros The number of zeros to append. */ private static void padWithZeros(StringBuilder buf, int numZeros) { while (numZeros >= NUM_ZEROS) { buf.append(ZEROS); numZeros -= NUM_ZEROS; } if (numZeros > 0) { buf.append(ZEROS, 0, numZeros); } } /** * This method is used to perform toString when arguments are small. * The value must be non-negative. If {@code digits <= 0} no padding * (pre-pending with zeros) will be effected. * * @param radix The base to convert to. * @param buf The StringBuilder that will be appended to in place. * @param digits The minimum number of digits to pad to. */ private void smallToString(int radix, StringBuilder buf, int digits) { assert signum >= 0; if (signum == 0) { padWithZeros(buf, digits); return; } // Compute upper bound on number of digit groups and allocate space int maxNumDigitGroups = (4*mag.length + 6)/7; long[] digitGroups = new long[maxNumDigitGroups]; // Translate number to string, a digit group at a time BigInteger tmp = this; int numGroups = 0; while (tmp.signum != 0) { BigInteger d = longRadix[radix]; MutableBigInteger q = new MutableBigInteger(), a = new MutableBigInteger(tmp.mag), b = new MutableBigInteger(d.mag); MutableBigInteger r = a.divide(b, q); BigInteger q2 = q.toBigInteger(tmp.signum * d.signum); BigInteger r2 = r.toBigInteger(tmp.signum * d.signum); digitGroups[numGroups++] = r2.longValue(); tmp = q2; } // Get string version of first digit group String s = Long.toString(digitGroups[numGroups-1], radix); // Pad with internal zeros if necessary. padWithZeros(buf, digits - (s.length() + (numGroups - 1)*digitsPerLong[radix])); // Put first digit group into result buffer buf.append(s); // Append remaining digit groups each padded with leading zeros for (int i=numGroups-2; i >= 0; i--) { // Prepend (any) leading zeros for this digit group s = Long.toString(digitGroups[i], radix); int numLeadingZeros = digitsPerLong[radix] - s.length(); if (numLeadingZeros != 0) { buf.append(ZEROS, 0, numLeadingZeros); } buf.append(s); } } /** * Converts the specified BigInteger to a string and appends to * {@code sb}. This implements the recursive Schoenhage algorithm * for base conversions. This method can only be called for non-negative * numbers. *

* See Knuth, Donald, _The Art of Computer Programming_, Vol. 2, * Answers to Exercises (4.4) Question 14. * * @param u The number to convert to a string. * @param sb The StringBuilder that will be appended to in place. * @param radix The base to convert to. * @param digits The minimum number of digits to pad to. */ private static void toString(BigInteger u, StringBuilder sb, int radix, int digits) { assert u.signum() >= 0; // If we're smaller than a certain threshold, use the smallToString // method, padding with leading zeroes when necessary unless we're // at the beginning of the string or digits <= 0. As u.signum() >= 0, // smallToString() will not prepend a negative sign. if (u.mag.length <= SCHOENHAGE_BASE_CONVERSION_THRESHOLD) { u.smallToString(radix, sb, digits); return; } // Calculate a value for n in the equation radix^(2^n) = u // and subtract 1 from that value. This is used to find the // cache index that contains the best value to divide u. int b = u.bitLength(); int n = (int) Math.round(Math.log(b * LOG_TWO / logCache[radix]) / LOG_TWO - 1.0); BigInteger v = getRadixConversionCache(radix, n); BigInteger[] results; results = u.divideAndRemainder(v); int expectedDigits = 1 << n; // Now recursively build the two halves of each number. toString(results[0], sb, radix, digits - expectedDigits); toString(results[1], sb, radix, expectedDigits); } /** * Returns the value radix^(2^exponent) from the cache. * If this value doesn't already exist in the cache, it is added. *

* This could be changed to a more complicated caching method using * {@code Future}. */ private static BigInteger getRadixConversionCache(int radix, int exponent) { BigInteger[] cacheLine = powerCache[radix]; // volatile read if (exponent < cacheLine.length) { return cacheLine[exponent]; } int oldLength = cacheLine.length; cacheLine = Arrays.copyOf(cacheLine, exponent + 1); for (int i = oldLength; i <= exponent; i++) { cacheLine[i] = cacheLine[i - 1].pow(2); } BigInteger[][] pc = powerCache; // volatile read again if (exponent >= pc[radix].length) { pc = pc.clone(); pc[radix] = cacheLine; powerCache = pc; // volatile write, publish } return cacheLine[exponent]; } /* Size of ZEROS string. */ private static int NUM_ZEROS = 63; /* ZEROS is a string of NUM_ZEROS consecutive zeros. */ private static final String ZEROS = .repeat(NUM_ZEROS); /** * Returns the decimal String representation of this BigInteger. * The digit-to-character mapping provided by * {@code Character.forDigit} is used, and a minus sign is * prepended if appropriate. (This representation is compatible * with the {@link #BigInteger(String) (String)} constructor, and * allows for String concatenation with Java's + operator.) * * @return decimal String representation of this BigInteger. * @see Character#forDigit * @see #BigInteger(java.lang.String) */ public String toString() { return toString(10); } /** * Returns a byte array containing the two's-complement * representation of this BigInteger. The byte array will be in * big-endian byte-order: the most significant byte is in * the zeroth element. The array will contain the minimum number * of bytes required to represent this BigInteger, including at * least one sign bit, which is {@code (ceil((this.bitLength() + * 1)/8))}. (This representation is compatible with the * {@link #BigInteger(byte[]) (byte[])} constructor.) * * @return a byte array containing the two's-complement representation of * this BigInteger. * @see #BigInteger(byte[]) */ public byte[] toByteArray() { int byteLen = bitLength()/8 + 1; byte[] byteArray = new byte[byteLen]; for (int i=byteLen-1, bytesCopied=4, nextInt=0, intIndex=0; i >= 0; i--) { if (bytesCopied == 4) { nextInt = getInt(intIndex++); bytesCopied = 1; } else { nextInt >>>= 8; bytesCopied++; } byteArray[i] = (byte)nextInt; } return byteArray; } /** * Converts this BigInteger to an {@code int}. This * conversion is analogous to a * narrowing primitive conversion from {@code long} to * {@code int} as defined in * The Java Language Specification: * if this BigInteger is too big to fit in an * {@code int}, only the low-order 32 bits are returned. * Note that this conversion can lose information about the * overall magnitude of the BigInteger value as well as return a * result with the opposite sign. * * @return this BigInteger converted to an {@code int}. * @see #intValueExact() * @jls 5.1.3 Narrowing Primitive Conversion */ public int intValue() { int result = 0; result = getInt(0); return result; } /** * Converts this BigInteger to a {@code long}. This * conversion is analogous to a * narrowing primitive conversion from {@code long} to * {@code int} as defined in * The Java Language Specification: * if this BigInteger is too big to fit in a * {@code long}, only the low-order 64 bits are returned. * Note that this conversion can lose information about the * overall magnitude of the BigInteger value as well as return a * result with the opposite sign. * * @return this BigInteger converted to a {@code long}. * @see #longValueExact() * @jls 5.1.3 Narrowing Primitive Conversion */ public long longValue() { long result = 0; for (int i=1; i >= 0; i--) result = (result << 32) + (getInt(i) & LONG_MASK); return result; } /** * Converts this BigInteger to a {@code float}. This * conversion is similar to the * narrowing primitive conversion from {@code double} to * {@code float} as defined in * The Java Language Specification: * if this BigInteger has too great a magnitude * to represent as a {@code float}, it will be converted to * {@link Float#NEGATIVE_INFINITY} or {@link * Float#POSITIVE_INFINITY} as appropriate. Note that even when * the return value is finite, this conversion can lose * information about the precision of the BigInteger value. * * @return this BigInteger converted to a {@code float}. * @jls 5.1.3 Narrowing Primitive Conversion */ public float floatValue() { if (signum == 0) { return 0.0f; } int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1; // exponent == floor(log2(abs(this))) if (exponent < Long.SIZE - 1) { return longValue(); } else if (exponent > Float.MAX_EXPONENT) { return signum > 0 ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY; } /* * We need the top SIGNIFICAND_WIDTH bits, including the * one bit. To make rounding easier, we pick out the top * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1 * bits, and signifFloor the top SIGNIFICAND_WIDTH. * * It helps to consider the real number signif = abs(this) * * 2^(SIGNIFICAND_WIDTH - 1 - exponent). */ int shift = exponent - FloatConsts.SIGNIFICAND_WIDTH; int twiceSignifFloor; // twiceSignifFloor will be == abs().shiftRight(shift).intValue() // We do the shift into an int directly to improve performance. int nBits = shift & 0x1f; int nBits2 = 32 - nBits; if (nBits == 0) { twiceSignifFloor = mag[0]; } else { twiceSignifFloor = mag[0] >>> nBits; if (twiceSignifFloor == 0) { twiceSignifFloor = (mag[0] << nBits2) | (mag[1] >>> nBits); } } int signifFloor = twiceSignifFloor >> 1; signifFloor &= FloatConsts.SIGNIF_BIT_MASK; // remove the implied bit /* * We round up if either the fractional part of signif is strictly * greater than 0.5 (which is true if the 0.5 bit is set and any lower * bit is set), or if the fractional part of signif is >= 0.5 and * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit * are set). This is equivalent to the desired HALF_EVEN rounding. */ boolean increment = (twiceSignifFloor & 1) != 0 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift); int signifRounded = increment ? signifFloor + 1 : signifFloor; int bits = ((exponent + FloatConsts.EXP_BIAS)) << (FloatConsts.SIGNIFICAND_WIDTH - 1); bits += signifRounded; /* * If signifRounded == 2^24, we'd need to set all of the significand * bits to zero and add 1 to the exponent. This is exactly the behavior * we get from just adding signifRounded to bits directly. If the * exponent is Float.MAX_EXPONENT, we round up (correctly) to * Float.POSITIVE_INFINITY. */ bits |= signum & FloatConsts.SIGN_BIT_MASK; return Float.intBitsToFloat(bits); } /** * Converts this BigInteger to a {@code double}. This * conversion is similar to the * narrowing primitive conversion from {@code double} to * {@code float} as defined in * The Java Language Specification: * if this BigInteger has too great a magnitude * to represent as a {@code double}, it will be converted to * {@link Double#NEGATIVE_INFINITY} or {@link * Double#POSITIVE_INFINITY} as appropriate. Note that even when * the return value is finite, this conversion can lose * information about the precision of the BigInteger value. * * @return this BigInteger converted to a {@code double}. * @jls 5.1.3 Narrowing Primitive Conversion */ public double doubleValue() { if (signum == 0) { return 0.0; } int exponent = ((mag.length - 1) << 5) + bitLengthForInt(mag[0]) - 1; // exponent == floor(log2(abs(this))Double) if (exponent < Long.SIZE - 1) { return longValue(); } else if (exponent > Double.MAX_EXPONENT) { return signum > 0 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY; } /* * We need the top SIGNIFICAND_WIDTH bits, including the * one bit. To make rounding easier, we pick out the top * SIGNIFICAND_WIDTH + 1 bits, so we have one to help us round up or * down. twiceSignifFloor will contain the top SIGNIFICAND_WIDTH + 1 * bits, and signifFloor the top SIGNIFICAND_WIDTH. * * It helps to consider the real number signif = abs(this) * * 2^(SIGNIFICAND_WIDTH - 1 - exponent). */ int shift = exponent - DoubleConsts.SIGNIFICAND_WIDTH; long twiceSignifFloor; // twiceSignifFloor will be == abs().shiftRight(shift).longValue() // We do the shift into a long directly to improve performance. int nBits = shift & 0x1f; int nBits2 = 32 - nBits; int highBits; int lowBits; if (nBits == 0) { highBits = mag[0]; lowBits = mag[1]; } else { highBits = mag[0] >>> nBits; lowBits = (mag[0] << nBits2) | (mag[1] >>> nBits); if (highBits == 0) { highBits = lowBits; lowBits = (mag[1] << nBits2) | (mag[2] >>> nBits); } } twiceSignifFloor = ((highBits & LONG_MASK) << 32) | (lowBits & LONG_MASK); long signifFloor = twiceSignifFloor >> 1; signifFloor &= DoubleConsts.SIGNIF_BIT_MASK; // remove the implied bit /* * We round up if either the fractional part of signif is strictly * greater than 0.5 (which is true if the 0.5 bit is set and any lower * bit is set), or if the fractional part of signif is >= 0.5 and * signifFloor is odd (which is true if both the 0.5 bit and the 1 bit * are set). This is equivalent to the desired HALF_EVEN rounding. */ boolean increment = (twiceSignifFloor & 1) != 0 && ((signifFloor & 1) != 0 || abs().getLowestSetBit() < shift); long signifRounded = increment ? signifFloor + 1 : signifFloor; long bits = (long) ((exponent + DoubleConsts.EXP_BIAS)) << (DoubleConsts.SIGNIFICAND_WIDTH - 1); bits += signifRounded; /* * If signifRounded == 2^53, we'd need to set all of the significand * bits to zero and add 1 to the exponent. This is exactly the behavior * we get from just adding signifRounded to bits directly. If the * exponent is Double.MAX_EXPONENT, we round up (correctly) to * Double.POSITIVE_INFINITY. */ bits |= signum & DoubleConsts.SIGN_BIT_MASK; return Double.longBitsToDouble(bits); } /** * Returns a copy of the input array stripped of any leading zero bytes. */ private static int[] stripLeadingZeroInts(int[] val) { int vlen = val.length; int keep; // Find first nonzero byte for (keep = 0; keep < vlen && val[keep] == 0; keep++) ; return java.util.Arrays.copyOfRange(val, keep, vlen); } /** * Returns the input array stripped of any leading zero bytes. * Since the source is trusted the copying may be skipped. */ private static int[] trustedStripLeadingZeroInts(int[] val) { int vlen = val.length; int keep; // Find first nonzero byte for (keep = 0; keep < vlen && val[keep] == 0; keep++) ; return keep == 0 ? val : java.util.Arrays.copyOfRange(val, keep, vlen); } private static int[] stripLeadingZeroBytes(byte[] a, int from, int len) { return stripLeadingZeroBytes(Integer.MIN_VALUE, a, from, len); } /* * Returns a copy of the input array stripped of any leading zero bytes. * The returned array is either empty, or its 0-th element is non-zero, * meeting the requirement for field mag (see comment on mag). * * The range [from, from + len) must be well-formed w.r.t. array a. * * b < -128 means that a[from] has not yet been read. * Otherwise, b must be a[from], have been read only once before invoking * this method, and len > 0 must hold. */ private static int[] stripLeadingZeroBytes(int b, byte[] a, int from, int len) { /* * Except for the first byte, each read access to the input array a * is of the form a[from++]. * The index from is never otherwise altered, except right below, * and only increases in steps of 1, always up to index to. * Hence, each byte in the array is read exactly once, from lower to * higher indices (from most to least significant byte). */ if (len == 0) { return ZERO.mag; } int to = from + len; if (b < -128) { b = a[from]; } /* Either way, a[from] has now been read exactly once, skip to next. */ ++from; /* * Set up the shortest int[] for the sequence of the bytes * b, a[from+1], ..., a[to-1] (len > 0) * Shortest means first skipping leading zeros. */ for (; b == 0 && from < to; b = a[from++]) ; //empty body if (b == 0) { /* Here, from == to as well. All bytes are zeros. */ return ZERO.mag; } /* * Allocate just enough ints to hold (to - from + 1) bytes, that is * ((to - from + 1) + 3) / 4 = (to - from) / 4 + 1 */ int[] res = new int[((to - from) >> 2) + 1]; /* * A is a group of 4 adjacent bytes aligned w.r.t. index to. * (Implied 0 bytes are prepended as needed.) * b is the most significant byte not 0. * Digit d0 spans the range of indices that includes current (from - 1). */ int d0 = b & 0xFF; while (((to - from) & 0x3) != 0) { d0 = d0 << 8 | a[from++] & 0xFF; } res[0] = d0; /* * Prepare the remaining digits. * (to - from) is a multiple of 4, so prepare an int for every 4 bytes. * This is a candidate for Unsafe.copy[Swap]Memory(). */ int i = 1; while (from < to) { res[i++] = a[from++] << 24 | (a[from++] & 0xFF) << 16 | (a[from++] & 0xFF) << 8 | (a[from++] & 0xFF); } return res; } /* * Takes an array a representing a negative 2's-complement number and * returns the minimal (no leading zero bytes) unsigned whose value is -a. * * len > 0 must hold. * The range [from, from + len) must be well-formed w.r.t. array a. * b is assumed to be the result of reading a[from] and to meet b < 0. */ private static int[] makePositive(int b, byte[] a, int from, int len) { /* * By assumption, b == a[from] < 0 and len > 0. * * First collect the bytes into the resulting array res. * Then convert res to two's complement. * * Except for b == a[from], each read access to the input array a * is of the form a[from++]. * The index from is never otherwise altered, except right below, * and only increases in steps of 1, always up to index to. * Hence, each byte in the array is read exactly once, from lower to * higher indices (from most to least significant byte). */ int to = from + len; /* b == a[from] has been read exactly once, skip to next index. */ ++from; /* Skip leading -1 bytes. */ for (; b == -1 && from < to; b = a[from++]) ; //empty body /* * A is a group of 4 adjacent bytes aligned w.r.t. index to. * b is the most significant byte not -1, or -1 only if from == to. * Digit d0 spans the range of indices that includes current (from - 1). * (Implied -1 bytes are prepended to array a as needed.) * It usually corresponds to res[0], except for the special case below. */ int d0 = -1 << 8 | b & 0xFF; while (((to - from) & 0x3) != 0) { d0 = d0 << 8 | (b = a[from++]) & 0xFF; } int f = from; // keeps the current from for sizing purposes later /* Skip zeros adjacent to d0, if at all. */ for (; b == 0 && from < to; b = a[from++]) ; //empty body /* * b is the most significant non-zero byte at or after (f - 1), * or 0 only if from == to. * Digit d spans the range of indices that includes (f - 1). */ int d = b & 0xFF; while (((to - from) & 0x3) != 0) { d = d << 8 | a[from++] & 0xFF; } /* * If the situation here is like this: * index: f to == from * ..., -1,-1, 0,0,0,0, 0,0,0,0, ..., 0,0,0,0 * digit: d0 d * then, as shown, the number of zeros is a positive multiple of 4. * The array res needs a minimal length of (1 + 1 + (to - f) / 4) * to accommodate the two's complement, including a leading 1. * In any other case, there is at least one byte that is non-zero. * The array for the two's complement has length (0 + 1 + (to - f) / 4). * c is 1, resp., 0 for the two situations. */ int c = (to - from | d0 | d) == 0 ? 1 : 0; int[] res = new int[c + 1 + ((to - f) >> 2)]; res[0] = c == 0 ? d0 : -1; int i = res.length - ((to - from) >> 2); if (i > 1) { res[i - 1] = d; } /* * Prepare the remaining digits. * (to - from) is a multiple of 4, so prepare an int for every 4 bytes. * This is a candidate for Unsafe.copy[Swap]Memory(). */ while (from < to) { res[i++] = a[from++] << 24 | (a[from++] & 0xFF) << 16 | (a[from++] & 0xFF) << 8 | (a[from++] & 0xFF); } /* Convert to two's complement. Here, i == res.length */ while (--i >= 0 && res[i] == 0) ; // empty body res[i] = -res[i]; while (--i >= 0) { res[i] = ~res[i]; } return res; } /** * Takes an array a representing a negative 2's-complement number and * returns the minimal (no leading zero ints) unsigned whose value is -a. */ private static int[] makePositive(int[] a) { int keep, j; // Find first non-sign (0xffffffff) int of input for (keep=0; keep < a.length && a[keep] == -1; keep++) ; /* Allocate output array. If all non-sign ints are 0x00, we must * allocate space for one extra output int. */ for (j=keep; j < a.length && a[j] == 0; j++) ; int extraInt = (j == a.length ? 1 : 0); int result[] = new int[a.length - keep + extraInt]; /* Copy one's complement of input into output, leaving extra * int (if it exists) == 0x00 */ for (int i = keep; i < a.length; i++) result[i - keep + extraInt] = ~a[i]; // Add one to one's complement to generate two's complement for (int i=result.length-1; ++result[i] == 0; i--) ; return result; } /* * The following two arrays are used for fast String conversions. Both * are indexed by radix. The first is the number of digits of the given * radix that can fit in a Java long without , i.e., the * highest integer n such that radix**n < 2**63. The second is the * , each of which * consists of the number of digits in the corresponding element in * digitsPerLong (longRadix[i] = i**digitPerLong[i]). Both arrays have * nonsense values in their 0 and 1 elements, as radixes 0 and 1 are not * used. */ private static int digitsPerLong[] = {0, 0, 62, 39, 31, 27, 24, 22, 20, 19, 18, 18, 17, 17, 16, 16, 15, 15, 15, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 12, 12}; private static BigInteger longRadix[] = {null, null, valueOf(0x4000000000000000L), valueOf(0x383d9170b85ff80bL), valueOf(0x4000000000000000L), valueOf(0x6765c793fa10079dL), valueOf(0x41c21cb8e1000000L), valueOf(0x3642798750226111L), valueOf(0x1000000000000000L), valueOf(0x12bf307ae81ffd59L), valueOf( 0xde0b6b3a7640000L), valueOf(0x4d28cb56c33fa539L), valueOf(0x1eca170c00000000L), valueOf(0x780c7372621bd74dL), valueOf(0x1e39a5057d810000L), valueOf(0x5b27ac993df97701L), valueOf(0x1000000000000000L), valueOf(0x27b95e997e21d9f1L), valueOf(0x5da0e1e53c5c8000L), valueOf( 0xb16a458ef403f19L), valueOf(0x16bcc41e90000000L), valueOf(0x2d04b7fdd9c0ef49L), valueOf(0x5658597bcaa24000L), valueOf( 0x6feb266931a75b7L), valueOf( 0xc29e98000000000L), valueOf(0x14adf4b7320334b9L), valueOf(0x226ed36478bfa000L), valueOf(0x383d9170b85ff80bL), valueOf(0x5a3c23e39c000000L), valueOf( 0x4e900abb53e6b71L), valueOf( 0x7600ec618141000L), valueOf( 0xaee5720ee830681L), valueOf(0x1000000000000000L), valueOf(0x172588ad4f5f0981L), valueOf(0x211e44f7d02c1000L), valueOf(0x2ee56725f06e5c71L), valueOf(0x41c21cb8e1000000L)}; /* * These two arrays are the integer analogue of above. */ private static int digitsPerInt[] = {0, 0, 30, 19, 15, 13, 11, 11, 10, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5}; private static int intRadix[] = {0, 0, 0x40000000, 0x4546b3db, 0x40000000, 0x48c27395, 0x159fd800, 0x75db9c97, 0x40000000, 0x17179149, 0x3b9aca00, 0xcc6db61, 0x19a10000, 0x309f1021, 0x57f6c100, 0xa2f1b6f, 0x10000000, 0x18754571, 0x247dbc80, 0x3547667b, 0x4c4b4000, 0x6b5a6e1d, 0x6c20a40, 0x8d2d931, 0xb640000, 0xe8d4a51, 0x1269ae40, 0x17179149, 0x1cb91000, 0x23744899, 0x2b73a840, 0x34e63b41, 0x40000000, 0x4cfa3cc1, 0x5c13d840, 0x6d91b519, 0x39aa400 }; /** * These routines provide access to the two's complement representation * of BigIntegers. */ /** * Returns the length of the two's complement representation in ints, * including space for at least one sign bit. */ private int intLength() { return (bitLength() >>> 5) + 1; } /* Returns sign bit */ private int signBit() { return signum < 0 ? 1 : 0; } /* Returns an int of sign bits */ private int signInt() { return signum < 0 ? -1 : 0; } /** * Returns the specified int of the little-endian two's complement * representation (int 0 is the least significant). The int number can * be arbitrarily high (values are logically preceded by infinitely many * sign ints). */ private int getInt(int n) { if (n < 0) return 0; if (n >= mag.length) return signInt(); int magInt = mag[mag.length-n-1]; return (signum >= 0 ? magInt : (n <= firstNonzeroIntNum() ? -magInt : ~magInt)); } /** * Returns the index of the int that contains the first nonzero int in the * little-endian binary representation of the magnitude (int 0 is the * least significant). If the magnitude is zero, return value is undefined. * *

Note: never used for a BigInteger with a magnitude of zero. * @see #getInt */ private int firstNonzeroIntNum() { int fn = firstNonzeroIntNumPlusTwo - 2; if (fn == -2) { // firstNonzeroIntNum not initialized yet // Search for the first nonzero int int i; int mlen = mag.length; for (i = mlen - 1; i >= 0 && mag[i] == 0; i--) ; fn = mlen - i - 1; firstNonzeroIntNumPlusTwo = fn + 2; // offset by two to initialize } return fn; } /** use serialVersionUID from JDK 1.1. for interoperability */ @java.io.Serial private static final long serialVersionUID = -8287574255936472291L; /** * Serializable fields for BigInteger. * * @serialField signum int * signum of this BigInteger * @serialField magnitude byte[] * magnitude array of this BigInteger * @serialField bitCount int * appears in the serialized form for backward compatibility * @serialField bitLength int * appears in the serialized form for backward compatibility * @serialField firstNonzeroByteNum int * appears in the serialized form for backward compatibility * @serialField lowestSetBit int * appears in the serialized form for backward compatibility */ @java.io.Serial private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(, Integer.TYPE), new ObjectStreamField(, byte[].class), new ObjectStreamField(, Integer.TYPE), new ObjectStreamField(, Integer.TYPE), new ObjectStreamField(, Integer.TYPE), new ObjectStreamField(, Integer.TYPE) }; /** * Reconstitute the {@code BigInteger} instance from a stream (that is, * deserialize it). The magnitude is read in as an array of bytes * for historical reasons, but it is converted to an array of ints * and the byte array is discarded. * Note: * The current convention is to initialize the cache fields, bitCountPlusOne, * bitLengthPlusOne and lowestSetBitPlusTwo, to 0 rather than some other * marker value. Therefore, no explicit action to set these fields needs to * be taken in readObject because those fields already have a 0 value by * default since defaultReadObject is not being used. * * @param s the stream being read. * @throws IOException if an I/O error occurs * @throws ClassNotFoundException if a serialized class cannot be loaded */ @java.io.Serial private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // prepare to read the alternate persistent fields ObjectInputStream.GetField fields = s.readFields(); // Read and validate the alternate persistent fields that we // care about, signum and magnitude // Read and validate signum int sign = fields.get(, -2); if (sign < -1 || sign > 1) { String message = ; if (fields.defaulted()) message = ; throw new java.io.StreamCorruptedException(message); } // Read and validate magnitude byte[] magnitude = (byte[])fields.get(, null); magnitude = magnitude.clone(); // defensive copy int[] mag = stripLeadingZeroBytes(magnitude, 0, magnitude.length); if ((mag.length == 0) != (sign == 0)) { String message = ; if (fields.defaulted()) message = ; throw new java.io.StreamCorruptedException(message); } // Equivalent to checkRange() on mag local without assigning // this.mag field if (mag.length > MAX_MAG_LENGTH || (mag.length == MAX_MAG_LENGTH && mag[0] < 0)) { throw new java.io.StreamCorruptedException(); } // Commit final fields via Unsafe UnsafeHolder.putSignAndMag(this, sign, mag); } /** * Serialization without data not supported for this class. */ @java.io.Serial private void readObjectNoData() throws ObjectStreamException { throw new InvalidObjectException(); } // Support for resetting final fields while deserializing private static class UnsafeHolder { private static final jdk.internal.misc.Unsafe unsafe = jdk.internal.misc.Unsafe.getUnsafe(); private static final long signumOffset = unsafe.objectFieldOffset(BigInteger.class, ); private static final long magOffset = unsafe.objectFieldOffset(BigInteger.class, ); static void putSignAndMag(BigInteger bi, int sign, int[] magnitude) { unsafe.putInt(bi, signumOffset, sign); unsafe.putReference(bi, magOffset, magnitude); } } /** * Save the {@code BigInteger} instance to a stream. The magnitude of a * {@code BigInteger} is serialized as a byte array for historical reasons. * To maintain compatibility with older implementations, the integers * -1, -1, -2, and -2 are written as the values of the obsolete fields * {@code bitCount}, {@code bitLength}, {@code lowestSetBit}, and * {@code firstNonzeroByteNum}, respectively. These values are compatible * with older implementations, but will be ignored by current * implementations. * * @param s the stream to serialize to. * @throws IOException if an I/O error occurs */ @java.io.Serial private void writeObject(ObjectOutputStream s) throws IOException { // set the values of the Serializable fields ObjectOutputStream.PutField fields = s.putFields(); fields.put(, signum); fields.put(, magSerializedForm()); // The values written for cached fields are compatible with older // versions, but are ignored in readObject so don't otherwise matter. fields.put(, -1); fields.put(, -1); fields.put(, -2); fields.put(, -2); // save them s.writeFields(); } /** * Returns the mag array as an array of bytes. */ private byte[] magSerializedForm() { int len = mag.length; int bitLen = (len == 0 ? 0 : ((len - 1) << 5) + bitLengthForInt(mag[0])); int byteLen = (bitLen + 7) >>> 3; byte[] result = new byte[byteLen]; for (int i = byteLen - 1, bytesCopied = 4, intIndex = len - 1, nextInt = 0; i >= 0; i--) { if (bytesCopied == 4) { nextInt = mag[intIndex--]; bytesCopied = 1; } else { nextInt >>>= 8; bytesCopied++; } result[i] = (byte)nextInt; } return result; } /** * Converts this {@code BigInteger} to a {@code long}, checking * for lost information. If the value of this {@code BigInteger} * is out of the range of the {@code long} type, then an * {@code ArithmeticException} is thrown. * * @return this {@code BigInteger} converted to a {@code long}. * @throws ArithmeticException if the value of {@code this} will * not exactly fit in a {@code long}. * @see BigInteger#longValue * @since 1.8 */ public long longValueExact() { if (mag.length <= 2 && bitLength() <= 63) return longValue(); else throw new ArithmeticException(); } /** * Converts this {@code BigInteger} to an {@code int}, checking * for lost information. If the value of this {@code BigInteger} * is out of the range of the {@code int} type, then an * {@code ArithmeticException} is thrown. * * @return this {@code BigInteger} converted to an {@code int}. * @throws ArithmeticException if the value of {@code this} will * not exactly fit in an {@code int}. * @see BigInteger#intValue * @since 1.8 */ public int intValueExact() { if (mag.length <= 1 && bitLength() <= 31) return intValue(); else throw new ArithmeticException(); } /** * Converts this {@code BigInteger} to a {@code short}, checking * for lost information. If the value of this {@code BigInteger} * is out of the range of the {@code short} type, then an * {@code ArithmeticException} is thrown. * * @return this {@code BigInteger} converted to a {@code short}. * @throws ArithmeticException if the value of {@code this} will * not exactly fit in a {@code short}. * @see BigInteger#shortValue * @since 1.8 */ public short shortValueExact() { if (mag.length <= 1 && bitLength() <= 31) { int value = intValue(); if (value >= Short.MIN_VALUE && value <= Short.MAX_VALUE) return shortValue(); } throw new ArithmeticException(); } /** * Converts this {@code BigInteger} to a {@code byte}, checking * for lost information. If the value of this {@code BigInteger} * is out of the range of the {@code byte} type, then an * {@code ArithmeticException} is thrown. * * @return this {@code BigInteger} converted to a {@code byte}. * @throws ArithmeticException if the value of {@code this} will * not exactly fit in a {@code byte}. * @see BigInteger#byteValue * @since 1.8 */ public byte byteValueExact() { if (mag.length <= 1 && bitLength() <= 31) { int value = intValue(); if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) return byteValue(); } throw new ArithmeticException(); } } /* * Copyright (c) 1996, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.RecordComponent; import java.lang.reflect.UndeclaredThrowableException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.security.AccessControlContext; import java.security.AccessController; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PermissionCollection; import java.security.Permissions; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import jdk.internal.misc.Unsafe; import jdk.internal.reflect.CallerSensitive; import jdk.internal.reflect.Reflection; import jdk.internal.reflect.ReflectionFactory; import jdk.internal.access.SharedSecrets; import jdk.internal.access.JavaSecurityAccess; import jdk.internal.util.ByteArray; import sun.reflect.misc.ReflectUtil; /** * Serialization's descriptor for classes. It contains the name and * serialVersionUID of the class. The ObjectStreamClass for a specific class * loaded in this Java VM can be found/created using the lookup method. * *

The algorithm to compute the SerialVersionUID is described in * * Java Object Serialization Specification, Section 4.6, . * * @spec serialization/index.html Java Object Serialization Specification * @author Mike Warres * @author Roger Riggs * @see ObjectStreamField * @see * Java Object Serialization Specification, Section 4, * @since 1.1 */ public final class ObjectStreamClass implements Serializable { /** serialPersistentFields value indicating no serializable fields */ public static final ObjectStreamField[] NO_FIELDS = new ObjectStreamField[0]; @java.io.Serial private static final long serialVersionUID = -6120832682080437368L; /** * {@code ObjectStreamClass} has no fields for default serialization. */ @java.io.Serial private static final ObjectStreamField[] serialPersistentFields = NO_FIELDS; /** reflection factory for obtaining serialization constructors */ @SuppressWarnings() private static final ReflectionFactory reflFactory = AccessController.doPrivileged( new ReflectionFactory.GetReflectionFactoryAction()); private static class Caches { /** cache mapping local classes -> descriptors */ static final ClassCache localDescs = new ClassCache<>() { @Override protected ObjectStreamClass computeValue(Class type) { return new ObjectStreamClass(type); } }; /** cache mapping field group/local desc pairs -> field reflectors */ static final ClassCache> reflectors = new ClassCache<>() { @Override protected Map computeValue(Class type) { return new ConcurrentHashMap<>(); } }; } /** class associated with this descriptor (if any) */ private Class cl; /** name of class represented by this descriptor */ private String name; /** serialVersionUID of represented class (null if not computed yet) */ private volatile Long suid; /** true if represents dynamic proxy class */ private boolean isProxy; /** true if represents enum type */ private boolean isEnum; /** true if represents record type */ private boolean isRecord; /** true if represented class implements Serializable */ private boolean serializable; /** true if represented class implements Externalizable */ private boolean externalizable; /** true if desc has data written by class-defined writeObject method */ private boolean hasWriteObjectData; /** * true if desc has externalizable data written in block data format; this * must be true by default to accommodate ObjectInputStream subclasses which * override readClassDescriptor() to return class descriptors obtained from * ObjectStreamClass.lookup() (see 4461737) */ private boolean hasBlockExternalData = true; /** * Contains information about InvalidClassException instances to be thrown * when attempting operations on an invalid class. Note that instances of * this class are immutable and are potentially shared among * ObjectStreamClass instances. */ private static class ExceptionInfo { private final String className; private final String message; ExceptionInfo(String cn, String msg) { className = cn; message = msg; } /** * Returns (does not throw) an InvalidClassException instance created * from the information in this object, suitable for being thrown by * the caller. */ InvalidClassException newInvalidClassException() { return new InvalidClassException(className, message); } } /** exception (if any) thrown while attempting to resolve class */ private ClassNotFoundException resolveEx; /** exception (if any) to throw if non-enum deserialization attempted */ private ExceptionInfo deserializeEx; /** exception (if any) to throw if non-enum serialization attempted */ private ExceptionInfo serializeEx; /** exception (if any) to throw if default serialization attempted */ private ExceptionInfo defaultSerializeEx; /** serializable fields */ private ObjectStreamField[] fields; /** aggregate marshalled size of primitive fields */ private int primDataSize; /** number of non-primitive fields */ private int numObjFields; /** reflector for setting/getting serializable field values */ private FieldReflector fieldRefl; /** data layout of serialized objects described by this class desc */ private volatile ClassDataSlot[] dataLayout; /** serialization-appropriate constructor, or null if none */ private Constructor cons; /** record canonical constructor (shared among OSCs for same class), or null */ private MethodHandle canonicalCtr; /** cache of record deserialization constructors per unique set of stream fields * (shared among OSCs for same class), or null */ private DeserializationConstructorsCache deserializationCtrs; /** session-cache of record deserialization constructor * (in de-serialized OSC only), or null */ private MethodHandle deserializationCtr; /** protection domains that need to be checked when calling the constructor */ private ProtectionDomain[] domains; /** class-defined writeObject method, or null if none */ private Method writeObjectMethod; /** class-defined readObject method, or null if none */ private Method readObjectMethod; /** class-defined readObjectNoData method, or null if none */ private Method readObjectNoDataMethod; /** class-defined writeReplace method, or null if none */ private Method writeReplaceMethod; /** class-defined readResolve method, or null if none */ private Method readResolveMethod; /** local class descriptor for represented class (may point to self) */ private ObjectStreamClass localDesc; /** superclass descriptor appearing in stream */ private ObjectStreamClass superDesc; /** true if, and only if, the object has been correctly initialized */ private boolean initialized; /** * Initializes native code. */ private static native void initNative(); static { initNative(); } /** * Find the descriptor for a class that can be serialized. Creates an * ObjectStreamClass instance if one does not exist yet for class. Null is * returned if the specified class does not implement java.io.Serializable * or java.io.Externalizable. * * @param cl class for which to get the descriptor * @return the class descriptor for the specified class */ public static ObjectStreamClass lookup(Class cl) { return lookup(cl, false); } /** * Returns the descriptor for any class, regardless of whether it * implements {@link Serializable}. * * @param cl class for which to get the descriptor * @return the class descriptor for the specified class * @since 1.6 */ public static ObjectStreamClass lookupAny(Class cl) { return lookup(cl, true); } /** * Returns the name of the class described by this descriptor. * This method returns the name of the class in the format that * is used by the {@link Class#getName} method. * * @return a string representing the name of the class */ public String getName() { return name; } /** * Return the serialVersionUID for this class. The serialVersionUID * defines a set of classes all with the same name that have evolved from a * common root class and agree to be serialized and deserialized using a * common format. NonSerializable classes have a serialVersionUID of 0L. * * @return the SUID of the class described by this descriptor */ @SuppressWarnings() public long getSerialVersionUID() { // REMIND: synchronize instead of relying on volatile? if (suid == null) { if (isRecord) return 0L; suid = AccessController.doPrivileged( new PrivilegedAction() { public Long run() { return computeDefaultSUID(cl); } } ); } return suid.longValue(); } /** * Return the class in the local VM that this version is mapped to. Null * is returned if there is no corresponding local class. * * @return the {@code Class} instance that this descriptor represents */ @SuppressWarnings() @CallerSensitive public Class forClass() { if (cl == null) { return null; } requireInitialized(); if (System.getSecurityManager() != null) { Class caller = Reflection.getCallerClass(); if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), cl.getClassLoader())) { ReflectUtil.checkPackageAccess(cl); } } return cl; } /** * Return an array of the fields of this serializable class. * * @return an array containing an element for each persistent field of * this class. Returns an array of length zero if there are no * fields. * @since 1.2 */ public ObjectStreamField[] getFields() { return getFields(true); } /** * Get the field of this class by name. * * @param name the name of the data field to look for * @return The ObjectStreamField object of the named field or null if * there is no such named field. */ public ObjectStreamField getField(String name) { return getField(name, null); } /** * Return a string describing this ObjectStreamClass. */ public String toString() { return name + + getSerialVersionUID() + ; } /** * Looks up and returns class descriptor for given class, or null if class * is non-serializable and is set to false. * * @param cl class to look up * @param all if true, return descriptors for all classes; if false, only * return descriptors for serializable classes */ static ObjectStreamClass lookup(Class cl, boolean all) { if (!(all || Serializable.class.isAssignableFrom(cl))) { return null; } return Caches.localDescs.get(cl); } /** * Creates local class descriptor representing given class. */ @SuppressWarnings() private ObjectStreamClass(final Class cl) { this.cl = cl; name = cl.getName(); isProxy = Proxy.isProxyClass(cl); isEnum = Enum.class.isAssignableFrom(cl); isRecord = cl.isRecord(); serializable = Serializable.class.isAssignableFrom(cl); externalizable = Externalizable.class.isAssignableFrom(cl); Class superCl = cl.getSuperclass(); superDesc = (superCl != null) ? lookup(superCl, false) : null; localDesc = this; if (serializable) { AccessController.doPrivileged(new PrivilegedAction<>() { public Void run() { if (isEnum) { suid = 0L; fields = NO_FIELDS; return null; } if (cl.isArray()) { fields = NO_FIELDS; return null; } suid = getDeclaredSUID(cl); try { fields = getSerialFields(cl); computeFieldOffsets(); } catch (InvalidClassException e) { serializeEx = deserializeEx = new ExceptionInfo(e.classname, e.getMessage()); fields = NO_FIELDS; } if (isRecord) { canonicalCtr = canonicalRecordCtr(cl); deserializationCtrs = new DeserializationConstructorsCache(); } else if (externalizable) { cons = getExternalizableConstructor(cl); } else { cons = getSerializableConstructor(cl); writeObjectMethod = getPrivateMethod(cl, , new Class[] { ObjectOutputStream.class }, Void.TYPE); readObjectMethod = getPrivateMethod(cl, , new Class[] { ObjectInputStream.class }, Void.TYPE); readObjectNoDataMethod = getPrivateMethod( cl, , null, Void.TYPE); hasWriteObjectData = (writeObjectMethod != null); } domains = getProtectionDomains(cons, cl); writeReplaceMethod = getInheritableMethod( cl, , null, Object.class); readResolveMethod = getInheritableMethod( cl, , null, Object.class); return null; } }); } else { suid = 0L; fields = NO_FIELDS; } try { fieldRefl = getReflector(fields, this); } catch (InvalidClassException ex) { // field mismatches impossible when matching local fields vs. self throw new InternalError(ex); } if (deserializeEx == null) { if (isEnum) { deserializeEx = new ExceptionInfo(name, ); } else if (cons == null && !isRecord) { deserializeEx = new ExceptionInfo(name, ); } } if (isRecord && canonicalCtr == null) { deserializeEx = new ExceptionInfo(name, ); } else { for (int i = 0; i < fields.length; i++) { if (fields[i].getField() == null) { defaultSerializeEx = new ExceptionInfo( name, ); } } } initialized = true; } /** * Creates blank class descriptor which should be initialized via a * subsequent call to initProxy(), initNonProxy() or readNonProxy(). */ ObjectStreamClass() { } /** * Creates a PermissionDomain that grants no permission. */ private ProtectionDomain noPermissionsDomain() { PermissionCollection perms = new Permissions(); perms.setReadOnly(); return new ProtectionDomain(null, perms); } /** * Aggregate the ProtectionDomains of all the classes that separate * a concrete class {@code cl} from its ancestor's class declaring * a constructor {@code cons}. * * If {@code cl} is defined by the boot loader, or the constructor * {@code cons} is declared by {@code cl}, or if there is no security * manager, then this method does nothing and {@code null} is returned. * * @param cons A constructor declared by {@code cl} or one of its * ancestors. * @param cl A concrete class, which is either the class declaring * the constructor {@code cons}, or a serializable subclass * of that class. * @return An array of ProtectionDomain representing the set of * ProtectionDomain that separate the concrete class {@code cl} * from its ancestor's declaring {@code cons}, or {@code null}. */ @SuppressWarnings() private ProtectionDomain[] getProtectionDomains(Constructor cons, Class cl) { ProtectionDomain[] domains = null; if (cons != null && cl.getClassLoader() != null && System.getSecurityManager() != null) { Class cls = cl; Class fnscl = cons.getDeclaringClass(); Set pds = null; while (cls != fnscl) { ProtectionDomain pd = cls.getProtectionDomain(); if (pd != null) { if (pds == null) pds = new HashSet<>(); pds.add(pd); } cls = cls.getSuperclass(); if (cls == null) { // that's not supposed to happen // make a ProtectionDomain with no permission. // should we throw instead? if (pds == null) pds = new HashSet<>(); else pds.clear(); pds.add(noPermissionsDomain()); break; } } if (pds != null) { domains = pds.toArray(new ProtectionDomain[0]); } } return domains; } /** * Initializes class descriptor representing a proxy class. */ void initProxy(Class cl, ClassNotFoundException resolveEx, ObjectStreamClass superDesc) throws InvalidClassException { ObjectStreamClass osc = null; if (cl != null) { osc = lookup(cl, true); if (!osc.isProxy) { throw new InvalidClassException( ); } } this.cl = cl; this.resolveEx = resolveEx; this.superDesc = superDesc; isProxy = true; serializable = true; suid = 0L; fields = NO_FIELDS; if (osc != null) { localDesc = osc; name = localDesc.name; externalizable = localDesc.externalizable; writeReplaceMethod = localDesc.writeReplaceMethod; readResolveMethod = localDesc.readResolveMethod; deserializeEx = localDesc.deserializeEx; domains = localDesc.domains; cons = localDesc.cons; } fieldRefl = getReflector(fields, localDesc); initialized = true; } /** * Initializes class descriptor representing a non-proxy class. */ void initNonProxy(ObjectStreamClass model, Class cl, ClassNotFoundException resolveEx, ObjectStreamClass superDesc) throws InvalidClassException { long suid = model.getSerialVersionUID(); ObjectStreamClass osc = null; if (cl != null) { osc = lookup(cl, true); if (osc.isProxy) { throw new InvalidClassException( ); } if (model.isEnum != osc.isEnum) { throw new InvalidClassException(model.isEnum ? : ); } if (model.serializable == osc.serializable && !cl.isArray() && !cl.isRecord() && suid != osc.getSerialVersionUID()) { throw new InvalidClassException(osc.name, + + suid + + osc.getSerialVersionUID()); } if (!classNamesEqual(model.name, osc.name)) { throw new InvalidClassException(osc.name, + ); } if (!model.isEnum) { if ((model.serializable == osc.serializable) && (model.externalizable != osc.externalizable)) { throw new InvalidClassException(osc.name, ); } if ((model.serializable != osc.serializable) || (model.externalizable != osc.externalizable) || !(model.serializable || model.externalizable)) { deserializeEx = new ExceptionInfo( osc.name, ); } } } this.cl = cl; this.resolveEx = resolveEx; this.superDesc = superDesc; name = model.name; this.suid = suid; isProxy = false; isEnum = model.isEnum; serializable = model.serializable; externalizable = model.externalizable; hasBlockExternalData = model.hasBlockExternalData; hasWriteObjectData = model.hasWriteObjectData; fields = model.fields; primDataSize = model.primDataSize; numObjFields = model.numObjFields; if (osc != null) { localDesc = osc; isRecord = localDesc.isRecord; // canonical record constructor is shared canonicalCtr = localDesc.canonicalCtr; // cache of deserialization constructors is shared deserializationCtrs = localDesc.deserializationCtrs; writeObjectMethod = localDesc.writeObjectMethod; readObjectMethod = localDesc.readObjectMethod; readObjectNoDataMethod = localDesc.readObjectNoDataMethod; writeReplaceMethod = localDesc.writeReplaceMethod; readResolveMethod = localDesc.readResolveMethod; if (deserializeEx == null) { deserializeEx = localDesc.deserializeEx; } domains = localDesc.domains; assert cl.isRecord() ? localDesc.cons == null : true; cons = localDesc.cons; } fieldRefl = getReflector(fields, localDesc); // reassign to matched fields so as to reflect local unshared settings fields = fieldRefl.getFields(); initialized = true; } /** * Reads non-proxy class descriptor information from given input stream. * The resulting class descriptor is not fully functional; it can only be * used as input to the ObjectInputStream.resolveClass() and * ObjectStreamClass.initNonProxy() methods. */ void readNonProxy(ObjectInputStream in) throws IOException, ClassNotFoundException { name = in.readUTF(); suid = in.readLong(); isProxy = false; byte flags = in.readByte(); hasWriteObjectData = ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0); hasBlockExternalData = ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0); externalizable = ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0); boolean sflag = ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0); if (externalizable && sflag) { throw new InvalidClassException( name, ); } serializable = externalizable || sflag; isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0); if (isEnum && suid.longValue() != 0L) { throw new InvalidClassException(name, + suid); } int numFields = in.readShort(); if (isEnum && numFields != 0) { throw new InvalidClassException(name, + numFields); } fields = (numFields > 0) ? new ObjectStreamField[numFields] : NO_FIELDS; for (int i = 0; i < numFields; i++) { char tcode = (char) in.readByte(); String fname = in.readUTF(); String signature = ((tcode == 'L') || (tcode == '[')) ? in.readTypeString() : String.valueOf(tcode); try { fields[i] = new ObjectStreamField(fname, signature, false); } catch (RuntimeException e) { throw new InvalidClassException(name, + fname, e); } } computeFieldOffsets(); } /** * Writes non-proxy class descriptor information to given output stream. */ void writeNonProxy(ObjectOutputStream out) throws IOException { out.writeUTF(name); out.writeLong(getSerialVersionUID()); byte flags = 0; if (externalizable) { flags |= ObjectStreamConstants.SC_EXTERNALIZABLE; int protocol = out.getProtocolVersion(); if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) { flags |= ObjectStreamConstants.SC_BLOCK_DATA; } } else if (serializable) { flags |= ObjectStreamConstants.SC_SERIALIZABLE; } if (hasWriteObjectData) { flags |= ObjectStreamConstants.SC_WRITE_METHOD; } if (isEnum) { flags |= ObjectStreamConstants.SC_ENUM; } out.writeByte(flags); out.writeShort(fields.length); for (int i = 0; i < fields.length; i++) { ObjectStreamField f = fields[i]; out.writeByte(f.getTypeCode()); out.writeUTF(f.getName()); if (!f.isPrimitive()) { out.writeTypeString(f.getTypeString()); } } } /** * Returns ClassNotFoundException (if any) thrown while attempting to * resolve local class corresponding to this class descriptor. */ ClassNotFoundException getResolveException() { return resolveEx; } /** * Throws InternalError if not initialized. */ private final void requireInitialized() { if (!initialized) throw new InternalError(); } /** * Throws InvalidClassException if not initialized. * To be called in cases where an uninitialized class descriptor indicates * a problem in the serialization stream. */ final void checkInitialized() throws InvalidClassException { if (!initialized) { throw new InvalidClassException(); } } /** * Throws an InvalidClassException if object instances referencing this * class descriptor should not be allowed to deserialize. This method does * not apply to deserialization of enum constants. */ void checkDeserialize() throws InvalidClassException { requireInitialized(); if (deserializeEx != null) { throw deserializeEx.newInvalidClassException(); } } /** * Throws an InvalidClassException if objects whose class is represented by * this descriptor should not be allowed to serialize. This method does * not apply to serialization of enum constants. */ void checkSerialize() throws InvalidClassException { requireInitialized(); if (serializeEx != null) { throw serializeEx.newInvalidClassException(); } } /** * Throws an InvalidClassException if objects whose class is represented by * this descriptor should not be permitted to use default serialization * (e.g., if the class declares serializable fields that do not correspond * to actual fields, and hence must use the GetField API). This method * does not apply to deserialization of enum constants. */ void checkDefaultSerialize() throws InvalidClassException { requireInitialized(); if (defaultSerializeEx != null) { throw defaultSerializeEx.newInvalidClassException(); } } /** * Returns superclass descriptor. Note that on the receiving side, the * superclass descriptor may be bound to a class that is not a superclass * of the subclass descriptor's bound class. */ ObjectStreamClass getSuperDesc() { requireInitialized(); return superDesc; } /** * Returns the class descriptor for the class associated with this * class descriptor (i.e., the result of * ObjectStreamClass.lookup(this.forClass())) or null if there is no class * associated with this descriptor. */ ObjectStreamClass getLocalDesc() { requireInitialized(); return localDesc; } /** * Returns arrays of ObjectStreamFields representing the serializable * fields of the represented class. If copy is true, a clone of this class * descriptor's field array is returned, otherwise the array itself is * returned. */ ObjectStreamField[] getFields(boolean copy) { return copy ? fields.clone() : fields; } /** * Looks up a serializable field of the represented class by name and type. * A specified type of null matches all types, Object.class matches all * non-primitive types, and any other non-null type matches assignable * types only. Returns matching field, or null if no match found. */ ObjectStreamField getField(String name, Class type) { for (int i = 0; i < fields.length; i++) { ObjectStreamField f = fields[i]; if (f.getName().equals(name)) { if (type == null || (type == Object.class && !f.isPrimitive())) { return f; } Class ftype = f.getType(); if (ftype != null && type.isAssignableFrom(ftype)) { return f; } } } return null; } /** * Returns true if class descriptor represents a dynamic proxy class, false * otherwise. */ boolean isProxy() { requireInitialized(); return isProxy; } /** * Returns true if class descriptor represents an enum type, false * otherwise. */ boolean isEnum() { requireInitialized(); return isEnum; } /** * Returns true if class descriptor represents a record type, false * otherwise. */ boolean isRecord() { requireInitialized(); return isRecord; } /** * Returns true if represented class implements Externalizable, false * otherwise. */ boolean isExternalizable() { requireInitialized(); return externalizable; } /** * Returns true if represented class implements Serializable, false * otherwise. */ boolean isSerializable() { requireInitialized(); return serializable; } /** * Returns true if class descriptor represents externalizable class that * has written its data in 1.2 (block data) format, false otherwise. */ boolean hasBlockExternalData() { requireInitialized(); return hasBlockExternalData; } /** * Returns true if class descriptor represents serializable (but not * externalizable) class which has written its data via a custom * writeObject() method, false otherwise. */ boolean hasWriteObjectData() { requireInitialized(); return hasWriteObjectData; } /** * Returns true if represented class is serializable/externalizable and can * be instantiated by the serialization runtime--i.e., if it is * externalizable and defines a public no-arg constructor, or if it is * non-externalizable and its first non-serializable superclass defines an * accessible no-arg constructor. Otherwise, returns false. */ boolean isInstantiable() { requireInitialized(); return (cons != null); } /** * Returns true if represented class is serializable (but not * externalizable) and defines a conformant writeObject method. Otherwise, * returns false. */ boolean hasWriteObjectMethod() { requireInitialized(); return (writeObjectMethod != null); } /** * Returns true if represented class is serializable (but not * externalizable) and defines a conformant readObject method. Otherwise, * returns false. */ boolean hasReadObjectMethod() { requireInitialized(); return (readObjectMethod != null); } /** * Returns true if represented class is serializable (but not * externalizable) and defines a conformant readObjectNoData method. * Otherwise, returns false. */ boolean hasReadObjectNoDataMethod() { requireInitialized(); return (readObjectNoDataMethod != null); } /** * Returns true if represented class is serializable or externalizable and * defines a conformant writeReplace method. Otherwise, returns false. */ boolean hasWriteReplaceMethod() { requireInitialized(); return (writeReplaceMethod != null); } /** * Returns true if represented class is serializable or externalizable and * defines a conformant readResolve method. Otherwise, returns false. */ boolean hasReadResolveMethod() { requireInitialized(); return (readResolveMethod != null); } /** * Creates a new instance of the represented class. If the class is * externalizable, invokes its public no-arg constructor; otherwise, if the * class is serializable, invokes the no-arg constructor of the first * non-serializable superclass. Throws UnsupportedOperationException if * this class descriptor is not associated with a class, if the associated * class is non-serializable or if the appropriate no-arg constructor is * inaccessible/unavailable. */ @SuppressWarnings() Object newInstance() throws InstantiationException, InvocationTargetException, UnsupportedOperationException { requireInitialized(); if (cons != null) { try { if (domains == null || domains.length == 0) { return cons.newInstance(); } else { JavaSecurityAccess jsa = SharedSecrets.getJavaSecurityAccess(); PrivilegedAction pea = () -> { try { return cons.newInstance(); } catch (InstantiationException | InvocationTargetException | IllegalAccessException x) { throw new UndeclaredThrowableException(x); } }; // Can't use PrivilegedExceptionAction with jsa try { return jsa.doIntersectionPrivilege(pea, AccessController.getContext(), new AccessControlContext(domains)); } catch (UndeclaredThrowableException x) { Throwable cause = x.getCause(); if (cause instanceof InstantiationException ie) throw ie; if (cause instanceof InvocationTargetException ite) throw ite; if (cause instanceof IllegalAccessException iae) throw iae; // not supposed to happen throw x; } } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause instanceof Error err) throw err; else throw ex; } catch (InstantiationError err) { var ex = new InstantiationException(); ex.initCause(err); throw ex; } } else { throw new UnsupportedOperationException(); } } /** * Invokes the writeObject method of the represented serializable class. * Throws UnsupportedOperationException if this class descriptor is not * associated with a class, or if the class is externalizable, * non-serializable or does not define writeObject. */ void invokeWriteObject(Object obj, ObjectOutputStream out) throws IOException, UnsupportedOperationException { requireInitialized(); if (writeObjectMethod != null) { try { writeObjectMethod.invoke(obj, new Object[]{ out }); } catch (InvocationTargetException ex) { Throwable th = ex.getCause(); if (th instanceof IOException) { throw (IOException) th; } else { throwMiscException(th); } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } } else { throw new UnsupportedOperationException(); } } /** * Invokes the readObject method of the represented serializable class. * Throws UnsupportedOperationException if this class descriptor is not * associated with a class, or if the class is externalizable, * non-serializable or does not define readObject. */ void invokeReadObject(Object obj, ObjectInputStream in) throws ClassNotFoundException, IOException, UnsupportedOperationException { requireInitialized(); if (readObjectMethod != null) { try { readObjectMethod.invoke(obj, new Object[]{ in }); } catch (InvocationTargetException ex) { Throwable th = ex.getCause(); if (th instanceof ClassNotFoundException) { throw (ClassNotFoundException) th; } else if (th instanceof IOException) { throw (IOException) th; } else { throwMiscException(th); } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } } else { throw new UnsupportedOperationException(); } } /** * Invokes the readObjectNoData method of the represented serializable * class. Throws UnsupportedOperationException if this class descriptor is * not associated with a class, or if the class is externalizable, * non-serializable or does not define readObjectNoData. */ void invokeReadObjectNoData(Object obj) throws IOException, UnsupportedOperationException { requireInitialized(); if (readObjectNoDataMethod != null) { try { readObjectNoDataMethod.invoke(obj, (Object[]) null); } catch (InvocationTargetException ex) { Throwable th = ex.getCause(); if (th instanceof ObjectStreamException) { throw (ObjectStreamException) th; } else { throwMiscException(th); } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } } else { throw new UnsupportedOperationException(); } } /** * Invokes the writeReplace method of the represented serializable class and * returns the result. Throws UnsupportedOperationException if this class * descriptor is not associated with a class, or if the class is * non-serializable or does not define writeReplace. */ Object invokeWriteReplace(Object obj) throws IOException, UnsupportedOperationException { requireInitialized(); if (writeReplaceMethod != null) { try { return writeReplaceMethod.invoke(obj, (Object[]) null); } catch (InvocationTargetException ex) { Throwable th = ex.getCause(); if (th instanceof ObjectStreamException) { throw (ObjectStreamException) th; } else { throwMiscException(th); throw new InternalError(th); // never reached } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } } else { throw new UnsupportedOperationException(); } } /** * Invokes the readResolve method of the represented serializable class and * returns the result. Throws UnsupportedOperationException if this class * descriptor is not associated with a class, or if the class is * non-serializable or does not define readResolve. */ Object invokeReadResolve(Object obj) throws IOException, UnsupportedOperationException { requireInitialized(); if (readResolveMethod != null) { try { return readResolveMethod.invoke(obj, (Object[]) null); } catch (InvocationTargetException ex) { Throwable th = ex.getCause(); if (th instanceof ObjectStreamException) { throw (ObjectStreamException) th; } else { throwMiscException(th); throw new InternalError(th); // never reached } } catch (IllegalAccessException ex) { // should not occur, as access checks have been suppressed throw new InternalError(ex); } } else { throw new UnsupportedOperationException(); } } /** * Class representing the portion of an object's serialized form allotted * to data described by a given class descriptor. If is false, * the object's serialized form does not contain data associated with the * class descriptor. */ static class ClassDataSlot { /** class descriptor this slot */ final ObjectStreamClass desc; /** true if serialized form includes data for this slot's descriptor */ final boolean hasData; ClassDataSlot(ObjectStreamClass desc, boolean hasData) { this.desc = desc; this.hasData = hasData; } } /** * Returns array of ClassDataSlot instances representing the data layout * (including superclass data) for serialized objects described by this * class descriptor. ClassDataSlots are ordered by inheritance with those * containing superclasses appearing first. The final * ClassDataSlot contains a reference to this descriptor. */ ClassDataSlot[] getClassDataLayout() throws InvalidClassException { // REMIND: synchronize instead of relying on volatile? if (dataLayout == null) { dataLayout = getClassDataLayout0(); } return dataLayout; } private ClassDataSlot[] getClassDataLayout0() throws InvalidClassException { ArrayList slots = new ArrayList<>(); Class start = cl, end = cl; // locate closest non-serializable superclass while (end != null && Serializable.class.isAssignableFrom(end)) { end = end.getSuperclass(); } HashSet oscNames = new HashSet<>(3); for (ObjectStreamClass d = this; d != null; d = d.superDesc) { if (oscNames.contains(d.name)) { throw new InvalidClassException(); } else { oscNames.add(d.name); } // search up inheritance hierarchy for class with matching name String searchName = (d.cl != null) ? d.cl.getName() : d.name; Class match = null; for (Class c = start; c != end; c = c.getSuperclass()) { if (searchName.equals(c.getName())) { match = c; break; } } // add slot for each unmatched class below match if (match != null) { for (Class c = start; c != match; c = c.getSuperclass()) { slots.add(new ClassDataSlot( ObjectStreamClass.lookup(c, true), false)); } start = match.getSuperclass(); } // record descriptor/class pairing slots.add(new ClassDataSlot(d.getVariantFor(match), true)); } // add slot for any leftover unmatched classes for (Class c = start; c != end; c = c.getSuperclass()) { slots.add(new ClassDataSlot( ObjectStreamClass.lookup(c, true), false)); } // order slots from superclass -> subclass Collections.reverse(slots); return slots.toArray(new ClassDataSlot[slots.size()]); } /** * Returns aggregate size (in bytes) of marshalled primitive field values * for represented class. */ int getPrimDataSize() { return primDataSize; } /** * Returns number of non-primitive serializable fields of represented * class. */ int getNumObjFields() { return numObjFields; } /** * Fetches the serializable primitive field values of object obj and * marshals them into byte array buf starting at offset 0. It is the * responsibility of the caller to ensure that obj is of the proper type if * non-null. */ void getPrimFieldValues(Object obj, byte[] buf) { fieldRefl.getPrimFieldValues(obj, buf); } /** * Sets the serializable primitive fields of object obj using values * unmarshalled from byte array buf starting at offset 0. It is the * responsibility of the caller to ensure that obj is of the proper type if * non-null. */ void setPrimFieldValues(Object obj, byte[] buf) { fieldRefl.setPrimFieldValues(obj, buf); } /** * Fetches the serializable object field values of object obj and stores * them in array vals starting at offset 0. It is the responsibility of * the caller to ensure that obj is of the proper type if non-null. */ void getObjFieldValues(Object obj, Object[] vals) { fieldRefl.getObjFieldValues(obj, vals); } /** * Checks that the given values, from array vals starting at offset 0, * are assignable to the given serializable object fields. * @throws ClassCastException if any value is not assignable */ void checkObjFieldValueTypes(Object obj, Object[] vals) { fieldRefl.checkObjectFieldValueTypes(obj, vals); } /** * Sets the serializable object fields of object obj using values from * array vals starting at offset 0. It is the responsibility of the caller * to ensure that obj is of the proper type if non-null. */ void setObjFieldValues(Object obj, Object[] vals) { fieldRefl.setObjFieldValues(obj, vals); } /** * Calculates and sets serializable field offsets, as well as primitive * data size and object field count totals. Throws InvalidClassException * if fields are illegally ordered. */ private void computeFieldOffsets() throws InvalidClassException { primDataSize = 0; numObjFields = 0; int firstObjIndex = -1; for (int i = 0; i < fields.length; i++) { ObjectStreamField f = fields[i]; switch (f.getTypeCode()) { case 'Z', 'B' -> f.setOffset(primDataSize++); case 'C', 'S' -> { f.setOffset(primDataSize); primDataSize += 2; } case 'I', 'F' -> { f.setOffset(primDataSize); primDataSize += 4; } case 'J', 'D' -> { f.setOffset(primDataSize); primDataSize += 8; } case '[', 'L' -> { f.setOffset(numObjFields++); if (firstObjIndex == -1) { firstObjIndex = i; } } default -> throw new InternalError(); } } if (firstObjIndex != -1 && firstObjIndex + numObjFields != fields.length) { throw new InvalidClassException(name, ); } } /** * If given class is the same as the class associated with this class * descriptor, returns reference to this class descriptor. Otherwise, * returns variant of this class descriptor bound to given class. */ private ObjectStreamClass getVariantFor(Class cl) throws InvalidClassException { if (this.cl == cl) { return this; } ObjectStreamClass desc = new ObjectStreamClass(); if (isProxy) { desc.initProxy(cl, null, superDesc); } else { desc.initNonProxy(this, cl, null, superDesc); } return desc; } /** * Returns public no-arg constructor of given class, or null if none found. * Access checks are disabled on the returned constructor (if any), since * the defining class may still be non-public. */ private static Constructor getExternalizableConstructor(Class cl) { try { Constructor cons = cl.getDeclaredConstructor((Class[]) null); cons.setAccessible(true); return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ? cons : null; } catch (NoSuchMethodException ex) { return null; } } /** * Returns subclass-accessible no-arg constructor of first non-serializable * superclass, or null if none found. Access checks are disabled on the * returned constructor (if any). */ private static Constructor getSerializableConstructor(Class cl) { return reflFactory.newConstructorForSerialization(cl); } /** * Returns the canonical constructor for the given record class, or null if * the not found ( which should never happen for correctly generated record * classes ). */ @SuppressWarnings() private static MethodHandle canonicalRecordCtr(Class cls) { assert cls.isRecord() : + cls; PrivilegedAction pa = () -> { Class[] paramTypes = Arrays.stream(cls.getRecordComponents()) .map(RecordComponent::getType) .toArray(Class[]::new); try { Constructor ctr = cls.getDeclaredConstructor(paramTypes); ctr.setAccessible(true); return MethodHandles.lookup().unreflectConstructor(ctr); } catch (IllegalAccessException | NoSuchMethodException e) { return null; } }; return AccessController.doPrivileged(pa); } /** * Returns the canonical constructor, if the local class equivalent of this * stream class descriptor is a record class, otherwise null. */ MethodHandle getRecordConstructor() { return canonicalCtr; } /** * Returns non-static, non-abstract method with given signature provided it * is defined by or accessible (via inheritance) by the given class, or * null if no match found. Access checks are disabled on the returned * method (if any). */ private static Method getInheritableMethod(Class cl, String name, Class[] argTypes, Class returnType) { Method meth = null; Class defCl = cl; while (defCl != null) { try { meth = defCl.getDeclaredMethod(name, argTypes); break; } catch (NoSuchMethodException ex) { defCl = defCl.getSuperclass(); } } if ((meth == null) || (meth.getReturnType() != returnType)) { return null; } meth.setAccessible(true); int mods = meth.getModifiers(); if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) { return null; } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) { return meth; } else if ((mods & Modifier.PRIVATE) != 0) { return (cl == defCl) ? meth : null; } else { return packageEquals(cl, defCl) ? meth : null; } } /** * Returns non-static private method with given signature defined by given * class, or null if none found. Access checks are disabled on the * returned method (if any). */ private static Method getPrivateMethod(Class cl, String name, Class[] argTypes, Class returnType) { try { Method meth = cl.getDeclaredMethod(name, argTypes); meth.setAccessible(true); int mods = meth.getModifiers(); return ((meth.getReturnType() == returnType) && ((mods & Modifier.STATIC) == 0) && ((mods & Modifier.PRIVATE) != 0)) ? meth : null; } catch (NoSuchMethodException ex) { return null; } } /** * Returns true if classes are defined in the same runtime package, false * otherwise. */ private static boolean packageEquals(Class cl1, Class cl2) { return cl1.getClassLoader() == cl2.getClassLoader() && cl1.getPackageName() == cl2.getPackageName(); } /** * Compares class names for equality, ignoring package names. Returns true * if class names equal, false otherwise. */ private static boolean classNamesEqual(String name1, String name2) { int idx1 = name1.lastIndexOf('.') + 1; int idx2 = name2.lastIndexOf('.') + 1; int len1 = name1.length() - idx1; int len2 = name2.length() - idx2; return len1 == len2 && name1.regionMatches(idx1, name2, idx2, len1); } /** * Returns JVM type signature for given list of parameters and return type. */ private static String getMethodSignature(Class[] paramTypes, Class retType) { StringBuilder sb = new StringBuilder(); sb.append('('); for (int i = 0; i < paramTypes.length; i++) { sb.append(paramTypes[i].descriptorString()); } sb.append(')'); sb.append(retType.descriptorString()); return sb.toString(); } /** * Convenience method for throwing an exception that is either a * RuntimeException, Error, or of some unexpected type (in which case it is * wrapped inside an IOException). */ private static void throwMiscException(Throwable th) throws IOException { if (th instanceof RuntimeException) { throw (RuntimeException) th; } else if (th instanceof Error) { throw (Error) th; } else { throw new IOException(, th); } } /** * Returns ObjectStreamField array describing the serializable fields of * the given class. Serializable fields backed by an actual field of the * class are represented by ObjectStreamFields with corresponding non-null * Field objects. Throws InvalidClassException if the (explicitly * declared) serializable fields are invalid. */ private static ObjectStreamField[] getSerialFields(Class cl) throws InvalidClassException { if (!Serializable.class.isAssignableFrom(cl)) return NO_FIELDS; ObjectStreamField[] fields; if (cl.isRecord()) { fields = getDefaultSerialFields(cl); Arrays.sort(fields); } else if (!Externalizable.class.isAssignableFrom(cl) && !Proxy.isProxyClass(cl) && !cl.isInterface()) { if ((fields = getDeclaredSerialFields(cl)) == null) { fields = getDefaultSerialFields(cl); } Arrays.sort(fields); } else { fields = NO_FIELDS; } return fields; } /** * Returns serializable fields of given class as defined explicitly by a * field, or null if no appropriate * field is defined. Serializable fields backed * by an actual field of the class are represented by ObjectStreamFields * with corresponding non-null Field objects. For compatibility with past * releases, a field with a null value is * considered equivalent to not declaring . Throws * InvalidClassException if the declared serializable fields are * invalid--e.g., if multiple fields share the same name. */ private static ObjectStreamField[] getDeclaredSerialFields(Class cl) throws InvalidClassException { ObjectStreamField[] serialPersistentFields = null; try { Field f = cl.getDeclaredField(); int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL; if ((f.getModifiers() & mask) == mask) { f.setAccessible(true); serialPersistentFields = (ObjectStreamField[]) f.get(null); } } catch (Exception ex) { } if (serialPersistentFields == null) { return null; } else if (serialPersistentFields.length == 0) { return NO_FIELDS; } ObjectStreamField[] boundFields = new ObjectStreamField[serialPersistentFields.length]; Set fieldNames = HashSet.newHashSet(serialPersistentFields.length); for (int i = 0; i < serialPersistentFields.length; i++) { ObjectStreamField spf = serialPersistentFields[i]; String fname = spf.getName(); if (fieldNames.contains(fname)) { throw new InvalidClassException( + fname); } fieldNames.add(fname); try { Field f = cl.getDeclaredField(fname); if ((f.getType() == spf.getType()) && ((f.getModifiers() & Modifier.STATIC) == 0)) { boundFields[i] = new ObjectStreamField(f, spf.isUnshared(), true); } } catch (NoSuchFieldException ex) { } if (boundFields[i] == null) { boundFields[i] = new ObjectStreamField( fname, spf.getType(), spf.isUnshared()); } } return boundFields; } /** * Returns array of ObjectStreamFields corresponding to all non-static * non-transient fields declared by given class. Each ObjectStreamField * contains a Field object for the field it represents. If no default * serializable fields exist, NO_FIELDS is returned. */ private static ObjectStreamField[] getDefaultSerialFields(Class cl) { Field[] clFields = cl.getDeclaredFields(); ArrayList list = new ArrayList<>(); int mask = Modifier.STATIC | Modifier.TRANSIENT; for (int i = 0; i < clFields.length; i++) { if ((clFields[i].getModifiers() & mask) == 0) { list.add(new ObjectStreamField(clFields[i], false, true)); } } int size = list.size(); return (size == 0) ? NO_FIELDS : list.toArray(new ObjectStreamField[size]); } /** * Returns explicit serial version UID value declared by given class, or * null if none. */ private static Long getDeclaredSUID(Class cl) { try { Field f = cl.getDeclaredField(); int mask = Modifier.STATIC | Modifier.FINAL; if ((f.getModifiers() & mask) == mask) { f.setAccessible(true); return f.getLong(null); } } catch (Exception ex) { } return null; } /** * Computes the default serial version UID value for the given class. */ private static long computeDefaultSUID(Class cl) { if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl)) { return 0L; } try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); dout.writeUTF(cl.getName()); int classMods = cl.getModifiers() & (Modifier.PUBLIC | Modifier.FINAL | Modifier.INTERFACE | Modifier.ABSTRACT); /* * compensate for javac bug in which ABSTRACT bit was set for an * interface only if the interface declared methods */ Method[] methods = cl.getDeclaredMethods(); if ((classMods & Modifier.INTERFACE) != 0) { classMods = (methods.length > 0) ? (classMods | Modifier.ABSTRACT) : (classMods & ~Modifier.ABSTRACT); } dout.writeInt(classMods); if (!cl.isArray()) { /* * compensate for change in 1.2FCS in which * Class.getInterfaces() was modified to return Cloneable and * Serializable for array classes. */ Class[] interfaces = cl.getInterfaces(); String[] ifaceNames = new String[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { ifaceNames[i] = interfaces[i].getName(); } Arrays.sort(ifaceNames); for (int i = 0; i < ifaceNames.length; i++) { dout.writeUTF(ifaceNames[i]); } } Field[] fields = cl.getDeclaredFields(); MemberSignature[] fieldSigs = new MemberSignature[fields.length]; for (int i = 0; i < fields.length; i++) { fieldSigs[i] = new MemberSignature(fields[i]); } Arrays.sort(fieldSigs, new Comparator<>() { public int compare(MemberSignature ms1, MemberSignature ms2) { return ms1.name.compareTo(ms2.name); } }); for (int i = 0; i < fieldSigs.length; i++) { MemberSignature sig = fieldSigs[i]; int mods = sig.member.getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT); if (((mods & Modifier.PRIVATE) == 0) || ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)) { dout.writeUTF(sig.name); dout.writeInt(mods); dout.writeUTF(sig.signature); } } if (hasStaticInitializer(cl)) { dout.writeUTF(); dout.writeInt(Modifier.STATIC); dout.writeUTF(); } Constructor[] cons = cl.getDeclaredConstructors(); MemberSignature[] consSigs = new MemberSignature[cons.length]; for (int i = 0; i < cons.length; i++) { consSigs[i] = new MemberSignature(cons[i]); } Arrays.sort(consSigs, new Comparator<>() { public int compare(MemberSignature ms1, MemberSignature ms2) { return ms1.signature.compareTo(ms2.signature); } }); for (int i = 0; i < consSigs.length; i++) { MemberSignature sig = consSigs[i]; int mods = sig.member.getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.ABSTRACT | Modifier.STRICT); if ((mods & Modifier.PRIVATE) == 0) { dout.writeUTF(); dout.writeInt(mods); dout.writeUTF(sig.signature.replace('/', '.')); } } MemberSignature[] methSigs = new MemberSignature[methods.length]; for (int i = 0; i < methods.length; i++) { methSigs[i] = new MemberSignature(methods[i]); } Arrays.sort(methSigs, new Comparator<>() { public int compare(MemberSignature ms1, MemberSignature ms2) { int comp = ms1.name.compareTo(ms2.name); if (comp == 0) { comp = ms1.signature.compareTo(ms2.signature); } return comp; } }); for (int i = 0; i < methSigs.length; i++) { MemberSignature sig = methSigs[i]; int mods = sig.member.getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.ABSTRACT | Modifier.STRICT); if ((mods & Modifier.PRIVATE) == 0) { dout.writeUTF(sig.name); dout.writeInt(mods); dout.writeUTF(sig.signature.replace('/', '.')); } } dout.flush(); MessageDigest md = MessageDigest.getInstance(); byte[] hashBytes = md.digest(bout.toByteArray()); long hash = 0; for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) { hash = (hash << 8) | (hashBytes[i] & 0xFF); } return hash; } catch (IOException ex) { throw new InternalError(ex); } catch (NoSuchAlgorithmException ex) { throw new SecurityException(ex.getMessage()); } } /** * Returns true if the given class defines a static initializer method, * false otherwise. */ private static native boolean hasStaticInitializer(Class cl); /** * Class for computing and caching field/constructor/method signatures * during serialVersionUID calculation. */ private static final class MemberSignature { public final Member member; public final String name; public final String signature; public MemberSignature(Field field) { member = field; name = field.getName(); signature = field.getType().descriptorString(); } public MemberSignature(Constructor cons) { member = cons; name = cons.getName(); signature = getMethodSignature( cons.getParameterTypes(), Void.TYPE); } public MemberSignature(Method meth) { member = meth; name = meth.getName(); signature = getMethodSignature( meth.getParameterTypes(), meth.getReturnType()); } } /** * Class for setting and retrieving serializable field values in batch. */ // REMIND: dynamically generate these? private static final class FieldReflector { /** handle for performing unsafe operations */ private static final Unsafe UNSAFE = Unsafe.getUnsafe(); /** fields to operate on */ private final ObjectStreamField[] fields; /** number of primitive fields */ private final int numPrimFields; /** unsafe field keys for reading fields - may contain dupes */ private final long[] readKeys; /** unsafe fields keys for writing fields - no dupes */ private final long[] writeKeys; /** field data offsets */ private final int[] offsets; /** field type codes */ private final char[] typeCodes; /** field types */ private final Class[] types; /** * Constructs FieldReflector capable of setting/getting values from the * subset of fields whose ObjectStreamFields contain non-null * reflective Field objects. ObjectStreamFields with null Fields are * treated as filler, for which get operations return default values * and set operations discard given values. */ FieldReflector(ObjectStreamField[] fields) { this.fields = fields; int nfields = fields.length; readKeys = new long[nfields]; writeKeys = new long[nfields]; offsets = new int[nfields]; typeCodes = new char[nfields]; ArrayList> typeList = new ArrayList<>(); Set usedKeys = new HashSet<>(); for (int i = 0; i < nfields; i++) { ObjectStreamField f = fields[i]; Field rf = f.getField(); long key = (rf != null) ? UNSAFE.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET; readKeys[i] = key; writeKeys[i] = usedKeys.add(key) ? key : Unsafe.INVALID_FIELD_OFFSET; offsets[i] = f.getOffset(); typeCodes[i] = f.getTypeCode(); if (!f.isPrimitive()) { typeList.add((rf != null) ? rf.getType() : null); } } types = typeList.toArray(new Class[typeList.size()]); numPrimFields = nfields - types.length; } /** * Returns list of ObjectStreamFields representing fields operated on * by this reflector. The shared/unshared values and Field objects * contained by ObjectStreamFields in the list reflect their bindings * to locally defined serializable fields. */ ObjectStreamField[] getFields() { return fields; } /** * Fetches the serializable primitive field values of object obj and * marshals them into byte array buf starting at offset 0. The caller * is responsible for ensuring that obj is of the proper type. */ void getPrimFieldValues(Object obj, byte[] buf) { if (obj == null) { throw new NullPointerException(); } /* assuming checkDefaultSerialize() has been called on the class * descriptor this FieldReflector was obtained from, no field keys * in array should be equal to Unsafe.INVALID_FIELD_OFFSET. */ for (int i = 0; i < numPrimFields; i++) { long key = readKeys[i]; int off = offsets[i]; switch (typeCodes[i]) { case 'Z' -> ByteArray.setBoolean(buf, off, UNSAFE.getBoolean(obj, key)); case 'B' -> buf[off] = UNSAFE.getByte(obj, key); case 'C' -> ByteArray.setChar(buf, off, UNSAFE.getChar(obj, key)); case 'S' -> ByteArray.setShort(buf, off, UNSAFE.getShort(obj, key)); case 'I' -> ByteArray.setInt(buf, off, UNSAFE.getInt(obj, key)); case 'F' -> ByteArray.setFloat(buf, off, UNSAFE.getFloat(obj, key)); case 'J' -> ByteArray.setLong(buf, off, UNSAFE.getLong(obj, key)); case 'D' -> ByteArray.setDouble(buf, off, UNSAFE.getDouble(obj, key)); default -> throw new InternalError(); } } } /** * Sets the serializable primitive fields of object obj using values * unmarshalled from byte array buf starting at offset 0. The caller * is responsible for ensuring that obj is of the proper type. */ void setPrimFieldValues(Object obj, byte[] buf) { if (obj == null) { throw new NullPointerException(); } for (int i = 0; i < numPrimFields; i++) { long key = writeKeys[i]; if (key == Unsafe.INVALID_FIELD_OFFSET) { continue; // discard value } int off = offsets[i]; switch (typeCodes[i]) { case 'Z' -> UNSAFE.putBoolean(obj, key, ByteArray.getBoolean(buf, off)); case 'B' -> UNSAFE.putByte(obj, key, buf[off]); case 'C' -> UNSAFE.putChar(obj, key, ByteArray.getChar(buf, off)); case 'S' -> UNSAFE.putShort(obj, key, ByteArray.getShort(buf, off)); case 'I' -> UNSAFE.putInt(obj, key, ByteArray.getInt(buf, off)); case 'F' -> UNSAFE.putFloat(obj, key, ByteArray.getFloat(buf, off)); case 'J' -> UNSAFE.putLong(obj, key, ByteArray.getLong(buf, off)); case 'D' -> UNSAFE.putDouble(obj, key, ByteArray.getDouble(buf, off)); default -> throw new InternalError(); } } } /** * Fetches the serializable object field values of object obj and * stores them in array vals starting at offset 0. The caller is * responsible for ensuring that obj is of the proper type. */ void getObjFieldValues(Object obj, Object[] vals) { if (obj == null) { throw new NullPointerException(); } /* assuming checkDefaultSerialize() has been called on the class * descriptor this FieldReflector was obtained from, no field keys * in array should be equal to Unsafe.INVALID_FIELD_OFFSET. */ for (int i = numPrimFields; i < fields.length; i++) { vals[offsets[i]] = switch (typeCodes[i]) { case 'L', '[' -> UNSAFE.getReference(obj, readKeys[i]); default -> throw new InternalError(); }; } } /** * Checks that the given values, from array vals starting at offset 0, * are assignable to the given serializable object fields. * @throws ClassCastException if any value is not assignable */ void checkObjectFieldValueTypes(Object obj, Object[] vals) { setObjFieldValues(obj, vals, true); } /** * Sets the serializable object fields of object obj using values from * array vals starting at offset 0. The caller is responsible for * ensuring that obj is of the proper type; however, attempts to set a * field with a value of the wrong type will trigger an appropriate * ClassCastException. */ void setObjFieldValues(Object obj, Object[] vals) { setObjFieldValues(obj, vals, false); } private void setObjFieldValues(Object obj, Object[] vals, boolean dryRun) { if (obj == null) { throw new NullPointerException(); } for (int i = numPrimFields; i < fields.length; i++) { long key = writeKeys[i]; if (key == Unsafe.INVALID_FIELD_OFFSET) { continue; // discard value } switch (typeCodes[i]) { case 'L', '[' -> { Object val = vals[offsets[i]]; if (val != null && !types[i - numPrimFields].isInstance(val)) { Field f = fields[i].getField(); throw new ClassCastException( + val.getClass().getName() + + f.getDeclaringClass().getName() + + f.getName() + + f.getType().getName() + + obj.getClass().getName()); } if (!dryRun) UNSAFE.putReference(obj, key, val); } default -> throw new InternalError(); } } } } /** * Matches given set of serializable fields with serializable fields * described by the given local class descriptor, and returns a * FieldReflector instance capable of setting/getting values from the * subset of fields that match (non-matching fields are treated as filler, * for which get operations return default values and set operations * discard given values). Throws InvalidClassException if unresolvable * type conflicts exist between the two sets of fields. */ private static FieldReflector getReflector(ObjectStreamField[] fields, ObjectStreamClass localDesc) throws InvalidClassException { // class irrelevant if no fields Class cl = (localDesc != null && fields.length > 0) ? localDesc.cl : Void.class; var clReflectors = Caches.reflectors.get(cl); var key = new FieldReflectorKey(fields); var reflector = clReflectors.get(key); if (reflector == null) { reflector = new FieldReflector(matchFields(fields, localDesc)); var oldReflector = clReflectors.putIfAbsent(key, reflector); if (oldReflector != null) { reflector = oldReflector; } } return reflector; } /** * FieldReflector cache lookup key. Keys are considered equal if they * refer to equivalent field formats. */ private static class FieldReflectorKey { private final String[] sigs; private final int hash; FieldReflectorKey(ObjectStreamField[] fields) { sigs = new String[2 * fields.length]; for (int i = 0, j = 0; i < fields.length; i++) { ObjectStreamField f = fields[i]; sigs[j++] = f.getName(); sigs[j++] = f.getSignature(); } hash = Arrays.hashCode(sigs); } public int hashCode() { return hash; } public boolean equals(Object obj) { return obj == this || obj instanceof FieldReflectorKey other && Arrays.equals(sigs, other.sigs); } } /** * Matches given set of serializable fields with serializable fields * obtained from the given local class descriptor (which contain bindings * to reflective Field objects). Returns list of ObjectStreamFields in * which each ObjectStreamField whose signature matches that of a local * field contains a Field object for that field; unmatched * ObjectStreamFields contain null Field objects. Shared/unshared settings * of the returned ObjectStreamFields also reflect those of matched local * ObjectStreamFields. Throws InvalidClassException if unresolvable type * conflicts exist between the two sets of fields. */ private static ObjectStreamField[] matchFields(ObjectStreamField[] fields, ObjectStreamClass localDesc) throws InvalidClassException { ObjectStreamField[] localFields = (localDesc != null) ? localDesc.fields : NO_FIELDS; /* * Even if fields == localFields, we cannot simply return localFields * here. In previous implementations of serialization, * ObjectStreamField.getType() returned Object.class if the * ObjectStreamField represented a non-primitive field and belonged to * a non-local class descriptor. To preserve this (questionable) * behavior, the ObjectStreamField instances returned by matchFields * cannot report non-primitive types other than Object.class; hence * localFields cannot be returned directly. */ ObjectStreamField[] matches = new ObjectStreamField[fields.length]; for (int i = 0; i < fields.length; i++) { ObjectStreamField f = fields[i], m = null; for (int j = 0; j < localFields.length; j++) { ObjectStreamField lf = localFields[j]; if (f.getName().equals(lf.getName())) { if ((f.isPrimitive() || lf.isPrimitive()) && f.getTypeCode() != lf.getTypeCode()) { throw new InvalidClassException(localDesc.name, + f.getName()); } if (lf.getField() != null) { m = new ObjectStreamField( lf.getField(), lf.isUnshared(), false); } else { m = new ObjectStreamField( lf.getName(), lf.getSignature(), lf.isUnshared()); } } } if (m == null) { m = new ObjectStreamField( f.getName(), f.getSignature(), false); } m.setOffset(f.getOffset()); matches[i] = m; } return matches; } /** * A LRA cache of record deserialization constructors. */ @SuppressWarnings() private static final class DeserializationConstructorsCache extends ConcurrentHashMap { // keep max. 10 cached entries - when the 11th element is inserted the oldest // is removed and 10 remains - 11 is the biggest map size where internal // table of 16 elements is sufficient (inserting 12th element would resize it to 32) private static final int MAX_SIZE = 10; private Key.Impl first, last; // first and last in FIFO queue DeserializationConstructorsCache() { // start small - if there is more than one shape of ObjectStreamClass // deserialized, there will typically be two (current version and previous version) super(2); } MethodHandle get(ObjectStreamField[] fields) { return get(new Key.Lookup(fields)); } synchronized MethodHandle putIfAbsentAndGet(ObjectStreamField[] fields, MethodHandle mh) { Key.Impl key = new Key.Impl(fields); var oldMh = putIfAbsent(key, mh); if (oldMh != null) return oldMh; // else we did insert new entry -> link the new key as last if (last == null) { last = first = key; } else { last = (last.next = key); } // may need to remove first if (size() > MAX_SIZE) { assert first != null; remove(first); first = first.next; if (first == null) { last = null; } } return mh; } // a key composed of ObjectStreamField[] names and types abstract static class Key { abstract int length(); abstract String fieldName(int i); abstract Class fieldType(int i); @Override public final int hashCode() { int n = length(); int h = 0; for (int i = 0; i < n; i++) h = h * 31 + fieldType(i).hashCode(); for (int i = 0; i < n; i++) h = h * 31 + fieldName(i).hashCode(); return h; } @Override public final boolean equals(Object obj) { if (!(obj instanceof Key other)) return false; int n = length(); if (n != other.length()) return false; for (int i = 0; i < n; i++) if (fieldType(i) != other.fieldType(i)) return false; for (int i = 0; i < n; i++) if (!fieldName(i).equals(other.fieldName(i))) return false; return true; } // lookup key - just wraps ObjectStreamField[] static final class Lookup extends Key { final ObjectStreamField[] fields; Lookup(ObjectStreamField[] fields) { this.fields = fields; } @Override int length() { return fields.length; } @Override String fieldName(int i) { return fields[i].getName(); } @Override Class fieldType(int i) { return fields[i].getType(); } } // real key - copies field names and types and forms FIFO queue in cache static final class Impl extends Key { Impl next; final String[] fieldNames; final Class[] fieldTypes; Impl(ObjectStreamField[] fields) { this.fieldNames = new String[fields.length]; this.fieldTypes = new Class[fields.length]; for (int i = 0; i < fields.length; i++) { fieldNames[i] = fields[i].getName(); fieldTypes[i] = fields[i].getType(); } } @Override int length() { return fieldNames.length; } @Override String fieldName(int i) { return fieldNames[i]; } @Override Class fieldType(int i) { return fieldTypes[i]; } } } } /** Record specific support for retrieving and binding stream field values. */ static final class RecordSupport { /** * Returns canonical record constructor adapted to take two arguments: * {@code (byte[] primValues, Object[] objValues)} * and return * {@code Object} */ @SuppressWarnings() static MethodHandle deserializationCtr(ObjectStreamClass desc) { // check the cached value 1st MethodHandle mh = desc.deserializationCtr; if (mh != null) return mh; mh = desc.deserializationCtrs.get(desc.getFields(false)); if (mh != null) return desc.deserializationCtr = mh; // retrieve record components RecordComponent[] recordComponents; try { Class cls = desc.forClass(); PrivilegedExceptionAction pa = cls::getRecordComponents; recordComponents = AccessController.doPrivileged(pa); } catch (PrivilegedActionException e) { throw new InternalError(e.getCause()); } // retrieve the canonical constructor // (T1, T2, ..., Tn):TR mh = desc.getRecordConstructor(); // change return type to Object // (T1, T2, ..., Tn):TR -> (T1, T2, ..., Tn):Object mh = mh.asType(mh.type().changeReturnType(Object.class)); // drop last 2 arguments representing primValues and objValues arrays // (T1, T2, ..., Tn):Object -> (T1, T2, ..., Tn, byte[], Object[]):Object mh = MethodHandles.dropArguments(mh, mh.type().parameterCount(), byte[].class, Object[].class); for (int i = recordComponents.length-1; i >= 0; i--) { String name = recordComponents[i].getName(); Class type = recordComponents[i].getType(); // obtain stream field extractor that extracts argument at // position i (Ti+1) from primValues and objValues arrays // (byte[], Object[]):Ti+1 MethodHandle combiner = streamFieldExtractor(name, type, desc); // fold byte[] privValues and Object[] objValues into argument at position i (Ti+1) // (..., Ti, Ti+1, byte[], Object[]):Object -> (..., Ti, byte[], Object[]):Object mh = MethodHandles.foldArguments(mh, i, combiner); } // what we are left with is a MethodHandle taking just the primValues // and objValues arrays and returning the constructed record instance // (byte[], Object[]):Object // store it into cache and return the 1st value stored return desc.deserializationCtr = desc.deserializationCtrs.putIfAbsentAndGet(desc.getFields(false), mh); } /** Returns the number of primitive fields for the given descriptor. */ private static int numberPrimValues(ObjectStreamClass desc) { ObjectStreamField[] fields = desc.getFields(); int primValueCount = 0; for (int i = 0; i < fields.length; i++) { if (fields[i].isPrimitive()) primValueCount++; else break; // can be no more } return primValueCount; } /** * Returns extractor MethodHandle taking the primValues and objValues arrays * and extracting the argument of canonical constructor with given name and type * or producing default value for the given type if the field is absent. */ private static MethodHandle streamFieldExtractor(String pName, Class pType, ObjectStreamClass desc) { ObjectStreamField[] fields = desc.getFields(false); for (int i = 0; i < fields.length; i++) { ObjectStreamField f = fields[i]; String fName = f.getName(); if (!fName.equals(pName)) continue; Class fType = f.getField().getType(); if (!pType.isAssignableFrom(fType)) throw new InternalError(fName + + fType); if (f.isPrimitive()) { // (byte[], int):fType MethodHandle mh = PRIM_VALUE_EXTRACTORS.get(fType); if (mh == null) { throw new InternalError( + fType); } // bind offset // (byte[], int):fType -> (byte[]):fType mh = MethodHandles.insertArguments(mh, 1, f.getOffset()); // drop objValues argument // (byte[]):fType -> (byte[], Object[]):fType mh = MethodHandles.dropArguments(mh, 1, Object[].class); // adapt return type to pType // (byte[], Object[]):fType -> (byte[], Object[]):pType if (pType != fType) { mh = mh.asType(mh.type().changeReturnType(pType)); } return mh; } else { // reference // (Object[], int):Object MethodHandle mh = MethodHandles.arrayElementGetter(Object[].class); // bind index // (Object[], int):Object -> (Object[]):Object mh = MethodHandles.insertArguments(mh, 1, i - numberPrimValues(desc)); // drop primValues argument // (Object[]):Object -> (byte[], Object[]):Object mh = MethodHandles.dropArguments(mh, 0, byte[].class); // adapt return type to pType // (byte[], Object[]):Object -> (byte[], Object[]):pType if (pType != Object.class) { mh = mh.asType(mh.type().changeReturnType(pType)); } return mh; } } // return default value extractor if no field matches pName return MethodHandles.empty(MethodType.methodType(pType, byte[].class, Object[].class)); } private static final Map, MethodHandle> PRIM_VALUE_EXTRACTORS; static { var lkp = MethodHandles.lookup(); try { PRIM_VALUE_EXTRACTORS = Map.of( byte.class, MethodHandles.arrayElementGetter(byte[].class), short.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(short.class, byte[].class, int.class)), int.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(int.class, byte[].class, int.class)), long.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(long.class, byte[].class, int.class)), float.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(float.class, byte[].class, int.class)), double.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(double.class, byte[].class, int.class)), char.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(char.class, byte[].class, int.class)), boolean.class, lkp.findStatic(ByteArray.class, , MethodType.methodType(boolean.class, byte[].class, int.class)) ); } catch (NoSuchMethodException | IllegalAccessException e) { throw new InternalError(, e); } } } } /* * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.net; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.channels.DatagramChannel; import java.security.AccessController; import java.security.PrivilegedExceptionAction; import java.util.Enumeration; import java.util.Objects; import java.util.Set; import java.util.Collections; /** * A multicast datagram socket that delegates socket operations to a * {@link DatagramSocketImpl}. * * This class overrides every public method defined by {@link DatagramSocket} * and {@link MulticastSocket}. */ final class NetMulticastSocket extends MulticastSocket { /** * Various states of this socket. */ private boolean bound = false; private boolean closed = false; private volatile boolean created; private final Object closeLock = new Object(); /* * The implementation of this DatagramSocket. */ private final DatagramSocketImpl impl; /** * Set when a socket is ST_CONNECTED until we are certain * that any packets which might have been received prior * to calling connect() but not read by the application * have been read. During this time we check the source * address of all packets received to be sure they are from * the connected destination. Other packets are read but * silently dropped. */ private boolean explicitFilter = false; private int bytesLeftToFilter; /* * Connection state: * ST_NOT_CONNECTED = socket not connected * ST_CONNECTED = socket connected */ static final int ST_NOT_CONNECTED = 0; static final int ST_CONNECTED = 1; int connectState = ST_NOT_CONNECTED; /* * Connected address & port */ InetAddress connectedAddress = null; int connectedPort = -1; /** * This constructor is also used by {@link DatagramSocket#DatagramSocket(DatagramSocketImpl)}. * @param impl The impl used in this instance. */ NetMulticastSocket(DatagramSocketImpl impl) { super((MulticastSocket) null); this.impl = Objects.requireNonNull(impl); } /** * Connects this socket to a remote socket address (IP address + port number). * Binds socket if not already bound. * * @param address The remote address. * @param port The remote port * @throws SocketException if binding the socket fails. */ private synchronized void connectInternal(InetAddress address, int port) throws SocketException { if (port < 0 || port > 0xFFFF) { throw new IllegalArgumentException( + port); } if (address == null) { throw new IllegalArgumentException(); } checkAddress(address, ); if (isClosed()) return; @SuppressWarnings() SecurityManager security = System.getSecurityManager(); if (security != null) { if (address.isMulticastAddress()) { security.checkMulticast(address); } else { security.checkConnect(address.getHostAddress(), port); security.checkAccept(address.getHostAddress(), port); } } if (port == 0) { throw new SocketException(); } if (!isBound()) bind(new InetSocketAddress(0)); getImpl().connect(address, port); // socket is now connected by the impl connectState = ST_CONNECTED; // Do we need to filter some packets? int avail = getImpl().dataAvailable(); if (avail == -1) { throw new SocketException(); } explicitFilter = avail > 0; if (explicitFilter) { bytesLeftToFilter = getReceiveBufferSize(); } connectedAddress = address; connectedPort = port; } /** * Return the {@code DatagramSocketImpl} attached to this socket, * creating the socket if not already created. * * @return the {@code DatagramSocketImpl} attached to that * DatagramSocket * @throws SocketException if creating the socket fails * @since 1.4 */ final DatagramSocketImpl getImpl() throws SocketException { if (!created) { synchronized (this) { if (!created) { impl.create(); created = true; } } } return impl; } @Override public synchronized void bind(SocketAddress addr) throws SocketException { if (isClosed()) throw new SocketException(); if (isBound()) throw new SocketException(); if (addr == null) addr = new InetSocketAddress(0); if (!(addr instanceof InetSocketAddress epoint)) throw new IllegalArgumentException(); if (epoint.isUnresolved()) throw new SocketException(); InetAddress iaddr = epoint.getAddress(); int port = epoint.getPort(); checkAddress(iaddr, ); @SuppressWarnings() SecurityManager sec = System.getSecurityManager(); if (sec != null) { sec.checkListen(port); } try { getImpl().bind(port, iaddr); } catch (SocketException e) { getImpl().close(); throw e; } bound = true; } static void checkAddress(InetAddress addr, String op) { if (addr == null) { return; } if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) { throw new IllegalArgumentException(op + ); } } @Override public void connect(InetAddress address, int port) { try { connectInternal(address, port); } catch (SocketException se) { throw new UncheckedIOException(, se); } } @Override public void connect(SocketAddress addr) throws SocketException { if (addr == null) throw new IllegalArgumentException(); if (!(addr instanceof InetSocketAddress epoint)) throw new IllegalArgumentException(); if (epoint.isUnresolved()) throw new SocketException(); connectInternal(epoint.getAddress(), epoint.getPort()); } @Override public void disconnect() { synchronized (this) { if (isClosed()) return; if (connectState == ST_CONNECTED) { impl.disconnect(); } connectedAddress = null; connectedPort = -1; connectState = ST_NOT_CONNECTED; explicitFilter = false; } } @Override public boolean isBound() { return bound; } @Override public boolean isConnected() { return connectState != ST_NOT_CONNECTED; } @Override public InetAddress getInetAddress() { return connectedAddress; } @Override public int getPort() { return connectedPort; } @Override public SocketAddress getRemoteSocketAddress() { if (!isConnected()) return null; return new InetSocketAddress(getInetAddress(), getPort()); } @Override public SocketAddress getLocalSocketAddress() { if (isClosed()) return null; if (!isBound()) return null; return new InetSocketAddress(getLocalAddress(), getLocalPort()); } @Override public void send(DatagramPacket p) throws IOException { synchronized (p) { if (isClosed()) throw new SocketException(); InetAddress packetAddress = p.getAddress(); int packetPort = p.getPort(); checkAddress(packetAddress, ); if (connectState == ST_NOT_CONNECTED) { if (packetAddress == null) { throw new IllegalArgumentException(); } if (packetPort < 0 || packetPort > 0xFFFF) throw new IllegalArgumentException( + packetPort); // check the address is ok with the security manager on every send. @SuppressWarnings() SecurityManager security = System.getSecurityManager(); // The reason you want to synchronize on datagram packet // is because you don't want an applet to change the address // while you are trying to send the packet for example // after the security check but before the send. if (security != null) { if (packetAddress.isMulticastAddress()) { security.checkMulticast(packetAddress); } else { security.checkConnect(packetAddress.getHostAddress(), packetPort); } } if (packetPort == 0) { throw new SocketException(); } } else { // we're connected if (packetAddress == null) { p.setAddress(connectedAddress); p.setPort(connectedPort); } else if ((!packetAddress.equals(connectedAddress)) || packetPort != connectedPort) { throw new IllegalArgumentException( + + ); } } // Check whether the socket is bound if (!isBound()) bind(new InetSocketAddress(0)); // call the method to send getImpl().send(p); } } @Override public synchronized void receive(DatagramPacket p) throws IOException { synchronized (p) { if (!isBound()) bind(new InetSocketAddress(0)); if (connectState == ST_NOT_CONNECTED) { // check the address is ok with the security manager before every recv. @SuppressWarnings() SecurityManager security = System.getSecurityManager(); if (security != null) { while (true) { int peekPort = 0; // peek at the packet to see who it is from. DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); peekPort = getImpl().peekData(peekPacket); String peekAd = peekPacket.getAddress().getHostAddress(); try { security.checkAccept(peekAd, peekPort); // security check succeeded - so now break // and recv the packet. break; } catch (SecurityException se) { // Throw away the offending packet by consuming // it in a tmp buffer. DatagramPacket tmp = new DatagramPacket(new byte[1], 1); getImpl().receive(tmp); // silently discard the offending packet // and continue: unknown/malicious // entities on nets should not make // runtime throw security exception and // disrupt the applet by sending random // datagram packets. continue; } } // end of while } } DatagramPacket tmp = null; if (explicitFilter) { // We have to do the filtering the old fashioned way since // the native impl doesn't support connect or the connect // via the impl failed, or .. may be set when // a socket is connected via the impl, for a period of time // when packets from other sources might be queued on socket. boolean stop = false; while (!stop) { // peek at the packet to see who it is from. DatagramPacket peekPacket = new DatagramPacket(new byte[1], 1); int peekPort = getImpl().peekData(peekPacket); InetAddress peekAddress = peekPacket.getAddress(); if ((!connectedAddress.equals(peekAddress)) || (connectedPort != peekPort)) { // throw the packet away and silently continue tmp = new DatagramPacket( new byte[1024], 1024); getImpl().receive(tmp); if (explicitFilter) { if (checkFiltering(tmp)) { stop = true; } } } else { stop = true; } } } // If the security check succeeds, or the datagram is // connected then receive the packet getImpl().receive(p); if (explicitFilter && tmp == null) { // packet was not filtered, account for it here checkFiltering(p); } } } private boolean checkFiltering(DatagramPacket p) throws SocketException { bytesLeftToFilter -= p.getLength(); if (bytesLeftToFilter <= 0 || getImpl().dataAvailable() <= 0) { explicitFilter = false; return true; } return false; } @Override public InetAddress getLocalAddress() { if (isClosed()) return null; InetAddress in; try { in = (InetAddress) getImpl().getOption(SocketOptions.SO_BINDADDR); if (in.isAnyLocalAddress()) { in = InetAddress.anyLocalAddress(); } @SuppressWarnings() SecurityManager s = System.getSecurityManager(); if (s != null) { s.checkConnect(in.getHostAddress(), -1); } } catch (Exception e) { in = InetAddress.anyLocalAddress(); // } return in; } @Override public int getLocalPort() { if (isClosed()) return -1; try { return getImpl().getLocalPort(); } catch (Exception e) { return 0; } } @Override public synchronized void setSoTimeout(int timeout) throws SocketException { if (isClosed()) throw new SocketException(); if (timeout < 0) throw new IllegalArgumentException(); getImpl().setOption(SocketOptions.SO_TIMEOUT, timeout); } @Override public synchronized int getSoTimeout() throws SocketException { if (isClosed()) throw new SocketException(); if (getImpl() == null) return 0; Object o = getImpl().getOption(SocketOptions.SO_TIMEOUT); /* extra type safety */ if (o instanceof Integer) { return ((Integer) o).intValue(); } else { return 0; } } @Override public synchronized void setSendBufferSize(int size) throws SocketException { if (!(size > 0)) { throw new IllegalArgumentException(); } if (isClosed()) throw new SocketException(); getImpl().setOption(SocketOptions.SO_SNDBUF, size); } @Override public synchronized int getSendBufferSize() throws SocketException { if (isClosed()) throw new SocketException(); int result = 0; Object o = getImpl().getOption(SocketOptions.SO_SNDBUF); if (o instanceof Integer) { result = ((Integer) o).intValue(); } return result; } @Override public synchronized void setReceiveBufferSize(int size) throws SocketException { if (size <= 0) { throw new IllegalArgumentException(); } if (isClosed()) throw new SocketException(); getImpl().setOption(SocketOptions.SO_RCVBUF, size); } @Override public synchronized int getReceiveBufferSize() throws SocketException { if (isClosed()) throw new SocketException(); int result = 0; Object o = getImpl().getOption(SocketOptions.SO_RCVBUF); if (o instanceof Integer) { result = ((Integer) o).intValue(); } return result; } @Override public synchronized void setReuseAddress(boolean on) throws SocketException { if (isClosed()) throw new SocketException(); getImpl().setOption(SocketOptions.SO_REUSEADDR, Boolean.valueOf(on)); } @Override public synchronized boolean getReuseAddress() throws SocketException { if (isClosed()) throw new SocketException(); Object o = getImpl().getOption(SocketOptions.SO_REUSEADDR); return ((Boolean) o).booleanValue(); } @Override public synchronized void setBroadcast(boolean on) throws SocketException { if (isClosed()) throw new SocketException(); getImpl().setOption(SocketOptions.SO_BROADCAST, Boolean.valueOf(on)); } @Override public synchronized boolean getBroadcast() throws SocketException { if (isClosed()) throw new SocketException(); return ((Boolean) (getImpl().getOption(SocketOptions.SO_BROADCAST))).booleanValue(); } @Override public synchronized void setTrafficClass(int tc) throws SocketException { if (tc < 0 || tc > 255) throw new IllegalArgumentException(); if (isClosed()) throw new SocketException(); try { getImpl().setOption(SocketOptions.IP_TOS, tc); } catch (SocketException se) { // not supported if socket already connected // Solaris returns error in such cases if (!isConnected()) throw se; } } @Override public synchronized int getTrafficClass() throws SocketException { if (isClosed()) throw new SocketException(); return ((Integer) (getImpl().getOption(SocketOptions.IP_TOS))).intValue(); } @Override public void close() { synchronized (closeLock) { if (isClosed()) return; impl.close(); closed = true; } } @Override public boolean isClosed() { synchronized (closeLock) { return closed; } } @Override public DatagramSocket setOption(SocketOption name, T value) throws IOException { Objects.requireNonNull(name); if (isClosed()) throw new SocketException(); getImpl().setOption(name, value); return this; } @Override public T getOption(SocketOption name) throws IOException { Objects.requireNonNull(name); if (isClosed()) throw new SocketException(); return getImpl().getOption(name); } private volatile Set> options; private final Object optionsLock = new Object(); @Override public Set> supportedOptions() { Set> options = this.options; if (options != null) return options; synchronized (optionsLock) { options = this.options; if (options != null) { return options; } try { DatagramSocketImpl impl = getImpl(); options = Collections.unmodifiableSet(impl.supportedOptions()); } catch (IOException e) { options = Collections.emptySet(); } return this.options = options; } } // Multicast socket support /** * Used on some platforms to record if an outgoing interface * has been set for this socket. */ private boolean interfaceSet; /** * The lock on the socket's TTL. This is for set/getTTL and * send(packet,ttl). */ private final Object ttlLock = new Object(); /** * The lock on the socket's interface - used by setInterface * and getInterface */ private final Object infLock = new Object(); /** * The interface set by setInterface on this MulticastSocket */ private InetAddress infAddress = null; @Deprecated @Override public void setTTL(byte ttl) throws IOException { if (isClosed()) throw new SocketException(); getImpl().setTTL(ttl); } @Override public void setTimeToLive(int ttl) throws IOException { if (ttl < 0 || ttl > 255) { throw new IllegalArgumentException(); } if (isClosed()) throw new SocketException(); getImpl().setTimeToLive(ttl); } @Deprecated @Override public byte getTTL() throws IOException { if (isClosed()) throw new SocketException(); return getImpl().getTTL(); } @Override public int getTimeToLive() throws IOException { if (isClosed()) throw new SocketException(); return getImpl().getTimeToLive(); } @Override @Deprecated public void joinGroup(InetAddress mcastaddr) throws IOException { if (isClosed()) { throw new SocketException(); } checkAddress(mcastaddr, ); @SuppressWarnings() SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkMulticast(mcastaddr); } if (!mcastaddr.isMulticastAddress()) { throw new SocketException(); } /** * required for some platforms where it's not possible to join * a group without setting the interface first. */ NetworkInterface defaultInterface = NetworkInterface.getDefault(); if (!interfaceSet && defaultInterface != null) { setNetworkInterface(defaultInterface); } getImpl().join(mcastaddr); } @Override @Deprecated public void leaveGroup(InetAddress mcastaddr) throws IOException { if (isClosed()) { throw new SocketException(); } checkAddress(mcastaddr, ); @SuppressWarnings() SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkMulticast(mcastaddr); } if (!mcastaddr.isMulticastAddress()) { throw new SocketException(); } getImpl().leave(mcastaddr); } @Override public void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException { if (isClosed()) throw new SocketException(); if (!(mcastaddr instanceof InetSocketAddress addr)) throw new IllegalArgumentException(); checkAddress(addr.getAddress(), ); @SuppressWarnings() SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkMulticast(addr.getAddress()); } if (!addr.getAddress().isMulticastAddress()) { throw new SocketException(); } getImpl().joinGroup(mcastaddr, netIf); } @Override public void leaveGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException { if (isClosed()) throw new SocketException(); if (!(mcastaddr instanceof InetSocketAddress addr)) throw new IllegalArgumentException(); checkAddress(addr.getAddress(), ); @SuppressWarnings() SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkMulticast(addr.getAddress()); } if (!addr.getAddress().isMulticastAddress()) { throw new SocketException(); } getImpl().leaveGroup(mcastaddr, netIf); } @Override @Deprecated public void setInterface(InetAddress inf) throws SocketException { if (isClosed()) { throw new SocketException(); } checkAddress(inf, ); synchronized (infLock) { getImpl().setOption(SocketOptions.IP_MULTICAST_IF, inf); infAddress = inf; interfaceSet = true; } } @Override @Deprecated public InetAddress getInterface() throws SocketException { if (isClosed()) { throw new SocketException(); } synchronized (infLock) { InetAddress ia = (InetAddress)getImpl().getOption(SocketOptions.IP_MULTICAST_IF); /** * No previous setInterface or interface can be * set using setNetworkInterface */ if (infAddress == null) { return ia; } /** * Same interface set with setInterface? */ if (ia.equals(infAddress)) { return ia; } /** * Different InetAddress from what we set with setInterface * so enumerate the current interface to see if the * address set by setInterface is bound to this interface. */ try { NetworkInterface ni = NetworkInterface.getByInetAddress(ia); Enumeration addrs = ni.getInetAddresses(); while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); if (addr.equals(infAddress)) { return infAddress; } } /** * No match so reset infAddress to indicate that the * interface has changed via means */ infAddress = null; return ia; } catch (Exception e) { return ia; } } } @Override public void setNetworkInterface(NetworkInterface netIf) throws SocketException { synchronized (infLock) { getImpl().setOption(SocketOptions.IP_MULTICAST_IF2, netIf); infAddress = null; interfaceSet = true; } } @Override public NetworkInterface getNetworkInterface() throws SocketException { NetworkInterface ni = (NetworkInterface)getImpl().getOption(SocketOptions.IP_MULTICAST_IF2); if (ni == null) { InetAddress[] addrs = new InetAddress[1]; addrs[0] = InetAddress.anyLocalAddress(); return new NetworkInterface(addrs[0].getHostName(), 0, addrs); } else { return ni; } } @Override @Deprecated public void setLoopbackMode(boolean disable) throws SocketException { getImpl().setOption(SocketOptions.IP_MULTICAST_LOOP, Boolean.valueOf(disable)); } @Override @Deprecated public boolean getLoopbackMode() throws SocketException { return ((Boolean)getImpl().getOption(SocketOptions.IP_MULTICAST_LOOP)).booleanValue(); } @SuppressWarnings() @Deprecated @Override public void send(DatagramPacket p, byte ttl) throws IOException { if (isClosed()) throw new SocketException(); synchronized(ttlLock) { synchronized(p) { InetAddress packetAddress = p.getAddress(); checkAddress(packetAddress, ); if (connectState == NetMulticastSocket.ST_NOT_CONNECTED) { if (packetAddress == null) { throw new IllegalArgumentException(); } // Security manager makes sure that the multicast address // is allowed one and that the ttl used is less // than the allowed maxttl. SecurityManager security = System.getSecurityManager(); if (security != null) { if (packetAddress.isMulticastAddress()) { security.checkMulticast(packetAddress, ttl); } else { security.checkConnect(packetAddress.getHostAddress(), p.getPort()); } } } else { // we're connected if (packetAddress == null) { p.setAddress(connectedAddress); p.setPort(connectedPort); } else if ((!packetAddress.equals(connectedAddress)) || p.getPort() != connectedPort) { throw new IllegalArgumentException( + ); } } byte dttl = getTTL(); try { if (ttl != dttl) { // set the ttl getImpl().setTTL(ttl); } if (p.getPort() == 0) { throw new SocketException(); } // call the datagram method to send getImpl().send(p); } finally { // set it back to default if (ttl != dttl) { getImpl().setTTL(dttl); } } } // synch p } //synch ttl } //method } /* * Copyright (c) 1995, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.io; import java.util.Objects; /** * A piped input stream should be connected * to a piped output stream; the piped input * stream then provides whatever data bytes * are written to the piped output stream. * Typically, data is read from a {@code PipedInputStream} * object by one thread and data is written * to the corresponding {@code PipedOutputStream} * by some other thread. Attempting to use * both objects from a single thread is not * recommended, as it may deadlock the thread. * The piped input stream contains a buffer, * decoupling read operations from write operations, * within limits. * A pipe is said to be broken if a * thread that was providing data bytes to the connected * piped output stream is no longer alive. * * @author James Gosling * @see java.io.PipedOutputStream * @since 1.0 */ public class PipedInputStream extends InputStream { boolean closedByWriter; volatile boolean closedByReader; boolean connected; /* REMIND: identification of the read and write sides needs to be more sophisticated. Either using thread groups (but what about pipes within a thread?) or using finalization (but it may be a long time until the next GC). */ Thread readSide; Thread writeSide; private static final int DEFAULT_PIPE_SIZE = 1024; /** * The default size of the pipe's circular input buffer. * @since 1.1 */ // This used to be a constant before the pipe size was allowed // to change. This field will continue to be maintained // for backward compatibility. protected static final int PIPE_SIZE = DEFAULT_PIPE_SIZE; /** * The circular buffer into which incoming data is placed. * @since 1.1 */ protected byte buffer[]; /** * The index of the position in the circular buffer at which the * next byte of data will be stored when received from the connected * piped output stream. {@code in < 0} implies the buffer is empty, * {@code in == out} implies the buffer is full * @since 1.1 */ protected int in = -1; /** * The index of the position in the circular buffer at which the next * byte of data will be read by this piped input stream. * @since 1.1 */ protected int out = 0; /** * Creates a {@code PipedInputStream} so * that it is connected to the piped output * stream {@code src}. Data bytes written * to {@code src} will then be available * as input from this stream. * * @param src the stream to connect to. * @throws IOException if an I/O error occurs. */ public PipedInputStream(PipedOutputStream src) throws IOException { this(src, DEFAULT_PIPE_SIZE); } /** * Creates a {@code PipedInputStream} so that it is * connected to the piped output stream * {@code src} and uses the specified pipe size for * the pipe's buffer. * Data bytes written to {@code src} will then * be available as input from this stream. * * @param src the stream to connect to. * @param pipeSize the size of the pipe's buffer. * @throws IOException if an I/O error occurs. * @throws IllegalArgumentException if {@code pipeSize <= 0}. * @since 1.6 */ public PipedInputStream(PipedOutputStream src, int pipeSize) throws IOException { initPipe(pipeSize); connect(src); } /** * Creates a {@code PipedInputStream} so * that it is not yet {@linkplain #connect(java.io.PipedOutputStream) * connected}. * It must be {@linkplain java.io.PipedOutputStream#connect( * java.io.PipedInputStream) connected} to a * {@code PipedOutputStream} before being used. */ public PipedInputStream() { initPipe(DEFAULT_PIPE_SIZE); } /** * Creates a {@code PipedInputStream} so that it is not yet * {@linkplain #connect(java.io.PipedOutputStream) connected} and * uses the specified pipe size for the pipe's buffer. * It must be {@linkplain java.io.PipedOutputStream#connect( * java.io.PipedInputStream) * connected} to a {@code PipedOutputStream} before being used. * * @param pipeSize the size of the pipe's buffer. * @throws IllegalArgumentException if {@code pipeSize <= 0}. * @since 1.6 */ public PipedInputStream(int pipeSize) { initPipe(pipeSize); } private void initPipe(int pipeSize) { if (pipeSize <= 0) { throw new IllegalArgumentException(); } buffer = new byte[pipeSize]; } /** * Causes this piped input stream to be connected * to the piped output stream {@code src}. * If this object is already connected to some * other piped output stream, an {@code IOException} * is thrown. *

* If {@code src} is an * unconnected piped output stream and {@code snk} * is an unconnected piped input stream, they * may be connected by either the call: * * {@snippet lang=java : * snk.connect(src) * } *

* or the call: * * {@snippet lang=java : * src.connect(snk) * } *

* The two calls have the same effect. * * @param src The piped output stream to connect to. * @throws IOException if an I/O error occurs. */ public void connect(PipedOutputStream src) throws IOException { src.connect(this); } /** * Receives a byte of data. This method will block if no input is * available. * @param b the byte being received * @throws IOException If the pipe is {@code broken}, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. * @since 1.1 */ protected synchronized void receive(int b) throws IOException { checkStateForReceive(); writeSide = Thread.currentThread(); if (in == out) awaitSpace(); if (in < 0) { in = 0; out = 0; } buffer[in++] = (byte)(b & 0xFF); if (in >= buffer.length) { in = 0; } } /** * Receives data into an array of bytes. This method will * block until some input is available. * @param b the buffer into which the data is received * @param off the start offset of the data * @param len the maximum number of bytes received * @throws IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. */ synchronized void receive(byte[] b, int off, int len) throws IOException { checkStateForReceive(); writeSide = Thread.currentThread(); int bytesToTransfer = len; while (bytesToTransfer > 0) { if (in == out) awaitSpace(); int nextTransferAmount = 0; if (out < in) { nextTransferAmount = buffer.length - in; } else if (in < out) { if (in == -1) { in = out = 0; nextTransferAmount = buffer.length - in; } else { nextTransferAmount = out - in; } } if (nextTransferAmount > bytesToTransfer) nextTransferAmount = bytesToTransfer; assert(nextTransferAmount > 0); System.arraycopy(b, off, buffer, in, nextTransferAmount); bytesToTransfer -= nextTransferAmount; off += nextTransferAmount; in += nextTransferAmount; if (in >= buffer.length) { in = 0; } } } private void checkStateForReceive() throws IOException { if (!connected) { throw new IOException(); } else if (closedByWriter || closedByReader) { throw new IOException(); } else if (readSide != null && !readSide.isAlive()) { throw new IOException(); } } private void awaitSpace() throws IOException { while (in == out) { checkStateForReceive(); /* full: kick any waiting readers */ notifyAll(); try { wait(1000); } catch (InterruptedException ex) { throw new java.io.InterruptedIOException(); } } } /** * Notifies all waiting threads that the last byte of data has been * received. */ synchronized void receivedLast() { closedByWriter = true; notifyAll(); } /** * Reads the next byte of data from this piped input stream. The * value byte is returned as an {@code int} in the range * {@code 0} to {@code 255}. * This method blocks until input data is available, the end of the * stream is detected, or an exception is thrown. * * @return {@inheritDoc} * @throws IOException if the pipe is * {@link #connect(java.io.PipedOutputStream) unconnected}, * {@code broken}, closed, * or if an I/O error occurs. */ @Override public synchronized int read() throws IOException { if (!connected) { throw new IOException(); } else if (closedByReader) { throw new IOException(); } else if (writeSide != null && !writeSide.isAlive() && !closedByWriter && (in < 0)) { throw new IOException(); } readSide = Thread.currentThread(); int trials = 2; while (in < 0) { if (closedByWriter) { /* closed by writer, return EOF */ return -1; } if ((writeSide != null) && (!writeSide.isAlive()) && (--trials < 0)) { throw new IOException(); } /* might be a writer waiting */ notifyAll(); try { wait(1000); } catch (InterruptedException ex) { throw new java.io.InterruptedIOException(); } } int ret = buffer[out++] & 0xFF; if (out >= buffer.length) { out = 0; } if (in == out) { /* now empty */ in = -1; } return ret; } /** * Reads up to {@code len} bytes of data from this piped input * stream into an array of bytes. Less than {@code len} bytes * will be read if the end of the data stream is reached or if * {@code len} exceeds the pipe's buffer size. * If {@code len } is zero, then no bytes are read and 0 is returned; * otherwise, the method blocks until at least 1 byte of input is * available, end of the stream has been detected, or an exception is * thrown. * * @param b {@inheritDoc} * @param off {@inheritDoc} * @param len {@inheritDoc} * @return {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IndexOutOfBoundsException {@inheritDoc} * @throws IOException if the pipe is {@code broken}, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. */ @Override public synchronized int read(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } Objects.checkFromIndexSize(off, len, b.length); if (len == 0) { return 0; } /* possibly wait on the first character */ int c = read(); if (c < 0) { return -1; } b[off] = (byte) c; int rlen = 1; while ((in >= 0) && (len > 1)) { int available; if (in > out) { available = Math.min((buffer.length - out), (in - out)); } else { available = buffer.length - out; } // A byte is read beforehand outside the loop if (available > (len - 1)) { available = len - 1; } System.arraycopy(buffer, out, b, off + rlen, available); out += available; rlen += available; len -= available; if (out >= buffer.length) { out = 0; } if (in == out) { /* now empty */ in = -1; } } return rlen; } /** * Returns the number of bytes that can be read from this input * stream without blocking. * * @return the number of bytes that can be read from this input stream * without blocking, or {@code 0} if this input stream has been * closed by invoking its {@link #close()} method, or if the pipe * is {@link #connect(java.io.PipedOutputStream) unconnected}, or * {@code broken}. * * @throws IOException {@inheritDoc} * @since 1.0.2 */ @Override public synchronized int available() throws IOException { if(in < 0) return 0; else if(in == out) return buffer.length; else if (in > out) return in - out; else return in + buffer.length - out; } /** * {@inheritDoc} * * @throws IOException {@inheritDoc} */ @Override public void close() throws IOException { closedByReader = true; synchronized (this) { in = -1; } } }