forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackTraceElement.java
603 lines (529 loc) · 24.4 KB
/
StackTraceElement.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/*
* Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang;
import jdk.internal.loader.BuiltinClassLoader;
import jdk.internal.misc.VM;
import jdk.internal.module.ModuleHashes;
import jdk.internal.module.ModuleReferenceImpl;
import java.lang.module.ModuleReference;
import java.lang.module.ResolvedModule;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* An element in a stack trace, as returned by {@link
* Throwable#getStackTrace()}. Each element represents a single stack frame.
* All stack frames except for the one at the top of the stack represent
* a method invocation. The frame at the top of the stack represents the
* execution point at which the stack trace was generated. Typically,
* this is the point at which the throwable corresponding to the stack trace
* was created.
*
* @author Josh Bloch
* @since 1.4
*/
// 方法调用链的栈帧
public final class StackTraceElement implements java.io.Serializable {
private static final long serialVersionUID = 6992337162326171013L;
private static final byte BUILTIN_CLASS_LOADER = 0x1;
private static final byte JDK_NON_UPGRADEABLE_MODULE = 0x2;
/**
* For Throwables and StackWalker, the VM initially sets this field to a reference to the declaring Class.
* The Class reference is used to construct the 'format' bitmap, and then is cleared.
* For STEs constructed using the public constructors, this field is not used.
*/
private transient Class<?> declaringClassObject;
private byte format = 0; // Default to show all
/*▼ 栈帧属性 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┓ */
private String moduleName; // 模块名
private String declaringClass; // 类名
private String methodName; // 方法名
private String fileName; // 文件名
private int lineNumber; // 行号
private String moduleVersion; // 模块版本
// Normally initialized by VM
private String classLoaderName; // 类加载器
/*▲ 栈帧属性 ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┛ */
/*▼ 构造方法 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Private constructor for the factory methods to create StackTraceElement
* for Throwable and StackFrameInfo
*/
private StackTraceElement() {
}
/**
* Creates a stack trace element representing the specified execution
* point. The {@link #getModuleName module name} and {@link
* #getModuleVersion module version} of the stack trace element will
* be {@code null}.
*
* @param declaringClass the fully qualified name of the class containing
* the execution point represented by the stack trace element
* @param methodName the name of the method containing the execution point
* represented by the stack trace element
* @param fileName the name of the file containing the execution point
* represented by the stack trace element, or {@code null} if
* this information is unavailable
* @param lineNumber the line number of the source line containing the
* execution point represented by this stack trace element, or
* a negative number if this information is unavailable. A value
* of -2 indicates that the method containing the execution point
* is a native method
*
* @throws NullPointerException if {@code declaringClass} or
* {@code methodName} is null
* @revised 9
* @spec JPMS
* @since 1.5
*/
public StackTraceElement(String declaringClass, String methodName, String fileName, int lineNumber) {
this(null, null, null, declaringClass, methodName, fileName, lineNumber);
}
/**
* Creates a stack trace element representing the specified execution
* point.
*
* @param classLoaderName the class loader name if the class loader of
* the class containing the execution point represented by
* the stack trace is named; otherwise {@code null}
* @param moduleName the module name if the class containing the
* execution point represented by the stack trace is in a named
* module; otherwise {@code null}
* @param moduleVersion the module version if the class containing the
* execution point represented by the stack trace is in a named
* module that has a version; otherwise {@code null}
* @param declaringClass the fully qualified name of the class containing
* the execution point represented by the stack trace element
* @param methodName the name of the method containing the execution point
* represented by the stack trace element
* @param fileName the name of the file containing the execution point
* represented by the stack trace element, or {@code null} if
* this information is unavailable
* @param lineNumber the line number of the source line containing the
* execution point represented by this stack trace element, or
* a negative number if this information is unavailable. A value
* of -2 indicates that the method containing the execution point
* is a native method
*
* @throws NullPointerException if {@code declaringClass} is {@code null}
* or {@code methodName} is {@code null}
* @spec JPMS
* @since 9
*/
public StackTraceElement(String classLoaderName, String moduleName, String moduleVersion, String declaringClass, String methodName, String fileName, int lineNumber) {
this.classLoaderName = classLoaderName;
this.moduleName = moduleName;
this.moduleVersion = moduleVersion;
this.declaringClass = Objects.requireNonNull(declaringClass, "Declaring class is null");
this.methodName = Objects.requireNonNull(methodName, "Method name is null");
this.fileName = fileName;
this.lineNumber = lineNumber;
}
/*▲ 构造方法 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 栈帧属性 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the module name of the module containing the execution point
* represented by this stack trace element.
*
* @return the module name of the {@code Module} containing the execution
* point represented by this stack trace element; {@code null}
* if the module name is not available.
*
* @spec JPMS
* @see Module#getName()
* @since 9
*/
// 模块名
public String getModuleName() {
return moduleName;
}
/**
* Returns the fully qualified name of the class containing the
* execution point represented by this stack trace element.
*
* @return the fully qualified name of the {@code Class} containing
* the execution point represented by this stack trace element.
*/
// 类名
public String getClassName() {
return declaringClass;
}
/**
* Returns the name of the method containing the execution point
* represented by this stack trace element. If the execution point is
* contained in an instance or class initializer, this method will return
* the appropriate <i>special method name</i>, {@code <init>} or
* {@code <clinit>}, as per Section 3.9 of <i>The Java Virtual
* Machine Specification</i>.
*
* @return the name of the method containing the execution point
* represented by this stack trace element.
*/
// 方法名
public String getMethodName() {
return methodName;
}
/**
* Returns the name of the source file containing the execution point
* represented by this stack trace element. Generally, this corresponds
* to the {@code SourceFile} attribute of the relevant {@code class}
* file (as per <i>The Java Virtual Machine Specification</i>, Section
* 4.7.7). In some systems, the name may refer to some source code unit
* other than a file, such as an entry in source repository.
*
* @return the name of the file containing the execution point
* represented by this stack trace element, or {@code null} if
* this information is unavailable.
*/
// 文件名
public String getFileName() {
return fileName;
}
/**
* Returns the line number of the source line containing the execution
* point represented by this stack trace element. Generally, this is
* derived from the {@code LineNumberTable} attribute of the relevant
* {@code class} file (as per <i>The Java Virtual Machine
* Specification</i>, Section 4.7.8).
*
* @return the line number of the source line containing the execution
* point represented by this stack trace element, or a negative
* number if this information is unavailable.
*/
// 行号
public int getLineNumber() {
return lineNumber;
}
/**
* Returns the module version of the module containing the execution point
* represented by this stack trace element.
*
* @return the module version of the {@code Module} containing the execution
* point represented by this stack trace element; {@code null}
* if the module version is not available.
*
* @spec JPMS
* @see java.lang.module.ModuleDescriptor.Version
* @since 9
*/
// 模块版本
public String getModuleVersion() {
return moduleVersion;
}
/**
* Returns the name of the class loader of the class containing the
* execution point represented by this stack trace element.
*
* @return the name of the class loader of the class containing the execution
* point represented by this stack trace element; {@code null}
* if the class loader is not named.
*
* @spec JPMS
* @see java.lang.ClassLoader#getName()
* @since 9
*/
// 类加载器
public String getClassLoaderName() {
return classLoaderName;
}
/*▲ 栈帧属性 ████████████████████████████████████████████████████████████████████████████████┛ */
/**
* Returns true if the method containing the execution point
* represented by this stack trace element is a native method.
*
* @return {@code true} if the method containing the execution point
* represented by this stack trace element is a native method.
*/
// 是否为native方法(native方法的行号标记为-2)
public boolean isNativeMethod() {
return lineNumber == -2;
}
/**
* Returns an array of StackTraceElements of the given depth filled from the backtrace of a given Throwable.
*/
static StackTraceElement[] of(Throwable x, int depth) {
StackTraceElement[] stackTrace = new StackTraceElement[depth];
for(int i = 0; i<depth; i++) {
stackTrace[i] = new StackTraceElement();
}
// VM to fill in StackTraceElement
initStackTraceElements(stackTrace, x);
// ensure the proper StackTraceElement initialization
for(StackTraceElement ste : stackTrace) {
ste.computeFormat();
}
return stackTrace;
}
/**
* Returns a StackTraceElement from a given StackFrameInfo.
*/
static StackTraceElement of(StackFrameInfo sfi) {
StackTraceElement ste = new StackTraceElement();
initStackTraceElement(ste, sfi);
ste.computeFormat();
return ste;
}
/**
* Returns true if the module is hashed with java.base.
* <p>
* This method returns false when running on the exploded image
* since JDK modules are not hashed. They have no Version attribute
* and so "@<version>" part will be omitted anyway.
*/
private static boolean isHashedInJavaBase(Module m) {
// return true if module system is not initialized as the code
// must be in java.base
if(!VM.isModuleSystemInited())
return true;
return ModuleLayer.boot() == m.getLayer() && HashedModules.contains(m);
}
/**
* Sets the given stack trace elements with the backtrace of the given Throwable.
*/
private static native void initStackTraceElements(StackTraceElement[] elements, Throwable x);
/**
* Sets the given stack trace element with the given StackFrameInfo
*/
private static native void initStackTraceElement(StackTraceElement element, StackFrameInfo sfi);
/**
* Returns a string representation of this stack trace element.
*
* @apiNote The format of this string depends on the implementation, but the
* following examples may be regarded as typical:
* <ul>
* <li>
* "{@code com.foo.loader/[email protected]/com.foo.Main.run(Main.java:101)}"
* - See the description below.
* </li>
* <li>
* "{@code com.foo.loader/[email protected]/com.foo.Main.run(Main.java)}"
* - The line number is unavailable.
* </li>
* <li>
* "{@code com.foo.loader/[email protected]/com.foo.Main.run(Unknown Source)}"
* - Neither the file name nor the line number is available.
* </li>
* <li>
* "{@code com.foo.loader/[email protected]/com.foo.Main.run(Native Method)}"
* - The method containing the execution point is a native method.
* </li>
* <li>
* "{@code com.foo.loader//com.foo.bar.App.run(App.java:12)}"
* - The class of the execution point is defined in the unnamed module of
* the class loader named {@code com.foo.loader}.
* </li>
* <li>
* "{@code [email protected]/org.acme.Lib.test(Lib.java:80)}"
* - The class of the execution point is defined in {@code acme} module
* loaded by a built-in class loader such as the application class loader.
* </li>
* <li>
* "{@code MyClass.mash(MyClass.java:9)}"
* - {@code MyClass} class is on the application class path.
* </li>
* </ul>
*
* <p> The first example shows a stack trace element consisting of
* three elements, each separated by {@code "/"} followed with
* the source file name and the line number of the source line
* containing the execution point.
*
* The first element "{@code com.foo.loader}" is
* the name of the class loader. The second element "{@code [email protected]}"
* is the module name and version. The third element is the method
* containing the execution point; "{@code com.foo.Main"}" is the
* fully-qualified class name and "{@code run}" is the name of the method.
* "{@code Main.java}" is the source file name and "{@code 101}" is
* the line number.
*
* <p> If a class is defined in an <em>unnamed module</em>
* then the second element is omitted as shown in
* "{@code com.foo.loader//com.foo.bar.App.run(App.java:12)}".
*
* <p> If the class loader is a <a href="ClassLoader.html#builtinLoaders">
* built-in class loader</a> or is not named then the first element
* and its following {@code "/"} are omitted as shown in
* "{@code [email protected]/org.acme.Lib.test(Lib.java:80)}".
* If the first element is omitted and the module is an unnamed module,
* the second element and its following {@code "/"} are also omitted
* as shown in "{@code MyClass.mash(MyClass.java:9)}".
*
* <p> The {@code toString} method may return two different values on two
* {@code StackTraceElement} instances that are
* {@linkplain #equals(Object) equal}, for example one created via the
* constructor, and one obtained from {@link java.lang.Throwable} or
* {@link java.lang.StackWalker.StackFrame}, where an implementation may
* choose to omit some element in the returned string.
* @revised 9
* @spec JPMS
* @see Throwable#printStackTrace()
*/
public String toString() {
String s = "";
if(!dropClassLoaderName() && classLoaderName != null && !classLoaderName.isEmpty()) {
s += classLoaderName + "/";
}
if(moduleName != null && !moduleName.isEmpty()) {
s += moduleName;
if(!dropModuleVersion() && moduleVersion != null && !moduleVersion.isEmpty()) {
s += "@" + moduleVersion;
}
}
s = s.isEmpty() ? declaringClass : s + "/" + declaringClass;
return s
+ "."
+ methodName
+ "("
+ (
isNativeMethod()
? "Native Method)"
: (
fileName != null && lineNumber >= 0
? fileName + ":" + lineNumber + ")"
: (
fileName != null
? "" + fileName + ")"
: "Unknown Source)"
)
)
);
}
/**
* Returns true if the specified object is another
* {@code StackTraceElement} instance representing the same execution
* point as this instance. Two stack trace elements {@code a} and
* {@code b} are equal if and only if:
* <pre>{@code
* equals(a.getClassLoaderName(), b.getClassLoaderName()) &&
* equals(a.getModuleName(), b.getModuleName()) &&
* equals(a.getModuleVersion(), b.getModuleVersion()) &&
* equals(a.getClassName(), b.getClassName()) &&
* equals(a.getMethodName(), b.getMethodName())
* equals(a.getFileName(), b.getFileName()) &&
* a.getLineNumber() == b.getLineNumber()
*
* }</pre>
* where {@code equals} has the semantics of {@link
* java.util.Objects#equals(Object, Object) Objects.equals}.
*
* @param obj the object to be compared with this stack trace element.
*
* @return true if the specified object is another
* {@code StackTraceElement} instance representing the same
* execution point as this instance.
*
* @revised 9
* @spec JPMS
*/
public boolean equals(Object obj) {
if(obj == this)
return true;
if(!(obj instanceof StackTraceElement))
return false;
StackTraceElement e = (StackTraceElement) obj;
return Objects.equals(classLoaderName, e.classLoaderName)
&& Objects.equals(moduleName, e.moduleName)
&& Objects.equals(moduleVersion, e.moduleVersion)
&& e.declaringClass.equals(declaringClass)
&& e.lineNumber == lineNumber
&& Objects.equals(methodName, e.methodName)
&& Objects.equals(fileName, e.fileName);
}
/**
* Returns a hash code value for this stack trace element.
*/
public int hashCode() {
int result = 31 * declaringClass.hashCode() + methodName.hashCode();
result = 31 * result + Objects.hashCode(classLoaderName);
result = 31 * result + Objects.hashCode(moduleName);
result = 31 * result + Objects.hashCode(moduleVersion);
result = 31 * result + Objects.hashCode(fileName);
result = 31 * result + lineNumber;
return result;
}
/**
* Called from of() methods to set the 'format' bitmap using the Class
* reference stored in declaringClassObject, and then clear the reference.
*
* <p>
* If the module is a non-upgradeable JDK module, then set
* JDK_NON_UPGRADEABLE_MODULE to omit its version string.
* <p>
* If the loader is one of the built-in loaders (`boot`, `platform`, or `app`)
* then set BUILTIN_CLASS_LOADER to omit the first element (`<loader>/`).
*/
private synchronized void computeFormat() {
try {
Class<?> cls = (Class<?>) declaringClassObject;
ClassLoader loader = cls.getClassLoader0();
Module m = cls.getModule();
byte bits = 0;
// First element - class loader name
// Call package-private ClassLoader::name method
if(loader instanceof BuiltinClassLoader) {
bits |= BUILTIN_CLASS_LOADER;
}
// Second element - module name and version
// Omit if is a JDK non-upgradeable module (recorded in the hashes in java.base)
if(isHashedInJavaBase(m)) {
bits |= JDK_NON_UPGRADEABLE_MODULE;
}
format = bits;
} finally {
// Class reference no longer needed, clear it
declaringClassObject = null;
}
}
private boolean dropClassLoaderName() {
return (format & BUILTIN_CLASS_LOADER) == BUILTIN_CLASS_LOADER;
}
private boolean dropModuleVersion() {
return (format & JDK_NON_UPGRADEABLE_MODULE) == JDK_NON_UPGRADEABLE_MODULE;
}
/**
* Finds JDK non-upgradeable modules, i.e. the modules that are
* included in the hashes in java.base.
*/
private static class HashedModules {
static Set<String> HASHED_MODULES = hashedModules();
static Set<String> hashedModules() {
Optional<ResolvedModule> resolvedModule = ModuleLayer.boot().configuration().findModule("java.base");
assert resolvedModule.isPresent();
ModuleReference mref = resolvedModule.get().reference();
assert mref instanceof ModuleReferenceImpl;
ModuleHashes hashes = ((ModuleReferenceImpl) mref).recordedHashes();
if(hashes != null) {
Set<String> names = new HashSet<>(hashes.names());
names.add("java.base");
return names;
}
return Set.of();
}
static boolean contains(Module m) {
return HASHED_MODULES.contains(m.getName());
}
}
}