1 /*
2 * Copyright (c) 1994, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package java.lang;
26
27 import java.io.BufferedInputStream;
28 import java.io.BufferedOutputStream;
29 import java.io.Console;
30 import java.io.FileDescriptor;
31 import java.io.FileInputStream;
32 import java.io.FileOutputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 import java.io.OutputStream;
36 import java.io.PrintStream;
37 import java.lang.annotation.Annotation;
38 import java.lang.foreign.MemorySegment;
39 import java.lang.invoke.MethodHandle;
40 import java.lang.invoke.MethodType;
41 import java.lang.module.ModuleDescriptor;
42 import java.lang.reflect.Executable;
43 import java.lang.reflect.Method;
44 import java.net.URI;
45 import java.nio.channels.Channel;
46 import java.nio.channels.spi.SelectorProvider;
47 import java.nio.charset.CharacterCodingException;
48 import java.nio.charset.Charset;
49 import java.security.ProtectionDomain;
50 import java.util.List;
51 import java.util.Locale;
52 import java.util.Map;
53 import java.util.Objects;
54 import java.util.Properties;
55 import java.util.ResourceBundle;
56 import java.util.Set;
57 import java.util.concurrent.Executor;
58 import java.util.function.Supplier;
59 import java.util.concurrent.ConcurrentHashMap;
60 import java.util.stream.Stream;
61
62 import jdk.internal.javac.Restricted;
63 import jdk.internal.loader.NativeLibraries;
64 import jdk.internal.logger.LoggerFinderLoader.TemporaryLoggerFinder;
65 import jdk.internal.misc.Blocker;
66 import jdk.internal.misc.CarrierThreadLocal;
67 import jdk.internal.util.StaticProperty;
68 import jdk.internal.module.ModuleBootstrap;
69 import jdk.internal.module.ServicesCatalog;
70 import jdk.internal.reflect.CallerSensitive;
71 import jdk.internal.reflect.Reflection;
72 import jdk.internal.access.JavaLangAccess;
73 import jdk.internal.access.SharedSecrets;
74 import jdk.internal.logger.LoggerFinderLoader;
75 import jdk.internal.logger.LazyLoggers;
76 import jdk.internal.logger.LocalizedLoggerWrapper;
77 import jdk.internal.misc.VM;
78 import jdk.internal.util.SystemProps;
79 import jdk.internal.vm.Continuation;
80 import jdk.internal.vm.ContinuationScope;
81 import jdk.internal.vm.StackableScope;
82 import jdk.internal.vm.ThreadContainer;
83 import jdk.internal.vm.annotation.IntrinsicCandidate;
84 import jdk.internal.vm.annotation.Stable;
85 import sun.reflect.annotation.AnnotationType;
86 import sun.nio.ch.Interruptible;
87 import sun.nio.cs.UTF_8;
88
89 /**
90 * The {@code System} class contains several useful class fields
91 * and methods. It cannot be instantiated.
92 *
93 * Among the facilities provided by the {@code System} class
94 * are standard input, standard output, and error output streams;
95 * access to externally defined properties and environment
96 * variables; a means of loading files and libraries; and a utility
97 * method for quickly copying a portion of an array.
98 *
99 * @since 1.0
100 */
101 public final class System {
102 /* Register the natives via the static initializer.
103 *
104 * The VM will invoke the initPhase1 method to complete the initialization
105 * of this class separate from <clinit>.
106 */
107 private static native void registerNatives();
108 static {
109 registerNatives();
110 }
111
112 /** Don't let anyone instantiate this class */
113 private System() {
114 }
115
116 /**
117 * The "standard" input stream. This stream is already
118 * open and ready to supply input data. This stream
119 * corresponds to keyboard input or another input source specified by
120 * the host environment or user. Applications should use the encoding
121 * specified by the {@link ##stdin.encoding stdin.encoding} property
122 * to convert input bytes to character data.
123 *
124 * @apiNote
125 * The typical approach to read character data is to wrap {@code System.in}
126 * within the object that handles character encoding. After this is done,
127 * subsequent reading should use only the wrapper object; continuing to
128 * operate directly on {@code System.in} results in unspecified behavior.
129 * <p>
130 * Here are two common examples. Using an {@link java.io.InputStreamReader
131 * InputStreamReader}:
132 * {@snippet lang=java :
133 * new InputStreamReader(System.in, System.getProperty("stdin.encoding"));
134 * }
135 * Or using a {@link java.util.Scanner Scanner}:
136 * {@snippet lang=java :
137 * new Scanner(System.in, System.getProperty("stdin.encoding"));
138 * }
139 * <p>
140 * For handling interactive input, consider using {@link Console}.
141 *
142 * @see Console
143 * @see ##stdin.encoding stdin.encoding
144 */
145 public static final InputStream in = null;
146
147 /**
148 * The "standard" output stream. This stream is already
149 * open and ready to accept output data. Typically this stream
150 * corresponds to display output or another output destination
151 * specified by the host environment or user. The encoding used
152 * in the conversion from characters to bytes is equivalent to
153 * {@link ##stdout.encoding stdout.encoding}.
154 * <p>
155 * For simple stand-alone Java applications, a typical way to write
156 * a line of output data is:
157 * <blockquote><pre>
158 * System.out.println(data)
159 * </pre></blockquote>
160 * <p>
161 * See the {@code println} methods in class {@code PrintStream}.
162 *
163 * @see java.io.PrintStream#println()
164 * @see java.io.PrintStream#println(boolean)
165 * @see java.io.PrintStream#println(char)
166 * @see java.io.PrintStream#println(char[])
167 * @see java.io.PrintStream#println(double)
168 * @see java.io.PrintStream#println(float)
169 * @see java.io.PrintStream#println(int)
170 * @see java.io.PrintStream#println(long)
171 * @see java.io.PrintStream#println(java.lang.Object)
172 * @see java.io.PrintStream#println(java.lang.String)
173 * @see ##stdout.encoding stdout.encoding
174 */
175 public static final PrintStream out = null;
176
177 /**
178 * The "standard" error output stream. This stream is already
179 * open and ready to accept output data.
180 * <p>
181 * Typically this stream corresponds to display output or another
182 * output destination specified by the host environment or user. By
183 * convention, this output stream is used to display error messages
184 * or other information that should come to the immediate attention
185 * of a user even if the principal output stream, the value of the
186 * variable {@code out}, has been redirected to a file or other
187 * destination that is typically not continuously monitored.
188 * The encoding used in the conversion from characters to bytes is
189 * equivalent to {@link ##stderr.encoding stderr.encoding}.
190 *
191 * @see ##stderr.encoding stderr.encoding
192 */
193 public static final PrintStream err = null;
194
195 // Initial values of System.in and System.err, set in initPhase1().
196 private static @Stable InputStream initialIn;
197 private static @Stable PrintStream initialErr;
198
199 // `sun.jnu.encoding` if it is not supported. Otherwise null.
200 // It is initialized in `initPhase1()` before any charset providers
201 // are initialized.
202 private static String notSupportedJnuEncoding;
203
204 /**
205 * Reassigns the "standard" input stream.
206 *
207 * @param in the new standard input stream.
208 *
209 * @since 1.1
210 */
211 public static void setIn(InputStream in) {
212 setIn0(in);
213 }
214
215 /**
216 * Reassigns the "standard" output stream.
217 *
218 * @param out the new standard output stream
219 *
220 * @since 1.1
221 */
222 public static void setOut(PrintStream out) {
223 setOut0(out);
224 }
225
226 /**
227 * Reassigns the "standard" error output stream.
228 *
229 * @param err the new standard error output stream.
230 *
231 * @since 1.1
232 */
233 public static void setErr(PrintStream err) {
234 setErr0(err);
235 }
236
237 private static volatile Console cons;
238
239 /**
240 * Returns the unique {@link Console Console} object associated
241 * with the current Java virtual machine, if any.
242 *
243 * @return The system console, if any, otherwise {@code null}.
244 * @see Console
245 *
246 * @since 1.6
247 */
248 public static Console console() {
249 Console c;
250 if ((c = cons) == null) {
251 synchronized (System.class) {
252 if ((c = cons) == null) {
253 cons = c = SharedSecrets.getJavaIOAccess().console();
254 }
255 }
256 }
257 return c;
258 }
259
260 /**
261 * Returns the channel inherited from the entity that created this
262 * Java virtual machine.
263 *
264 * This method returns the channel obtained by invoking the
265 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
266 * inheritedChannel} method of the system-wide default
267 * {@link java.nio.channels.spi.SelectorProvider} object.
268 *
269 * <p> In addition to the network-oriented channels described in
270 * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
271 * inheritedChannel}, this method may return other kinds of
272 * channels in the future.
273 *
274 * @return The inherited channel, if any, otherwise {@code null}.
275 *
276 * @throws IOException
277 * If an I/O error occurs
278 *
279 * @since 1.5
280 */
281 public static Channel inheritedChannel() throws IOException {
282 return SelectorProvider.provider().inheritedChannel();
283 }
284
285 private static native void setIn0(InputStream in);
286 private static native void setOut0(PrintStream out);
287 private static native void setErr0(PrintStream err);
288
289 /**
290 * Throws {@code UnsupportedOperationException}. Setting a security manager
291 * is not supported.
292 *
293 * @param sm ignored
294 * @throws UnsupportedOperationException always
295 * @see #getSecurityManager
296 * @deprecated This method originally set
297 * {@linkplain SecurityManager the system-wide Security Manager}.
298 * Setting a Security Manager is no longer supported. There is no
299 * replacement for the Security Manager or this method.
300 */
301 @Deprecated(since="17", forRemoval=true)
302 public static void setSecurityManager(@SuppressWarnings("removal") SecurityManager sm) {
303 throw new UnsupportedOperationException(
304 "Setting a Security Manager is not supported");
305 }
306
307 /**
308 * Returns {@code null}. Setting a security manager is not supported.
309 *
310 * @return {@code null}
311 * @see #setSecurityManager
312 * @deprecated This method originally returned
313 * {@linkplain SecurityManager the system-wide Security Manager}.
314 * Setting a Security Manager is no longer supported. There is no
315 * replacement for the Security Manager or this method.
316 */
317 @SuppressWarnings("removal")
318 @Deprecated(since="17", forRemoval=true)
319 public static SecurityManager getSecurityManager() {
320 return null;
321 }
322
323 /**
324 * Returns the current time in milliseconds. Note that
325 * while the unit of time of the return value is a millisecond,
326 * the granularity of the value depends on the underlying
327 * operating system and may be larger. For example, many
328 * operating systems measure time in units of tens of
329 * milliseconds.
330 *
331 * <p> See the description of the class {@code Date} for
332 * a discussion of slight discrepancies that may arise between
333 * "computer time" and coordinated universal time (UTC).
334 *
335 * @return the difference, measured in milliseconds, between
336 * the current time and midnight, January 1, 1970 UTC.
337 * @see java.util.Date
338 */
339 @IntrinsicCandidate
340 public static native long currentTimeMillis();
341
342 /**
343 * Returns the current value of the running Java Virtual Machine's
344 * high-resolution time source, in nanoseconds.
345 *
346 * This method can only be used to measure elapsed time and is
347 * not related to any other notion of system or wall-clock time.
348 * The value returned represents nanoseconds since some fixed but
349 * arbitrary <i>origin</i> time (perhaps in the future, so values
350 * may be negative). The same origin is used by all invocations of
351 * this method in an instance of a Java virtual machine; other
352 * virtual machine instances are likely to use a different origin.
353 *
354 * <p>This method provides nanosecond precision, but not necessarily
355 * nanosecond resolution (that is, how frequently the value changes)
356 * - no guarantees are made except that the resolution is at least as
357 * good as that of {@link #currentTimeMillis()}.
358 *
359 * <p>Differences in successive calls that span greater than
360 * approximately 292 years (2<sup>63</sup> nanoseconds) will not
361 * correctly compute elapsed time due to numerical overflow.
362 *
363 * <p>The values returned by this method become meaningful only when
364 * the difference between two such values, obtained within the same
365 * instance of a Java virtual machine, is computed.
366 *
367 * <p>For example, to measure how long some code takes to execute:
368 * <pre> {@code
369 * long startTime = System.nanoTime();
370 * // ... the code being measured ...
371 * long elapsedNanos = System.nanoTime() - startTime;}</pre>
372 *
373 * <p>To compare elapsed time against a timeout, use <pre> {@code
374 * if (System.nanoTime() - startTime >= timeoutNanos) ...}</pre>
375 * instead of <pre> {@code
376 * if (System.nanoTime() >= startTime + timeoutNanos) ...}</pre>
377 * because of the possibility of numerical overflow.
378 *
379 * @return the current value of the running Java Virtual Machine's
380 * high-resolution time source, in nanoseconds
381 * @since 1.5
382 */
383 @IntrinsicCandidate
384 public static native long nanoTime();
385
386 /**
387 * Copies an array from the specified source array, beginning at the
388 * specified position, to the specified position of the destination array.
389 * A subsequence of array components are copied from the source
390 * array referenced by {@code src} to the destination array
391 * referenced by {@code dest}. The number of components copied is
392 * equal to the {@code length} argument. The components at
393 * positions {@code srcPos} through
394 * {@code srcPos+length-1} in the source array are copied into
395 * positions {@code destPos} through
396 * {@code destPos+length-1}, respectively, of the destination
397 * array.
398 * <p>
399 * If the {@code src} and {@code dest} arguments refer to the
400 * same array object, then the copying is performed as if the
401 * components at positions {@code srcPos} through
402 * {@code srcPos+length-1} were first copied to a temporary
403 * array with {@code length} components and then the contents of
404 * the temporary array were copied into positions
405 * {@code destPos} through {@code destPos+length-1} of the
406 * destination array.
407 * <p>
408 * If {@code dest} is {@code null}, then a
409 * {@code NullPointerException} is thrown.
410 * <p>
411 * If {@code src} is {@code null}, then a
412 * {@code NullPointerException} is thrown and the destination
413 * array is not modified.
414 * <p>
415 * Otherwise, if any of the following is true, an
416 * {@code ArrayStoreException} is thrown and the destination is
417 * not modified:
418 * <ul>
419 * <li>The {@code src} argument refers to an object that is not an
420 * array.
421 * <li>The {@code dest} argument refers to an object that is not an
422 * array.
423 * <li>The {@code src} argument and {@code dest} argument refer
424 * to arrays whose component types are different primitive types.
425 * <li>The {@code src} argument refers to an array with a primitive
426 * component type and the {@code dest} argument refers to an array
427 * with a reference component type.
428 * <li>The {@code src} argument refers to an array with a reference
429 * component type and the {@code dest} argument refers to an array
430 * with a primitive component type.
431 * </ul>
432 * <p>
433 * Otherwise, if any of the following is true, an
434 * {@code IndexOutOfBoundsException} is
435 * thrown and the destination is not modified:
436 * <ul>
437 * <li>The {@code srcPos} argument is negative.
438 * <li>The {@code destPos} argument is negative.
439 * <li>The {@code length} argument is negative.
440 * <li>{@code srcPos+length} is greater than
441 * {@code src.length}, the length of the source array.
442 * <li>{@code destPos+length} is greater than
443 * {@code dest.length}, the length of the destination array.
444 * </ul>
445 * <p>
446 * Otherwise, if any actual component of the source array from
447 * position {@code srcPos} through
448 * {@code srcPos+length-1} cannot be converted to the component
449 * type of the destination array by assignment conversion, an
450 * {@code ArrayStoreException} is thrown. In this case, let
451 * <b><i>k</i></b> be the smallest nonnegative integer less than
452 * length such that {@code src[srcPos+}<i>k</i>{@code ]}
453 * cannot be converted to the component type of the destination
454 * array; when the exception is thrown, source array components from
455 * positions {@code srcPos} through
456 * {@code srcPos+}<i>k</i>{@code -1}
457 * will already have been copied to destination array positions
458 * {@code destPos} through
459 * {@code destPos+}<i>k</I>{@code -1} and no other
460 * positions of the destination array will have been modified.
461 * (Because of the restrictions already itemized, this
462 * paragraph effectively applies only to the situation where both
463 * arrays have component types that are reference types.)
464 *
465 * @param src the source array.
466 * @param srcPos starting position in the source array.
467 * @param dest the destination array.
468 * @param destPos starting position in the destination data.
469 * @param length the number of array elements to be copied.
470 * @throws IndexOutOfBoundsException if copying would cause
471 * access of data outside array bounds.
472 * @throws ArrayStoreException if an element in the {@code src}
473 * array could not be stored into the {@code dest} array
474 * because of a type mismatch.
475 * @throws NullPointerException if either {@code src} or
476 * {@code dest} is {@code null}.
477 */
478 @IntrinsicCandidate
479 public static native void arraycopy(Object src, int srcPos,
480 Object dest, int destPos,
481 int length);
482
483 /**
484 * Returns the same hash code for the given object as
485 * would be returned by the default method hashCode(),
486 * whether or not the given object's class overrides
487 * hashCode().
488 * The hash code for the null reference is zero.
489 *
490 * @param x object for which the hashCode is to be calculated
491 * @return the hashCode
492 * @since 1.1
493 * @see Object#hashCode
494 * @see java.util.Objects#hashCode(Object)
495 */
496 @IntrinsicCandidate
497 public static native int identityHashCode(Object x);
498
499 /**
500 * System properties.
501 *
502 * See {@linkplain #getProperties getProperties} for details.
503 */
504 private static Properties props;
505
506 /**
507 * Determines the current system properties.
508 * <p>
509 * The current set of system properties for use by the
510 * {@link #getProperty(String)} method is returned as a
511 * {@code Properties} object. If there is no current set of
512 * system properties, a set of system properties is first created and
513 * initialized. This set of system properties includes a value
514 * for each of the following keys unless the description of the associated
515 * value indicates that the value is optional.
516 * <table class="striped" style="text-align:left">
517 * <caption style="display:none">Shows property keys and associated values</caption>
518 * <thead>
519 * <tr><th scope="col">Key</th>
520 * <th scope="col">Description of Associated Value</th></tr>
521 * </thead>
522 * <tbody>
523 * <tr><th scope="row">{@systemProperty java.version}</th>
524 * <td>Java Runtime Environment version, which may be interpreted
525 * as a {@link Runtime.Version}</td></tr>
526 * <tr><th scope="row">{@systemProperty java.version.date}</th>
527 * <td>Java Runtime Environment version date, in ISO-8601 YYYY-MM-DD
528 * format, which may be interpreted as a {@link
529 * java.time.LocalDate}</td></tr>
530 * <tr><th scope="row">{@systemProperty java.vendor}</th>
531 * <td>Java Runtime Environment vendor</td></tr>
532 * <tr><th scope="row">{@systemProperty java.vendor.url}</th>
533 * <td>Java vendor URL</td></tr>
534 * <tr><th scope="row">{@systemProperty java.vendor.version}</th>
535 * <td>Java vendor version <em>(optional)</em> </td></tr>
536 * <tr><th scope="row">{@systemProperty java.home}</th>
537 * <td>Java installation directory</td></tr>
538 * <tr><th scope="row">{@systemProperty java.vm.specification.version}</th>
539 * <td>Java Virtual Machine specification version, whose value is the
540 * {@linkplain Runtime.Version#feature feature} element of the
541 * {@linkplain Runtime#version() runtime version}</td></tr>
542 * <tr><th scope="row">{@systemProperty java.vm.specification.vendor}</th>
543 * <td>Java Virtual Machine specification vendor</td></tr>
544 * <tr><th scope="row">{@systemProperty java.vm.specification.name}</th>
545 * <td>Java Virtual Machine specification name</td></tr>
546 * <tr><th scope="row">{@systemProperty java.vm.version}</th>
547 * <td>Java Virtual Machine implementation version which may be
548 * interpreted as a {@link Runtime.Version}</td></tr>
549 * <tr><th scope="row">{@systemProperty java.vm.vendor}</th>
550 * <td>Java Virtual Machine implementation vendor</td></tr>
551 * <tr><th scope="row">{@systemProperty java.vm.name}</th>
552 * <td>Java Virtual Machine implementation name</td></tr>
553 * <tr><th scope="row">{@systemProperty java.specification.version}</th>
554 * <td>Java Runtime Environment specification version, whose value is
555 * the {@linkplain Runtime.Version#feature feature} element of the
556 * {@linkplain Runtime#version() runtime version}</td></tr>
557 * <tr><th scope="row">{@systemProperty java.specification.maintenance.version}</th>
558 * <td>Java Runtime Environment specification maintenance version,
559 * may be interpreted as a positive integer <em>(optional, see below)</em></td></tr>
560 * <tr><th scope="row">{@systemProperty java.specification.vendor}</th>
561 * <td>Java Runtime Environment specification vendor</td></tr>
562 * <tr><th scope="row">{@systemProperty java.specification.name}</th>
563 * <td>Java Runtime Environment specification name</td></tr>
564 * <tr><th scope="row">{@systemProperty java.class.version}</th>
565 * <td>{@linkplain java.lang.reflect.ClassFileFormatVersion#latest() Latest}
566 * Java class file format version recognized by the Java runtime as {@code "MAJOR.MINOR"}
567 * where {@link java.lang.reflect.ClassFileFormatVersion#major() MAJOR} and {@code MINOR}
568 * are both formatted as decimal integers</td></tr>
569 * <tr><th scope="row">{@systemProperty java.class.path}</th>
570 * <td>Java class path (refer to
571 * {@link ClassLoader#getSystemClassLoader()} for details)</td></tr>
572 * <tr><th scope="row">{@systemProperty java.library.path}</th>
573 * <td>List of paths to search when loading libraries</td></tr>
574 * <tr><th scope="row">{@systemProperty java.io.tmpdir}</th>
575 * <td>Default temp file path</td></tr>
576 * <tr><th scope="row">{@systemProperty os.name}</th>
577 * <td>Operating system name</td></tr>
578 * <tr><th scope="row">{@systemProperty os.arch}</th>
579 * <td>Operating system architecture</td></tr>
580 * <tr><th scope="row">{@systemProperty os.version}</th>
581 * <td>Operating system version</td></tr>
582 * <tr><th scope="row">{@systemProperty file.separator}</th>
583 * <td>File separator ("/" on UNIX)</td></tr>
584 * <tr><th scope="row">{@systemProperty path.separator}</th>
585 * <td>Path separator (":" on UNIX)</td></tr>
586 * <tr><th scope="row">{@systemProperty line.separator}</th>
587 * <td>Line separator ("\n" on UNIX)</td></tr>
588 * <tr><th scope="row">{@systemProperty user.name}</th>
589 * <td>User's account name</td></tr>
590 * <tr><th scope="row">{@systemProperty user.home}</th>
591 * <td>User's home directory</td></tr>
592 * <tr><th scope="row">{@systemProperty user.dir}</th>
593 * <td>User's current working directory</td></tr>
594 * <tr><th scope="row">{@systemProperty native.encoding}</th>
595 * <td>Character encoding name derived from the host environment and
596 * the user's settings. Setting this system property on the command line
597 * has no effect.</td></tr>
598 * <tr><th scope="row">{@systemProperty stdin.encoding}</th>
599 * <td>Character encoding name for {@link System#in System.in}.
600 * The Java runtime can be started with the system property set to {@code UTF-8}.
601 * Starting it with the property set to another value results in unspecified behavior.
602 * <tr><th scope="row">{@systemProperty stdout.encoding}</th>
603 * <td>Character encoding name for {@link System#out System.out} and
604 * {@link System#console() System.console()}.
605 * The Java runtime can be started with the system property set to {@code UTF-8}.
606 * Starting it with the property set to another value results in unspecified behavior.
607 * <tr><th scope="row">{@systemProperty stderr.encoding}</th>
608 * <td>Character encoding name for {@link System#err System.err}.
609 * The Java runtime can be started with the system property set to {@code UTF-8}.
610 * Starting it with the property set to another value results in unspecified behavior.
611 * </tbody>
612 * </table>
613 * <p>
614 * The {@code java.specification.maintenance.version} property is
615 * defined if the specification implemented by this runtime at the
616 * time of its construction had undergone a <a
617 * href="https://jcp.org/en/procedures/jcp2#3.6.4">maintenance
618 * release</a>. When defined, its value identifies that
619 * maintenance release. To indicate the first maintenance release
620 * this property will have the value {@code "1"}, to indicate the
621 * second maintenance release this property will have the value
622 * {@code "2"}, and so on.
623 * <p>
624 * Multiple paths in a system property value are separated by the path
625 * separator character of the platform.
626 * <p>
627 * Additional locale-related system properties defined by the
628 * {@link Locale##default_locale Default Locale} section in the {@code Locale}
629 * class description may also be obtained with this method.
630 *
631 * @apiNote
632 * <strong>Changing a standard system property may have unpredictable results
633 * unless otherwise specified.</strong>
634 * Property values may be cached during initialization or on first use.
635 * Setting a standard property after initialization using {@link #getProperties()},
636 * {@link #setProperties(Properties)}, {@link #setProperty(String, String)}, or
637 * {@link #clearProperty(String)} may not have the desired effect.
638 *
639 * @implNote
640 * In addition to the standard system properties, the system
641 * properties may include the following keys:
642 * <table class="striped">
643 * <caption style="display:none">Shows property keys and associated values</caption>
644 * <thead>
645 * <tr><th scope="col">Key</th>
646 * <th scope="col">Description of Associated Value</th></tr>
647 * </thead>
648 * <tbody>
649 * <tr><th scope="row">{@systemProperty jdk.module.path}</th>
650 * <td>The application module path</td></tr>
651 * <tr><th scope="row">{@systemProperty jdk.module.upgrade.path}</th>
652 * <td>The upgrade module path</td></tr>
653 * <tr><th scope="row">{@systemProperty jdk.module.main}</th>
654 * <td>The module name of the initial/main module</td></tr>
655 * <tr><th scope="row">{@systemProperty jdk.module.main.class}</th>
656 * <td>The main class name of the initial module</td></tr>
657 * <tr><th scope="row">{@systemProperty file.encoding}</th>
658 * <td>The name of the default charset, defaults to {@code UTF-8}.
659 * The property may be set on the command line to the value
660 * {@code UTF-8} or {@code COMPAT}. If set on the command line to
661 * the value {@code COMPAT} then the value is replaced with the
662 * value of the {@code native.encoding} property during startup.
663 * Setting the property to a value other than {@code UTF-8} or
664 * {@code COMPAT} results in unspecified behavior.
665 * </td></tr>
666 * </tbody>
667 * </table>
668 *
669 * @return the system properties
670 * @see #setProperties
671 * @see java.util.Properties
672 */
673 public static Properties getProperties() {
674 return props;
675 }
676
677 /**
678 * Returns the system-dependent line separator string. It always
679 * returns the same value - the initial value of the {@linkplain
680 * #getProperty(String) system property} {@code line.separator}.
681 *
682 * <p>On UNIX systems, it returns {@code "\n"}; on Microsoft
683 * Windows systems it returns {@code "\r\n"}.
684 *
685 * @return the system-dependent line separator string
686 * @since 1.7
687 */
688 public static String lineSeparator() {
689 return lineSeparator;
690 }
691
692 private static String lineSeparator;
693
694 /**
695 * Sets the system properties to the {@code Properties} argument.
696 * <p>
697 * The argument becomes the current set of system properties for use
698 * by the {@link #getProperty(String)} method. If the argument is
699 * {@code null}, then the current set of system properties is
700 * forgotten.
701 *
702 * @apiNote
703 * <strong>Changing a standard system property may have unpredictable results
704 * unless otherwise specified</strong>.
705 * See {@linkplain #getProperties getProperties} for details.
706 *
707 * @param props the new system properties.
708 * @see #getProperties
709 * @see java.util.Properties
710 */
711 public static void setProperties(Properties props) {
712 if (props == null) {
713 Map<String, String> tempProps = SystemProps.initProperties();
714 VersionProps.init(tempProps);
715 props = createProperties(tempProps);
716 }
717 System.props = props;
718 }
719
720 /**
721 * Gets the system property indicated by the specified key.
722 * <p>
723 * If there is no current set of system properties, a set of system
724 * properties is first created and initialized in the same manner as
725 * for the {@code getProperties} method.
726 *
727 * @apiNote
728 * <strong>Changing a standard system property may have unpredictable results
729 * unless otherwise specified</strong>.
730 * See {@linkplain #getProperties getProperties} for details.
731 *
732 * @param key the name of the system property.
733 * @return the string value of the system property,
734 * or {@code null} if there is no property with that key.
735 *
736 * @throws NullPointerException if {@code key} is {@code null}.
737 * @throws IllegalArgumentException if {@code key} is empty.
738 * @see #setProperty
739 * @see java.lang.System#getProperties()
740 */
741 public static String getProperty(String key) {
742 checkKey(key);
743 return props.getProperty(key);
744 }
745
746 /**
747 * Gets the system property indicated by the specified key.
748 * <p>
749 * If there is no current set of system properties, a set of system
750 * properties is first created and initialized in the same manner as
751 * for the {@code getProperties} method.
752 *
753 * @param key the name of the system property.
754 * @param def a default value.
755 * @return the string value of the system property,
756 * or the default value if there is no property with that key.
757 *
758 * @throws NullPointerException if {@code key} is {@code null}.
759 * @throws IllegalArgumentException if {@code key} is empty.
760 * @see #setProperty
761 * @see java.lang.System#getProperties()
762 */
763 public static String getProperty(String key, String def) {
764 checkKey(key);
765 return props.getProperty(key, def);
766 }
767
768 /**
769 * Sets the system property indicated by the specified key.
770 *
771 * @apiNote
772 * <strong>Changing a standard system property may have unpredictable results
773 * unless otherwise specified</strong>.
774 * See {@linkplain #getProperties getProperties} for details.
775 *
776 * @param key the name of the system property.
777 * @param value the value of the system property.
778 * @return the previous value of the system property,
779 * or {@code null} if it did not have one.
780 *
781 * @throws NullPointerException if {@code key} or
782 * {@code value} is {@code null}.
783 * @throws IllegalArgumentException if {@code key} is empty.
784 * @see #getProperty
785 * @see java.lang.System#getProperty(java.lang.String)
786 * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
787 * @since 1.2
788 */
789 public static String setProperty(String key, String value) {
790 checkKey(key);
791 return (String) props.setProperty(key, value);
792 }
793
794 /**
795 * Removes the system property indicated by the specified key.
796 *
797 * @apiNote
798 * <strong>Changing a standard system property may have unpredictable results
799 * unless otherwise specified</strong>.
800 * See {@linkplain #getProperties getProperties} method for details.
801 *
802 * @param key the name of the system property to be removed.
803 * @return the previous string value of the system property,
804 * or {@code null} if there was no property with that key.
805 *
806 * @throws NullPointerException if {@code key} is {@code null}.
807 * @throws IllegalArgumentException if {@code key} is empty.
808 * @see #getProperty
809 * @see #setProperty
810 * @see java.util.Properties
811 * @since 1.5
812 */
813 public static String clearProperty(String key) {
814 checkKey(key);
815 return (String) props.remove(key);
816 }
817
818 private static void checkKey(String key) {
819 if (key == null) {
820 throw new NullPointerException("key can't be null");
821 }
822 if (key.isEmpty()) {
823 throw new IllegalArgumentException("key can't be empty");
824 }
825 }
826
827 /**
828 * Gets the value of the specified environment variable. An
829 * environment variable is a system-dependent external named
830 * value.
831 *
832 * <p><a id="EnvironmentVSSystemProperties"><i>System
833 * properties</i> and <i>environment variables</i></a> are both
834 * conceptually mappings between names and values. Both
835 * mechanisms can be used to pass user-defined information to a
836 * Java process. Environment variables have a more global effect,
837 * because they are visible to all descendants of the process
838 * which defines them, not just the immediate Java subprocess.
839 * They can have subtly different semantics, such as case
840 * insensitivity, on different operating systems. For these
841 * reasons, environment variables are more likely to have
842 * unintended side effects. It is best to use system properties
843 * where possible. Environment variables should be used when a
844 * global effect is desired, or when an external system interface
845 * requires an environment variable (such as {@code PATH}).
846 *
847 * <p>On UNIX systems the alphabetic case of {@code name} is
848 * typically significant, while on Microsoft Windows systems it is
849 * typically not. For example, the expression
850 * {@code System.getenv("FOO").equals(System.getenv("foo"))}
851 * is likely to be true on Microsoft Windows.
852 *
853 * @param name the name of the environment variable
854 * @return the string value of the variable, or {@code null}
855 * if the variable is not defined in the system environment
856 * @throws NullPointerException if {@code name} is {@code null}
857 * @see #getenv()
858 * @see ProcessBuilder#environment()
859 */
860 public static String getenv(String name) {
861 return ProcessEnvironment.getenv(name);
862 }
863
864
865 /**
866 * Returns an unmodifiable string map view of the current system environment.
867 * The environment is a system-dependent mapping from names to
868 * values which is passed from parent to child processes.
869 *
870 * <p>If the system does not support environment variables, an
871 * empty map is returned.
872 *
873 * <p>The returned map will never contain null keys or values.
874 * Attempting to query the presence of a null key or value will
875 * throw a {@link NullPointerException}. Attempting to query
876 * the presence of a key or value which is not of type
877 * {@link String} will throw a {@link ClassCastException}.
878 *
879 * <p>The returned map and its collection views may not obey the
880 * general contract of the {@link Object#equals} and
881 * {@link Object#hashCode} methods.
882 *
883 * <p>The returned map is typically case-sensitive on all platforms.
884 *
885 * <p>When passing information to a Java subprocess,
886 * <a href=#EnvironmentVSSystemProperties>system properties</a>
887 * are generally preferred over environment variables.
888 *
889 * @return the environment as a map of variable names to values
890 * @see #getenv(String)
891 * @see ProcessBuilder#environment()
892 * @since 1.5
893 */
894 public static java.util.Map<String,String> getenv() {
895 return ProcessEnvironment.getenv();
896 }
897
898 /**
899 * {@code System.Logger} instances log messages that will be
900 * routed to the underlying logging framework the {@link System.LoggerFinder
901 * LoggerFinder} uses.
902 *
903 * {@code System.Logger} instances are typically obtained from
904 * the {@link java.lang.System System} class, by calling
905 * {@link java.lang.System#getLogger(java.lang.String) System.getLogger(loggerName)}
906 * or {@link java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle)
907 * System.getLogger(loggerName, bundle)}.
908 *
909 * @see java.lang.System#getLogger(java.lang.String)
910 * @see java.lang.System#getLogger(java.lang.String, java.util.ResourceBundle)
911 * @see java.lang.System.LoggerFinder
912 *
913 * @since 9
914 */
915 public interface Logger {
916
917 /**
918 * System {@linkplain Logger loggers} levels.
919 *
920 * A level has a {@linkplain #getName() name} and {@linkplain
921 * #getSeverity() severity}.
922 * Level values are {@link #ALL}, {@link #TRACE}, {@link #DEBUG},
923 * {@link #INFO}, {@link #WARNING}, {@link #ERROR}, {@link #OFF},
924 * by order of increasing severity.
925 * <br>
926 * {@link #ALL} and {@link #OFF}
927 * are simple markers with severities mapped respectively to
928 * {@link java.lang.Integer#MIN_VALUE Integer.MIN_VALUE} and
929 * {@link java.lang.Integer#MAX_VALUE Integer.MAX_VALUE}.
930 * <p>
931 * <b>Severity values and Mapping to {@code java.util.logging.Level}.</b>
932 * <p>
933 * {@linkplain System.Logger.Level System logger levels} are mapped to
934 * {@linkplain java.logging/java.util.logging.Level java.util.logging levels}
935 * of corresponding severity.
936 * <br>The mapping is as follows:
937 * <br><br>
938 * <table class="striped">
939 * <caption>System.Logger Severity Level Mapping</caption>
940 * <thead>
941 * <tr><th scope="col">System.Logger Levels</th>
942 * <th scope="col">java.util.logging Levels</th>
943 * </thead>
944 * <tbody>
945 * <tr><th scope="row">{@link Logger.Level#ALL ALL}</th>
946 * <td>{@link java.logging/java.util.logging.Level#ALL ALL}</td>
947 * <tr><th scope="row">{@link Logger.Level#TRACE TRACE}</th>
948 * <td>{@link java.logging/java.util.logging.Level#FINER FINER}</td>
949 * <tr><th scope="row">{@link Logger.Level#DEBUG DEBUG}</th>
950 * <td>{@link java.logging/java.util.logging.Level#FINE FINE}</td>
951 * <tr><th scope="row">{@link Logger.Level#INFO INFO}</th>
952 * <td>{@link java.logging/java.util.logging.Level#INFO INFO}</td>
953 * <tr><th scope="row">{@link Logger.Level#WARNING WARNING}</th>
954 * <td>{@link java.logging/java.util.logging.Level#WARNING WARNING}</td>
955 * <tr><th scope="row">{@link Logger.Level#ERROR ERROR}</th>
956 * <td>{@link java.logging/java.util.logging.Level#SEVERE SEVERE}</td>
957 * <tr><th scope="row">{@link Logger.Level#OFF OFF}</th>
958 * <td>{@link java.logging/java.util.logging.Level#OFF OFF}</td>
959 * </tbody>
960 * </table>
961 *
962 * @since 9
963 *
964 * @see java.lang.System.LoggerFinder
965 * @see java.lang.System.Logger
966 */
967 @SuppressWarnings("doclint:reference") // cross-module links
968 public enum Level {
969
970 // for convenience, we're reusing java.util.logging.Level int values
971 // the mapping logic in sun.util.logging.PlatformLogger depends
972 // on this.
973 /**
974 * A marker to indicate that all levels are enabled.
975 * This level {@linkplain #getSeverity() severity} is
976 * {@link Integer#MIN_VALUE}.
977 */
978 ALL(Integer.MIN_VALUE), // typically mapped to/from j.u.l.Level.ALL
979 /**
980 * {@code TRACE} level: usually used to log diagnostic information.
981 * This level {@linkplain #getSeverity() severity} is
982 * {@code 400}.
983 */
984 TRACE(400), // typically mapped to/from j.u.l.Level.FINER
985 /**
986 * {@code DEBUG} level: usually used to log debug information traces.
987 * This level {@linkplain #getSeverity() severity} is
988 * {@code 500}.
989 */
990 DEBUG(500), // typically mapped to/from j.u.l.Level.FINEST/FINE/CONFIG
991 /**
992 * {@code INFO} level: usually used to log information messages.
993 * This level {@linkplain #getSeverity() severity} is
994 * {@code 800}.
995 */
996 INFO(800), // typically mapped to/from j.u.l.Level.INFO
997 /**
998 * {@code WARNING} level: usually used to log warning messages.
999 * This level {@linkplain #getSeverity() severity} is
1000 * {@code 900}.
1001 */
1002 WARNING(900), // typically mapped to/from j.u.l.Level.WARNING
1003 /**
1004 * {@code ERROR} level: usually used to log error messages.
1005 * This level {@linkplain #getSeverity() severity} is
1006 * {@code 1000}.
1007 */
1008 ERROR(1000), // typically mapped to/from j.u.l.Level.SEVERE
1009 /**
1010 * A marker to indicate that all levels are disabled.
1011 * This level {@linkplain #getSeverity() severity} is
1012 * {@link Integer#MAX_VALUE}.
1013 */
1014 OFF(Integer.MAX_VALUE); // typically mapped to/from j.u.l.Level.OFF
1015
1016 private final int severity;
1017
1018 private Level(int severity) {
1019 this.severity = severity;
1020 }
1021
1022 /**
1023 * Returns the name of this level.
1024 * @return this level {@linkplain #name()}.
1025 */
1026 public final String getName() {
1027 return name();
1028 }
1029
1030 /**
1031 * Returns the severity of this level.
1032 * A higher severity means a more severe condition.
1033 * @return this level severity.
1034 */
1035 public final int getSeverity() {
1036 return severity;
1037 }
1038 }
1039
1040 /**
1041 * Returns the name of this logger.
1042 *
1043 * @return the logger name.
1044 */
1045 public String getName();
1046
1047 /**
1048 * Checks if a message of the given level would be logged by
1049 * this logger.
1050 *
1051 * @param level the log message level.
1052 * @return {@code true} if the given log message level is currently
1053 * being logged.
1054 *
1055 * @throws NullPointerException if {@code level} is {@code null}.
1056 */
1057 public boolean isLoggable(Level level);
1058
1059 /**
1060 * Logs a message.
1061 *
1062 * @implSpec The default implementation for this method calls
1063 * {@code this.log(level, (ResourceBundle)null, msg, (Object[])null);}
1064 *
1065 * @param level the log message level.
1066 * @param msg the string message (or a key in the message catalog, if
1067 * this logger is a {@link
1068 * LoggerFinder#getLocalizedLogger(java.lang.String,
1069 * java.util.ResourceBundle, java.lang.Module) localized logger});
1070 * can be {@code null}.
1071 *
1072 * @throws NullPointerException if {@code level} is {@code null}.
1073 */
1074 public default void log(Level level, String msg) {
1075 log(level, (ResourceBundle) null, msg, (Object[]) null);
1076 }
1077
1078 /**
1079 * Logs a lazily supplied message.
1080 *
1081 * If the logger is currently enabled for the given log message level
1082 * then a message is logged that is the result produced by the
1083 * given supplier function. Otherwise, the supplier is not operated on.
1084 *
1085 * @implSpec When logging is enabled for the given level, the default
1086 * implementation for this method calls
1087 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), (Object[])null);}
1088 *
1089 * @param level the log message level.
1090 * @param msgSupplier a supplier function that produces a message.
1091 *
1092 * @throws NullPointerException if {@code level} is {@code null},
1093 * or {@code msgSupplier} is {@code null}.
1094 */
1095 public default void log(Level level, Supplier<String> msgSupplier) {
1096 Objects.requireNonNull(msgSupplier);
1097 if (isLoggable(Objects.requireNonNull(level))) {
1098 log(level, (ResourceBundle) null, msgSupplier.get(), (Object[]) null);
1099 }
1100 }
1101
1102 /**
1103 * Logs a message produced from the given object.
1104 *
1105 * If the logger is currently enabled for the given log message level then
1106 * a message is logged that, by default, is the result produced from
1107 * calling toString on the given object.
1108 * Otherwise, the object is not operated on.
1109 *
1110 * @implSpec When logging is enabled for the given level, the default
1111 * implementation for this method calls
1112 * {@code this.log(level, (ResourceBundle)null, obj.toString(), (Object[])null);}
1113 *
1114 * @param level the log message level.
1115 * @param obj the object to log.
1116 *
1117 * @throws NullPointerException if {@code level} is {@code null}, or
1118 * {@code obj} is {@code null}.
1119 */
1120 public default void log(Level level, Object obj) {
1121 Objects.requireNonNull(obj);
1122 if (isLoggable(Objects.requireNonNull(level))) {
1123 this.log(level, (ResourceBundle) null, obj.toString(), (Object[]) null);
1124 }
1125 }
1126
1127 /**
1128 * Logs a message associated with a given throwable.
1129 *
1130 * @implSpec The default implementation for this method calls
1131 * {@code this.log(level, (ResourceBundle)null, msg, thrown);}
1132 *
1133 * @param level the log message level.
1134 * @param msg the string message (or a key in the message catalog, if
1135 * this logger is a {@link
1136 * LoggerFinder#getLocalizedLogger(java.lang.String,
1137 * java.util.ResourceBundle, java.lang.Module) localized logger});
1138 * can be {@code null}.
1139 * @param thrown a {@code Throwable} associated with the log message;
1140 * can be {@code null}.
1141 *
1142 * @throws NullPointerException if {@code level} is {@code null}.
1143 */
1144 public default void log(Level level, String msg, Throwable thrown) {
1145 this.log(level, null, msg, thrown);
1146 }
1147
1148 /**
1149 * Logs a lazily supplied message associated with a given throwable.
1150 *
1151 * If the logger is currently enabled for the given log message level
1152 * then a message is logged that is the result produced by the
1153 * given supplier function. Otherwise, the supplier is not operated on.
1154 *
1155 * @implSpec When logging is enabled for the given level, the default
1156 * implementation for this method calls
1157 * {@code this.log(level, (ResourceBundle)null, msgSupplier.get(), thrown);}
1158 *
1159 * @param level one of the log message level identifiers.
1160 * @param msgSupplier a supplier function that produces a message.
1161 * @param thrown a {@code Throwable} associated with log message;
1162 * can be {@code null}.
1163 *
1164 * @throws NullPointerException if {@code level} is {@code null}, or
1165 * {@code msgSupplier} is {@code null}.
1166 */
1167 public default void log(Level level, Supplier<String> msgSupplier,
1168 Throwable thrown) {
1169 Objects.requireNonNull(msgSupplier);
1170 if (isLoggable(Objects.requireNonNull(level))) {
1171 this.log(level, null, msgSupplier.get(), thrown);
1172 }
1173 }
1174
1175 /**
1176 * Logs a message with an optional list of parameters.
1177 *
1178 * @implSpec The default implementation for this method calls
1179 * {@code this.log(level, (ResourceBundle)null, format, params);}
1180 *
1181 * @param level one of the log message level identifiers.
1182 * @param format the string message format in {@link
1183 * java.text.MessageFormat} format, (or a key in the message
1184 * catalog, if this logger is a {@link
1185 * LoggerFinder#getLocalizedLogger(java.lang.String,
1186 * java.util.ResourceBundle, java.lang.Module) localized logger});
1187 * can be {@code null}.
1188 * @param params an optional list of parameters to the message (may be
1189 * none).
1190 *
1191 * @throws NullPointerException if {@code level} is {@code null}.
1192 */
1193 public default void log(Level level, String format, Object... params) {
1194 this.log(level, null, format, params);
1195 }
1196
1197 /**
1198 * Logs a localized message associated with a given throwable.
1199 *
1200 * If the given resource bundle is non-{@code null}, the {@code msg}
1201 * string is localized using the given resource bundle.
1202 * Otherwise the {@code msg} string is not localized.
1203 *
1204 * @param level the log message level.
1205 * @param bundle a resource bundle to localize {@code msg}; can be
1206 * {@code null}.
1207 * @param msg the string message (or a key in the message catalog,
1208 * if {@code bundle} is not {@code null}); can be {@code null}.
1209 * @param thrown a {@code Throwable} associated with the log message;
1210 * can be {@code null}.
1211 *
1212 * @throws NullPointerException if {@code level} is {@code null}.
1213 */
1214 public void log(Level level, ResourceBundle bundle, String msg,
1215 Throwable thrown);
1216
1217 /**
1218 * Logs a message with resource bundle and an optional list of
1219 * parameters.
1220 *
1221 * If the given resource bundle is non-{@code null}, the {@code format}
1222 * string is localized using the given resource bundle.
1223 * Otherwise the {@code format} string is not localized.
1224 *
1225 * @param level the log message level.
1226 * @param bundle a resource bundle to localize {@code format}; can be
1227 * {@code null}.
1228 * @param format the string message format in {@link
1229 * java.text.MessageFormat} format, (or a key in the message
1230 * catalog if {@code bundle} is not {@code null}); can be {@code null}.
1231 * @param params an optional list of parameters to the message (may be
1232 * none).
1233 *
1234 * @throws NullPointerException if {@code level} is {@code null}.
1235 */
1236 public void log(Level level, ResourceBundle bundle, String format,
1237 Object... params);
1238 }
1239
1240 /**
1241 * The {@code LoggerFinder} service is responsible for creating, managing,
1242 * and configuring loggers to the underlying framework it uses.
1243 *
1244 * A logger finder is a concrete implementation of this class that has a
1245 * zero-argument constructor and implements the abstract methods defined
1246 * by this class.
1247 * The loggers returned from a logger finder are capable of routing log
1248 * messages to the logging backend this provider supports.
1249 * A given invocation of the Java Runtime maintains a single
1250 * system-wide LoggerFinder instance that is loaded as follows:
1251 * <ul>
1252 * <li>First it finds any custom {@code LoggerFinder} provider
1253 * using the {@link java.util.ServiceLoader} facility with the
1254 * {@linkplain ClassLoader#getSystemClassLoader() system class
1255 * loader}.</li>
1256 * <li>If no {@code LoggerFinder} provider is found, the system default
1257 * {@code LoggerFinder} implementation will be used.</li>
1258 * </ul>
1259 * <p>
1260 * An application can replace the logging backend
1261 * <i>even when the java.logging module is present</i>, by simply providing
1262 * and declaring an implementation of the {@link LoggerFinder} service.
1263 * <p>
1264 * <b>Default Implementation</b>
1265 * <p>
1266 * The system default {@code LoggerFinder} implementation uses
1267 * {@code java.util.logging} as the backend framework when the
1268 * {@code java.logging} module is present.
1269 * It returns a {@linkplain System.Logger logger} instance
1270 * that will route log messages to a {@link java.logging/java.util.logging.Logger
1271 * java.util.logging.Logger}. Otherwise, if {@code java.logging} is not
1272 * present, the default implementation will return a simple logger
1273 * instance that will route log messages of {@code INFO} level and above to
1274 * the console ({@code System.err}).
1275 * <p>
1276 * <b>Logging Configuration</b>
1277 * <p>
1278 * {@linkplain Logger Logger} instances obtained from the
1279 * {@code LoggerFinder} factory methods are not directly configurable by
1280 * the application. Configuration is the responsibility of the underlying
1281 * logging backend, and usually requires using APIs specific to that backend.
1282 * <p>For the default {@code LoggerFinder} implementation
1283 * using {@code java.util.logging} as its backend, refer to
1284 * {@link java.logging/java.util.logging java.util.logging} for logging configuration.
1285 * For the default {@code LoggerFinder} implementation returning simple loggers
1286 * when the {@code java.logging} module is absent, the configuration
1287 * is implementation dependent.
1288 * <p>
1289 * Usually an application that uses a logging framework will log messages
1290 * through a logger facade defined (or supported) by that framework.
1291 * Applications that wish to use an external framework should log
1292 * through the facade associated with that framework.
1293 * <p>
1294 * A system class that needs to log messages will typically obtain
1295 * a {@link System.Logger} instance to route messages to the logging
1296 * framework selected by the application.
1297 * <p>
1298 * Libraries and classes that only need loggers to produce log messages
1299 * should not attempt to configure loggers by themselves, as that
1300 * would make them dependent from a specific implementation of the
1301 * {@code LoggerFinder} service.
1302 * <p>
1303 * <b>Message Levels and Mapping to backend levels</b>
1304 * <p>
1305 * A logger finder is responsible for mapping from a {@code
1306 * System.Logger.Level} to a level supported by the logging backend it uses.
1307 * <br>The default LoggerFinder using {@code java.util.logging} as the backend
1308 * maps {@code System.Logger} levels to
1309 * {@linkplain java.logging/java.util.logging.Level java.util.logging} levels
1310 * of corresponding severity - as described in {@link Logger.Level
1311 * Logger.Level}.
1312 *
1313 * @see java.lang.System
1314 * @see java.lang.System.Logger
1315 *
1316 * @since 9
1317 */
1318 @SuppressWarnings("doclint:reference") // cross-module links
1319 public abstract static class LoggerFinder {
1320
1321 /**
1322 * Creates a new instance of {@code LoggerFinder}.
1323 *
1324 * @implNote It is recommended that a {@code LoggerFinder} service
1325 * implementation does not perform any heavy initialization in its
1326 * constructor, in order to avoid possible risks of deadlock or class
1327 * loading cycles during the instantiation of the service provider.
1328 */
1329 protected LoggerFinder() {
1330 }
1331
1332 /**
1333 * Returns an instance of {@link Logger Logger}
1334 * for the given {@code module}.
1335 *
1336 * @param name the name of the logger.
1337 * @param module the module for which the logger is being requested.
1338 *
1339 * @return a {@link Logger logger} suitable for use within the given
1340 * module.
1341 * @throws NullPointerException if {@code name} is {@code null} or
1342 * {@code module} is {@code null}.
1343 */
1344 public abstract Logger getLogger(String name, Module module);
1345
1346 /**
1347 * Returns a localizable instance of {@link Logger Logger}
1348 * for the given {@code module}.
1349 * The returned logger will use the provided resource bundle for
1350 * message localization.
1351 *
1352 * @implSpec By default, this method calls {@link
1353 * #getLogger(java.lang.String, java.lang.Module)
1354 * this.getLogger(name, module)} to obtain a logger, then wraps that
1355 * logger in a {@link Logger} instance where all methods that do not
1356 * take a {@link ResourceBundle} as parameter are redirected to one
1357 * which does - passing the given {@code bundle} for
1358 * localization. So for instance, a call to {@link
1359 * Logger#log(Logger.Level, String) Logger.log(Level.INFO, msg)}
1360 * will end up as a call to {@link
1361 * Logger#log(Logger.Level, ResourceBundle, String, Object...)
1362 * Logger.log(Level.INFO, bundle, msg, (Object[])null)} on the wrapped
1363 * logger instance.
1364 * Note however that by default, string messages returned by {@link
1365 * java.util.function.Supplier Supplier<String>} will not be
1366 * localized, as it is assumed that such strings are messages which are
1367 * already constructed, rather than keys in a resource bundle.
1368 * <p>
1369 * An implementation of {@code LoggerFinder} may override this method,
1370 * for example, when the underlying logging backend provides its own
1371 * mechanism for localizing log messages, then such a
1372 * {@code LoggerFinder} would be free to return a logger
1373 * that makes direct use of the mechanism provided by the backend.
1374 *
1375 * @param name the name of the logger.
1376 * @param bundle a resource bundle; can be {@code null}.
1377 * @param module the module for which the logger is being requested.
1378 * @return an instance of {@link Logger Logger} which will use the
1379 * provided resource bundle for message localization.
1380 *
1381 * @throws NullPointerException if {@code name} is {@code null} or
1382 * {@code module} is {@code null}.
1383 */
1384 public Logger getLocalizedLogger(String name, ResourceBundle bundle,
1385 Module module) {
1386 return new LocalizedLoggerWrapper<>(getLogger(name, module), bundle);
1387 }
1388
1389 /**
1390 * Returns the {@code LoggerFinder} instance. There is one
1391 * single system-wide {@code LoggerFinder} instance in
1392 * the Java Runtime. See the class specification of how the
1393 * {@link LoggerFinder LoggerFinder} implementation is located and
1394 * loaded.
1395 *
1396 * @return the {@link LoggerFinder LoggerFinder} instance.
1397 */
1398 public static LoggerFinder getLoggerFinder() {
1399 return accessProvider();
1400 }
1401
1402
1403 private static volatile LoggerFinder service;
1404 static LoggerFinder accessProvider() {
1405 // We do not need to synchronize: LoggerFinderLoader will
1406 // always return the same instance, so if we don't have it,
1407 // just fetch it again.
1408 LoggerFinder finder = service;
1409 if (finder == null) {
1410 finder = LoggerFinderLoader.getLoggerFinder();
1411 if (finder instanceof TemporaryLoggerFinder) return finder;
1412 service = finder;
1413 }
1414 return finder;
1415 }
1416
1417 }
1418
1419
1420 /**
1421 * Returns an instance of {@link Logger Logger} for the caller's
1422 * use.
1423 *
1424 * @implSpec
1425 * Instances returned by this method route messages to loggers
1426 * obtained by calling {@link LoggerFinder#getLogger(java.lang.String,
1427 * java.lang.Module) LoggerFinder.getLogger(name, module)}, where
1428 * {@code module} is the caller's module.
1429 * In cases where {@code System.getLogger} is called from a context where
1430 * there is no caller frame on the stack (e.g when called directly
1431 * from a JNI attached thread), {@code IllegalCallerException} is thrown.
1432 * To obtain a logger in such a context, use an auxiliary class that will
1433 * implicitly be identified as the caller, or use the system {@link
1434 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead.
1435 * Note that doing the latter may eagerly initialize the underlying
1436 * logging system.
1437 *
1438 * @apiNote
1439 * This method may defer calling the {@link
1440 * LoggerFinder#getLogger(java.lang.String, java.lang.Module)
1441 * LoggerFinder.getLogger} method to create an actual logger supplied by
1442 * the logging backend, for instance, to allow loggers to be obtained during
1443 * the system initialization time.
1444 *
1445 * @param name the name of the logger.
1446 * @return an instance of {@link Logger} that can be used by the calling
1447 * class.
1448 * @throws NullPointerException if {@code name} is {@code null}.
1449 * @throws IllegalCallerException if there is no Java caller frame on the
1450 * stack.
1451 *
1452 * @since 9
1453 */
1454 @CallerSensitive
1455 public static Logger getLogger(String name) {
1456 Objects.requireNonNull(name);
1457 final Class<?> caller = Reflection.getCallerClass();
1458 if (caller == null) {
1459 throw new IllegalCallerException("no caller frame");
1460 }
1461 return LazyLoggers.getLogger(name, caller.getModule());
1462 }
1463
1464 /**
1465 * Returns a localizable instance of {@link Logger
1466 * Logger} for the caller's use.
1467 * The returned logger will use the provided resource bundle for message
1468 * localization.
1469 *
1470 * @implSpec
1471 * The returned logger will perform message localization as specified
1472 * by {@link LoggerFinder#getLocalizedLogger(java.lang.String,
1473 * java.util.ResourceBundle, java.lang.Module)
1474 * LoggerFinder.getLocalizedLogger(name, bundle, module)}, where
1475 * {@code module} is the caller's module.
1476 * In cases where {@code System.getLogger} is called from a context where
1477 * there is no caller frame on the stack (e.g when called directly
1478 * from a JNI attached thread), {@code IllegalCallerException} is thrown.
1479 * To obtain a logger in such a context, use an auxiliary class that
1480 * will implicitly be identified as the caller, or use the system {@link
1481 * LoggerFinder#getLoggerFinder() LoggerFinder} to obtain a logger instead.
1482 * Note that doing the latter may eagerly initialize the underlying
1483 * logging system.
1484 *
1485 * @apiNote
1486 * This method is intended to be used after the system is fully initialized.
1487 * This method may trigger the immediate loading and initialization
1488 * of the {@link LoggerFinder} service, which may cause issues if the
1489 * Java Runtime is not ready to initialize the concrete service
1490 * implementation yet.
1491 * System classes which may be loaded early in the boot sequence and
1492 * need to log localized messages should create a logger using
1493 * {@link #getLogger(java.lang.String)} and then use the log methods that
1494 * take a resource bundle as parameter.
1495 *
1496 * @param name the name of the logger.
1497 * @param bundle a resource bundle.
1498 * @return an instance of {@link Logger} which will use the provided
1499 * resource bundle for message localization.
1500 * @throws NullPointerException if {@code name} is {@code null} or
1501 * {@code bundle} is {@code null}.
1502 * @throws IllegalCallerException if there is no Java caller frame on the
1503 * stack.
1504 *
1505 * @since 9
1506 */
1507 @CallerSensitive
1508 public static Logger getLogger(String name, ResourceBundle bundle) {
1509 final ResourceBundle rb = Objects.requireNonNull(bundle);
1510 Objects.requireNonNull(name);
1511 final Class<?> caller = Reflection.getCallerClass();
1512 if (caller == null) {
1513 throw new IllegalCallerException("no caller frame");
1514 }
1515 return LoggerFinder.accessProvider()
1516 .getLocalizedLogger(name, rb, caller.getModule());
1517 }
1518
1519 /**
1520 * Initiates the {@linkplain Runtime##shutdown shutdown sequence} of the Java Virtual
1521 * Machine. This method initiates the shutdown sequence (if it is not already initiated)
1522 * and then blocks indefinitely. This method neither returns nor throws an exception;
1523 * that is, it does not complete either normally or abruptly.
1524 * <p>
1525 * The argument serves as a status code. By convention, a nonzero status code
1526 * indicates abnormal termination.
1527 * <p>
1528 * The call {@code System.exit(n)} is effectively equivalent to the call:
1529 * {@snippet :
1530 * Runtime.getRuntime().exit(n)
1531 * }
1532 *
1533 * @implNote
1534 * The initiation of the shutdown sequence is logged by {@link Runtime#exit(int)}.
1535 *
1536 * @param status exit status.
1537 * @see java.lang.Runtime#exit(int)
1538 */
1539 public static void exit(int status) {
1540 Runtime.getRuntime().exit(status);
1541 }
1542
1543 /**
1544 * Returns whether the AOT system is recording training data.
1545 * @return whether the AOT system is recording training data.
1546 * @since 26
1547 */
1548 public static native boolean AOTIsTraining();
1549
1550 /**
1551 * Will stop the recording of AOT training data.
1552 * @since 26
1553 */
1554 public static native void AOTEndTraining();
1555
1556 /**
1557 * Runs the garbage collector in the Java Virtual Machine.
1558 * <p>
1559 * Calling the {@code gc} method suggests that the Java Virtual Machine
1560 * expend effort toward recycling unused objects in order to
1561 * make the memory they currently occupy available for reuse
1562 * by the Java Virtual Machine.
1563 * When control returns from the method call, the Java Virtual Machine
1564 * has made a best effort to reclaim space from all unused objects.
1565 * There is no guarantee that this effort will recycle any particular
1566 * number of unused objects, reclaim any particular amount of space, or
1567 * complete at any particular time, if at all, before the method returns or ever.
1568 * There is also no guarantee that this effort will determine
1569 * the change of reachability in any particular number of objects,
1570 * or that any particular number of {@link java.lang.ref.Reference Reference}
1571 * objects will be cleared and enqueued.
1572 *
1573 * <p>
1574 * The call {@code System.gc()} is effectively equivalent to the
1575 * call:
1576 * <blockquote><pre>
1577 * Runtime.getRuntime().gc()
1578 * </pre></blockquote>
1579 *
1580 * @see java.lang.Runtime#gc()
1581 */
1582 public static void gc() {
1583 Runtime.getRuntime().gc();
1584 }
1585
1586 /**
1587 * Runs the finalization methods of any objects pending finalization.
1588 *
1589 * Calling this method suggests that the Java Virtual Machine expend
1590 * effort toward running the {@code finalize} methods of objects
1591 * that have been found to be discarded but whose {@code finalize}
1592 * methods have not yet been run. When control returns from the
1593 * method call, the Java Virtual Machine has made a best effort to
1594 * complete all outstanding finalizations.
1595 * <p>
1596 * The call {@code System.runFinalization()} is effectively
1597 * equivalent to the call:
1598 * <blockquote><pre>
1599 * Runtime.getRuntime().runFinalization()
1600 * </pre></blockquote>
1601 *
1602 * @deprecated Finalization has been deprecated for removal. See
1603 * {@link java.lang.Object#finalize} for background information and details
1604 * about migration options.
1605 * <p>
1606 * When running in a JVM in which finalization has been disabled or removed,
1607 * no objects will be pending finalization, so this method does nothing.
1608 *
1609 * @see java.lang.Runtime#runFinalization()
1610 * @jls 12.6 Finalization of Class Instances
1611 */
1612 @Deprecated(since="18", forRemoval=true)
1613 @SuppressWarnings("removal")
1614 public static void runFinalization() {
1615 Runtime.getRuntime().runFinalization();
1616 }
1617
1618 /**
1619 * Loads the native library specified by the filename argument. The filename
1620 * argument must be an absolute path name.
1621 *
1622 * If the filename argument, when stripped of any platform-specific library
1623 * prefix, path, and file extension, indicates a library whose name is,
1624 * for example, L, and a native library called L is statically linked
1625 * with the VM, then the JNI_OnLoad_L function exported by the library
1626 * is invoked rather than attempting to load a dynamic library.
1627 * A filename matching the argument does not have to exist in the
1628 * file system.
1629 * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a>
1630 * for more details.
1631 *
1632 * Otherwise, the filename argument is mapped to a native library image in
1633 * an implementation-dependent manner.
1634 *
1635 * <p>
1636 * The call {@code System.load(name)} is effectively equivalent
1637 * to the call:
1638 * <blockquote><pre>
1639 * Runtime.getRuntime().load(name)
1640 * </pre></blockquote>
1641 *
1642 * @param filename the file to load.
1643 * @throws UnsatisfiedLinkError if either the filename is not an
1644 * absolute path name, the native library is not statically
1645 * linked with the VM, or the library cannot be mapped to
1646 * a native library image by the host system.
1647 * @throws NullPointerException if {@code filename} is {@code null}
1648 * @throws IllegalCallerException if the caller is in a module that
1649 * does not have native access enabled.
1650 *
1651 * @spec jni/index.html Java Native Interface Specification
1652 * @see java.lang.Runtime#load(java.lang.String)
1653 */
1654 @CallerSensitive
1655 @Restricted
1656 public static void load(String filename) {
1657 Class<?> caller = Reflection.getCallerClass();
1658 Reflection.ensureNativeAccess(caller, System.class, "load", false);
1659 Runtime.getRuntime().load0(caller, filename);
1660 }
1661
1662 /**
1663 * Loads the native library specified by the {@code libname}
1664 * argument. The {@code libname} argument must not contain any platform
1665 * specific prefix, file extension or path. If a native library
1666 * called {@code libname} is statically linked with the VM, then the
1667 * JNI_OnLoad_{@code libname} function exported by the library is invoked.
1668 * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a>
1669 * for more details.
1670 *
1671 * Otherwise, the libname argument is loaded from a system library
1672 * location and mapped to a native library image in an
1673 * implementation-dependent manner.
1674 * <p>
1675 * The call {@code System.loadLibrary(name)} is effectively
1676 * equivalent to the call
1677 * <blockquote><pre>
1678 * Runtime.getRuntime().loadLibrary(name)
1679 * </pre></blockquote>
1680 *
1681 * @param libname the name of the library.
1682 * @throws UnsatisfiedLinkError if either the libname argument
1683 * contains a file path, the native library is not statically
1684 * linked with the VM, or the library cannot be mapped to a
1685 * native library image by the host system.
1686 * @throws NullPointerException if {@code libname} is {@code null}
1687 * @throws IllegalCallerException if the caller is in a module that
1688 * does not have native access enabled.
1689 *
1690 * @spec jni/index.html Java Native Interface Specification
1691 * @see java.lang.Runtime#loadLibrary(java.lang.String)
1692 */
1693 @CallerSensitive
1694 @Restricted
1695 public static void loadLibrary(String libname) {
1696 Class<?> caller = Reflection.getCallerClass();
1697 Reflection.ensureNativeAccess(caller, System.class, "loadLibrary", false);
1698 Runtime.getRuntime().loadLibrary0(caller, libname);
1699 }
1700
1701 /**
1702 * Maps a library name into a platform-specific string representing
1703 * a native library.
1704 *
1705 * @param libname the name of the library.
1706 * @return a platform-dependent native library name.
1707 * @throws NullPointerException if {@code libname} is {@code null}
1708 * @see java.lang.System#loadLibrary(java.lang.String)
1709 * @see java.lang.ClassLoader#findLibrary(java.lang.String)
1710 * @since 1.2
1711 */
1712 public static native String mapLibraryName(String libname);
1713
1714 /**
1715 * Create PrintStream for stdout/err based on encoding.
1716 */
1717 private static PrintStream newPrintStream(OutputStream out, String enc) {
1718 if (enc != null) {
1719 return new PrintStream(new BufferedOutputStream(out, 128), true,
1720 Charset.forName(enc, UTF_8.INSTANCE));
1721 }
1722 return new PrintStream(new BufferedOutputStream(out, 128), true);
1723 }
1724
1725 /**
1726 * Logs an exception/error at initialization time to stdout or stderr.
1727 *
1728 * @param printToStderr to print to stderr rather than stdout
1729 * @param printStackTrace to print the stack trace
1730 * @param msg the message to print before the exception, can be {@code null}
1731 * @param e the exception or error
1732 */
1733 private static void logInitException(boolean printToStderr,
1734 boolean printStackTrace,
1735 String msg,
1736 Throwable e) {
1737 if (VM.initLevel() < 1) {
1738 throw new InternalError("system classes not initialized");
1739 }
1740 PrintStream log = (printToStderr) ? err : out;
1741 if (msg != null) {
1742 log.println(msg);
1743 }
1744 if (printStackTrace) {
1745 e.printStackTrace(log);
1746 } else {
1747 log.println(e);
1748 for (Throwable suppressed : e.getSuppressed()) {
1749 log.println("Suppressed: " + suppressed);
1750 }
1751 Throwable cause = e.getCause();
1752 if (cause != null) {
1753 log.println("Caused by: " + cause);
1754 }
1755 }
1756 }
1757
1758 /**
1759 * Create the Properties object from a map - masking out system properties
1760 * that are not intended for public access.
1761 */
1762 private static Properties createProperties(Map<String, String> initialProps) {
1763 Properties properties = new Properties(initialProps.size());
1764 for (var entry : initialProps.entrySet()) {
1765 String prop = entry.getKey();
1766 switch (prop) {
1767 // Do not add private system properties to the Properties
1768 case "sun.nio.MaxDirectMemorySize":
1769 case "sun.nio.PageAlignDirectMemory":
1770 // used by java.lang.Integer.IntegerCache
1771 case "java.lang.Integer.IntegerCache.high":
1772 // used by sun.launcher.LauncherHelper
1773 case "sun.java.launcher.diag":
1774 // used by jdk.internal.loader.ClassLoaders
1775 case "jdk.boot.class.path.append":
1776 break;
1777 default:
1778 properties.put(prop, entry.getValue());
1779 }
1780 }
1781 return properties;
1782 }
1783
1784 /**
1785 * Initialize the system class. Called after thread initialization.
1786 */
1787 private static void initPhase1() {
1788
1789 // register the shared secrets - do this first, since SystemProps.initProperties
1790 // might initialize CharsetDecoders that rely on it
1791 setJavaLangAccess();
1792
1793 // VM might invoke JNU_NewStringPlatform() to set those encoding
1794 // sensitive properties (user.home, user.name, boot.class.path, etc.)
1795 // during "props" initialization.
1796 // The charset is initialized in System.c and does not depend on the Properties.
1797 Map<String, String> tempProps = SystemProps.initProperties();
1798 VersionProps.init(tempProps);
1799
1800 // There are certain system configurations that may be controlled by
1801 // VM options such as the maximum amount of direct memory and
1802 // Integer cache size used to support the object identity semantics
1803 // of autoboxing. Typically, the library will obtain these values
1804 // from the properties set by the VM. If the properties are for
1805 // internal implementation use only, these properties should be
1806 // masked from the system properties.
1807 //
1808 // Save a private copy of the system properties object that
1809 // can only be accessed by the internal implementation.
1810 VM.saveProperties(tempProps);
1811 props = createProperties(tempProps);
1812
1813 // Check if sun.jnu.encoding is supported. If not, replace it with UTF-8.
1814 var jnuEncoding = props.getProperty("sun.jnu.encoding");
1815 if (jnuEncoding == null || !Charset.isSupported(jnuEncoding)) {
1816 notSupportedJnuEncoding = jnuEncoding == null ? "null" : jnuEncoding;
1817 props.setProperty("sun.jnu.encoding", "UTF-8");
1818 }
1819
1820 StaticProperty.javaHome(); // Load StaticProperty to cache the property values
1821
1822 lineSeparator = props.getProperty("line.separator");
1823
1824 FileInputStream fdIn = new In(FileDescriptor.in);
1825 FileOutputStream fdOut = new Out(FileDescriptor.out);
1826 FileOutputStream fdErr = new Out(FileDescriptor.err);
1827 initialIn = new BufferedInputStream(fdIn);
1828 setIn0(initialIn);
1829 // stdout/err.encoding are set when the VM is associated with the terminal,
1830 // thus they are equivalent to Console.charset(), otherwise the encodings
1831 // of those properties default to native.encoding
1832 setOut0(newPrintStream(fdOut, props.getProperty("stdout.encoding")));
1833 initialErr = newPrintStream(fdErr, props.getProperty("stderr.encoding"));
1834 setErr0(initialErr);
1835
1836 // Setup Java signal handlers for HUP, TERM, and INT (where available).
1837 Terminator.setup();
1838
1839 // Initialize any miscellaneous operating system settings that need to be
1840 // set for the class libraries. Currently this is no-op everywhere except
1841 // for Windows where the process-wide error mode is set before the java.io
1842 // classes are used.
1843 VM.initializeOSEnvironment();
1844
1845 // start Finalizer and Reference Handler threads
1846 SharedSecrets.getJavaLangRefAccess().startThreads();
1847
1848 // system properties, java.lang and other core classes are now initialized
1849 VM.initLevel(1);
1850 }
1851
1852 /**
1853 * System.in.
1854 */
1855 private static class In extends FileInputStream {
1856 In(FileDescriptor fd) {
1857 super(fd);
1858 }
1859
1860 @Override
1861 public int read() throws IOException {
1862 boolean attempted = Blocker.begin();
1863 try {
1864 return super.read();
1865 } finally {
1866 Blocker.end(attempted);
1867 }
1868 }
1869
1870 @Override
1871 public int read(byte[] b) throws IOException {
1872 boolean attempted = Blocker.begin();
1873 try {
1874 return super.read(b);
1875 } finally {
1876 Blocker.end(attempted);
1877 }
1878 }
1879
1880 @Override
1881 public int read(byte[] b, int off, int len) throws IOException {
1882 boolean attempted = Blocker.begin();
1883 try {
1884 return super.read(b, off, len);
1885 } finally {
1886 Blocker.end(attempted);
1887 }
1888 }
1889 }
1890
1891 /**
1892 * System.out/System.err wrap this output stream.
1893 */
1894 private static class Out extends FileOutputStream {
1895 Out(FileDescriptor fd) {
1896 super(fd);
1897 }
1898
1899 @Override
1900 public void write(int b) throws IOException {
1901 boolean attempted = Blocker.begin();
1902 try {
1903 super.write(b);
1904 } finally {
1905 Blocker.end(attempted);
1906 }
1907 }
1908
1909 @Override
1910 public void write(byte[] b) throws IOException {
1911 boolean attempted = Blocker.begin();
1912 try {
1913 super.write(b);
1914 } finally {
1915 Blocker.end(attempted);
1916 }
1917 }
1918
1919 @Override
1920 public void write(byte[] b, int off, int len) throws IOException {
1921 boolean attempted = Blocker.begin();
1922 try {
1923 super.write(b, off, len);
1924 } finally {
1925 Blocker.end(attempted);
1926 }
1927 }
1928 }
1929
1930 // @see #initPhase2()
1931 static ModuleLayer bootLayer;
1932
1933 /*
1934 * Invoked by VM. Phase 2 module system initialization.
1935 * Only classes in java.base can be loaded in this phase.
1936 *
1937 * @param printToStderr print exceptions to stderr rather than stdout
1938 * @param printStackTrace print stack trace when exception occurs
1939 *
1940 * @return JNI_OK for success, JNI_ERR for failure
1941 */
1942 private static int initPhase2(boolean printToStderr, boolean printStackTrace) {
1943
1944 try {
1945 bootLayer = ModuleBootstrap.boot();
1946 } catch (Exception | Error e) {
1947 logInitException(printToStderr, printStackTrace,
1948 "Error occurred during initialization of boot layer", e);
1949 return -1; // JNI_ERR
1950 }
1951
1952 // module system initialized
1953 VM.initLevel(2);
1954
1955 return 0; // JNI_OK
1956 }
1957
1958 /*
1959 * Invoked by VM. Phase 3 is the final system initialization:
1960 * 1. set system class loader
1961 * 2. set TCCL
1962 *
1963 * This method must be called after the module system initialization.
1964 */
1965 private static void initPhase3() {
1966
1967 // Emit a warning if java.io.tmpdir is set via the command line
1968 // to a directory that doesn't exist
1969 if (SystemProps.isBadIoTmpdir()) {
1970 System.err.println("WARNING: java.io.tmpdir directory does not exist");
1971 }
1972
1973 String smProp = System.getProperty("java.security.manager");
1974 if (smProp != null) {
1975 switch (smProp) {
1976 case "disallow":
1977 break;
1978 case "allow":
1979 case "":
1980 case "default":
1981 default:
1982 throw new Error("A command line option has attempted to allow or enable the Security Manager."
1983 + " Enabling a Security Manager is not supported.");
1984 }
1985 }
1986
1987 // Emit a warning if `sun.jnu.encoding` is not supported.
1988 if (notSupportedJnuEncoding != null) {
1989 System.err.println(
1990 "WARNING: The encoding of the underlying platform's" +
1991 " file system is not supported: " +
1992 notSupportedJnuEncoding);
1993 }
1994
1995 // initializing the system class loader
1996 VM.initLevel(3);
1997
1998 // system class loader initialized
1999 ClassLoader scl = ClassLoader.initSystemClassLoader();
2000
2001 // set TCCL
2002 Thread.currentThread().setContextClassLoader(scl);
2003
2004 // system is fully initialized
2005 VM.initLevel(4);
2006 }
2007
2008 private static void setJavaLangAccess() {
2009 // Allow privileged classes outside of java.lang
2010 SharedSecrets.setJavaLangAccess(new JavaLangAccess() {
2011 public List<Method> getDeclaredPublicMethods(Class<?> klass, String name, Class<?>... parameterTypes) {
2012 return klass.getDeclaredPublicMethods(name, parameterTypes);
2013 }
2014 public Method findMethod(Class<?> klass, boolean publicOnly, String name, Class<?>... parameterTypes) {
2015 return klass.findMethod(publicOnly, name, parameterTypes);
2016 }
2017 public jdk.internal.reflect.ConstantPool getConstantPool(Class<?> klass) {
2018 return klass.getConstantPool();
2019 }
2020 public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {
2021 return klass.casAnnotationType(oldType, newType);
2022 }
2023 public AnnotationType getAnnotationType(Class<?> klass) {
2024 return klass.getAnnotationType();
2025 }
2026 public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) {
2027 return klass.getDeclaredAnnotationMap();
2028 }
2029 public byte[] getRawClassAnnotations(Class<?> klass) {
2030 return klass.getRawAnnotations();
2031 }
2032 public byte[] getRawClassTypeAnnotations(Class<?> klass) {
2033 return klass.getRawTypeAnnotations();
2034 }
2035 public byte[] getRawExecutableTypeAnnotations(Executable executable) {
2036 return Class.getExecutableTypeAnnotationBytes(executable);
2037 }
2038 public int getClassFileAccessFlags(Class<?> klass) {
2039 return klass.getClassFileAccessFlags();
2040 }
2041 public <E extends Enum<E>>
2042 E[] getEnumConstantsShared(Class<E> klass) {
2043 return klass.getEnumConstantsShared();
2044 }
2045 public int classFileVersion(Class<?> clazz) {
2046 return clazz.getClassFileVersion();
2047 }
2048 public void blockedOn(Interruptible b) {
2049 Thread.currentThread().blockedOn(b);
2050 }
2051 public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {
2052 Shutdown.add(slot, registerShutdownInProgress, hook);
2053 }
2054 @SuppressWarnings("removal")
2055 public void invokeFinalize(Object o) throws Throwable {
2056 o.finalize();
2057 }
2058 public ConcurrentHashMap<?, ?> createOrGetClassLoaderValueMap(ClassLoader cl) {
2059 return cl.createOrGetClassLoaderValueMap();
2060 }
2061 public Class<?> defineClass(ClassLoader loader, String name, byte[] b, ProtectionDomain pd, String source) {
2062 return ClassLoader.defineClass1(loader, name, b, 0, b.length, pd, source);
2063 }
2064 public Class<?> defineClass(ClassLoader loader, Class<?> lookup, String name, byte[] b, ProtectionDomain pd,
2065 boolean initialize, int flags, Object classData) {
2066 return ClassLoader.defineClass0(loader, lookup, name, b, 0, b.length, pd, initialize, flags, classData);
2067 }
2068 public Class<?> findBootstrapClassOrNull(String name) {
2069 return ClassLoader.findBootstrapClassOrNull(name);
2070 }
2071 public Package definePackage(ClassLoader cl, String name, Module module) {
2072 return cl.definePackage(name, module);
2073 }
2074 public Module defineModule(ClassLoader loader,
2075 ModuleDescriptor descriptor,
2076 URI uri) {
2077 return new Module(null, loader, descriptor, uri);
2078 }
2079 public Module defineUnnamedModule(ClassLoader loader) {
2080 return new Module(loader);
2081 }
2082 public void addReads(Module m1, Module m2) {
2083 m1.implAddReads(m2);
2084 }
2085 public void addReadsAllUnnamed(Module m) {
2086 m.implAddReadsAllUnnamed();
2087 }
2088 public void addExports(Module m, String pn) {
2089 m.implAddExports(pn);
2090 }
2091 public void addExports(Module m, String pn, Module other) {
2092 m.implAddExports(pn, other);
2093 }
2094 public void addExportsToAllUnnamed(Module m, String pn) {
2095 m.implAddExportsToAllUnnamed(pn);
2096 }
2097 public void addOpens(Module m, String pn, Module other) {
2098 m.implAddOpens(pn, other);
2099 }
2100 public void addOpensToAllUnnamed(Module m, String pn) {
2101 m.implAddOpensToAllUnnamed(pn);
2102 }
2103 public void addUses(Module m, Class<?> service) {
2104 m.implAddUses(service);
2105 }
2106 public boolean isReflectivelyExported(Module m, String pn, Module other) {
2107 return m.isReflectivelyExported(pn, other);
2108 }
2109 public boolean isReflectivelyOpened(Module m, String pn, Module other) {
2110 return m.isReflectivelyOpened(pn, other);
2111 }
2112 public Module addEnableNativeAccess(Module m) {
2113 return m.implAddEnableNativeAccess();
2114 }
2115 public boolean addEnableNativeAccess(ModuleLayer layer, String name) {
2116 return layer.addEnableNativeAccess(name);
2117 }
2118 public void addEnableNativeAccessToAllUnnamed() {
2119 Module.implAddEnableNativeAccessToAllUnnamed();
2120 }
2121 public void ensureNativeAccess(Module m, Class<?> owner, String methodName, Class<?> currentClass, boolean jni) {
2122 m.ensureNativeAccess(owner, methodName, currentClass, jni);
2123 }
2124 public ServicesCatalog getServicesCatalog(ModuleLayer layer) {
2125 return layer.getServicesCatalog();
2126 }
2127 public void bindToLoader(ModuleLayer layer, ClassLoader loader) {
2128 layer.bindToLoader(loader);
2129 }
2130 public Stream<ModuleLayer> layers(ModuleLayer layer) {
2131 return layer.layers();
2132 }
2133 public Stream<ModuleLayer> layers(ClassLoader loader) {
2134 return ModuleLayer.layers(loader);
2135 }
2136
2137 public int countPositives(byte[] bytes, int offset, int length) {
2138 return StringCoding.countPositives(bytes, offset, length);
2139 }
2140
2141 public int countNonZeroAscii(String s) {
2142 return StringCoding.countNonZeroAscii(s);
2143 }
2144
2145 public String uncheckedNewStringWithLatin1Bytes(byte[] bytes) {
2146 return String.newStringWithLatin1Bytes(bytes);
2147 }
2148
2149 public String uncheckedNewStringOrThrow(byte[] bytes, Charset cs) throws CharacterCodingException {
2150 return String.newStringOrThrow(bytes, cs);
2151 }
2152
2153 public char uncheckedGetUTF16Char(byte[] bytes, int index) {
2154 return StringUTF16.getChar(bytes, index);
2155 }
2156
2157 public void uncheckedPutCharUTF16(byte[] bytes, int index, int ch) {
2158 StringUTF16.putChar(bytes, index, ch);
2159 }
2160
2161 public byte[] uncheckedGetBytesOrThrow(String s, Charset cs) throws CharacterCodingException {
2162 return String.getBytesOrThrow(s, cs);
2163 }
2164
2165 public byte[] getBytesUTF8OrThrow(String s) throws CharacterCodingException {
2166 return String.getBytesUTF8OrThrow(s);
2167 }
2168
2169 public void inflateBytesToChars(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
2170 StringLatin1.inflate(src, srcOff, dst, dstOff, len);
2171 }
2172
2173 public int decodeASCII(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
2174 return String.decodeASCII(src, srcOff, dst, dstOff, len);
2175 }
2176
2177 public int encodeASCII(char[] sa, int sp, byte[] da, int dp, int len) {
2178 return StringCoding.encodeAsciiArray(sa, sp, da, dp, len);
2179 }
2180
2181 public InputStream initialSystemIn() {
2182 return initialIn;
2183 }
2184
2185 public PrintStream initialSystemErr() {
2186 return initialErr;
2187 }
2188
2189 public void setCause(Throwable t, Throwable cause) {
2190 t.setCause(cause);
2191 }
2192
2193 public ProtectionDomain protectionDomain(Class<?> c) {
2194 return c.getProtectionDomain();
2195 }
2196
2197 public MethodHandle stringConcatHelper(String name, MethodType methodType) {
2198 return StringConcatHelper.lookupStatic(name, methodType);
2199 }
2200
2201 public Object uncheckedStringConcat1(String[] constants) {
2202 return new StringConcatHelper.Concat1(constants);
2203 }
2204
2205 public byte stringInitCoder() {
2206 return String.COMPACT_STRINGS ? String.LATIN1 : String.UTF16;
2207 }
2208
2209 public byte stringCoder(String str) {
2210 return str.coder();
2211 }
2212
2213 public String join(String prefix, String suffix, String delimiter, String[] elements, int size) {
2214 return String.join(prefix, suffix, delimiter, elements, size);
2215 }
2216
2217 public String concat(String prefix, Object value, String suffix) {
2218 return StringConcatHelper.concat(prefix, value, suffix);
2219 }
2220
2221 public Object classData(Class<?> c) {
2222 return c.getClassData();
2223 }
2224
2225 @Override
2226 public NativeLibraries nativeLibrariesFor(ClassLoader loader) {
2227 return ClassLoader.nativeLibrariesFor(loader);
2228 }
2229
2230 public Thread[] getAllThreads() {
2231 return Thread.getAllThreads();
2232 }
2233
2234 public ThreadContainer threadContainer(Thread thread) {
2235 return thread.threadContainer();
2236 }
2237
2238 public void start(Thread thread, ThreadContainer container) {
2239 thread.start(container);
2240 }
2241
2242 public StackableScope headStackableScope(Thread thread) {
2243 return thread.headStackableScopes();
2244 }
2245
2246 public void setHeadStackableScope(StackableScope scope) {
2247 Thread.setHeadStackableScope(scope);
2248 }
2249
2250 public Thread currentCarrierThread() {
2251 return Thread.currentCarrierThread();
2252 }
2253
2254 public <T> T getCarrierThreadLocal(CarrierThreadLocal<T> local) {
2255 return ((ThreadLocal<T>)local).getCarrierThreadLocal();
2256 }
2257
2258 public <T> void setCarrierThreadLocal(CarrierThreadLocal<T> local, T value) {
2259 ((ThreadLocal<T>)local).setCarrierThreadLocal(value);
2260 }
2261
2262 public void removeCarrierThreadLocal(CarrierThreadLocal<?> local) {
2263 ((ThreadLocal<?>)local).removeCarrierThreadLocal();
2264 }
2265
2266 public Object[] scopedValueCache() {
2267 return Thread.scopedValueCache();
2268 }
2269
2270 public void setScopedValueCache(Object[] cache) {
2271 Thread.setScopedValueCache(cache);
2272 }
2273
2274 public Object scopedValueBindings() {
2275 return Thread.scopedValueBindings();
2276 }
2277
2278 public Continuation getContinuation(Thread thread) {
2279 return thread.getContinuation();
2280 }
2281
2282 public void setContinuation(Thread thread, Continuation continuation) {
2283 thread.setContinuation(continuation);
2284 }
2285
2286 public ContinuationScope virtualThreadContinuationScope() {
2287 return VirtualThread.continuationScope();
2288 }
2289
2290 public void parkVirtualThread() {
2291 Thread thread = Thread.currentThread();
2292 if (thread instanceof BaseVirtualThread vthread) {
2293 vthread.park();
2294 } else {
2295 throw new WrongThreadException();
2296 }
2297 }
2298
2299 public void parkVirtualThread(long nanos) {
2300 Thread thread = Thread.currentThread();
2301 if (thread instanceof BaseVirtualThread vthread) {
2302 vthread.parkNanos(nanos);
2303 } else {
2304 throw new WrongThreadException();
2305 }
2306 }
2307
2308 public void unparkVirtualThread(Thread thread) {
2309 if (thread instanceof BaseVirtualThread vthread) {
2310 vthread.unpark();
2311 } else {
2312 throw new WrongThreadException();
2313 }
2314 }
2315
2316 public Executor virtualThreadDefaultScheduler() {
2317 return VirtualThread.defaultScheduler();
2318 }
2319
2320 public StackWalker newStackWalkerInstance(Set<StackWalker.Option> options,
2321 ContinuationScope contScope,
2322 Continuation continuation) {
2323 return StackWalker.newInstance(options, null, contScope, continuation);
2324 }
2325
2326 public String getLoaderNameID(ClassLoader loader) {
2327 return loader != null ? loader.nameAndId() : "null";
2328 }
2329
2330 @Override
2331 public void copyToSegmentRaw(String string, MemorySegment segment, long offset) {
2332 string.copyToSegmentRaw(segment, offset);
2333 }
2334
2335 @Override
2336 public boolean bytesCompatible(String string, Charset charset) {
2337 return string.bytesCompatible(charset);
2338 }
2339 });
2340 }
2341 }