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