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