-
Notifications
You must be signed in to change notification settings - Fork 105
/
jvm.cpp
3768 lines (3175 loc) · 141 KB
/
jvm.cpp
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1997, 2019, 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.
*
* 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.
*
*/
#include "precompiled.hpp"
#include "jvm.h"
#include "classfile/classFileStream.hpp"
#include "classfile/classLoader.hpp"
#include "classfile/classLoaderData.inline.hpp"
#include "classfile/javaAssertions.hpp"
#include "classfile/javaClasses.inline.hpp"
#include "classfile/moduleEntry.hpp"
#include "classfile/modules.hpp"
#include "classfile/packageEntry.hpp"
#include "classfile/stringTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "gc/shared/collectedHeap.inline.hpp"
#include "interpreter/bytecode.hpp"
#include "jfr/jfrEvents.hpp"
#include "logging/log.hpp"
#include "memory/heapShared.hpp"
#include "memory/oopFactory.hpp"
#include "memory/referenceType.hpp"
#include "memory/resourceArea.hpp"
#include "memory/universe.hpp"
#include "oops/access.inline.hpp"
#include "oops/fieldStreams.hpp"
#include "oops/instanceKlass.hpp"
#include "oops/method.hpp"
#include "oops/objArrayKlass.hpp"
#include "oops/objArrayOop.inline.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvm_misc.hpp"
#include "prims/jvmtiExport.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "prims/nativeLookup.hpp"
#include "prims/privilegedStack.hpp"
#include "prims/stackwalk.hpp"
#include "runtime/arguments.hpp"
#include "runtime/atomic.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/init.hpp"
#include "runtime/interfaceSupport.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/javaCalls.hpp"
#include "runtime/jfieldIDWorkaround.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/orderAccess.hpp"
#include "runtime/os.inline.hpp"
#include "runtime/perfData.hpp"
#include "runtime/reflection.hpp"
#include "runtime/thread.inline.hpp"
#include "runtime/threadSMR.hpp"
#include "runtime/vframe.inline.hpp"
#include "runtime/vm_operations.hpp"
#include "runtime/vm_version.hpp"
#include "services/attachListener.hpp"
#include "services/management.hpp"
#include "services/threadService.hpp"
#include "utilities/copy.hpp"
#include "utilities/defaultStream.hpp"
#include "utilities/dtrace.hpp"
#include "utilities/events.hpp"
#include "utilities/histogram.hpp"
#include "utilities/macros.hpp"
#include "utilities/utf8.hpp"
#if INCLUDE_CDS
#include "classfile/systemDictionaryShared.hpp"
#endif
#include <errno.h>
/*
NOTE about use of any ctor or function call that can trigger a safepoint/GC:
such ctors and calls MUST NOT come between an oop declaration/init and its
usage because if objects are move this may cause various memory stomps, bus
errors and segfaults. Here is a cookbook for causing so called "naked oop
failures":
JVM_ENTRY(jobjectArray, JVM_GetClassDeclaredFields<etc> {
JVMWrapper("JVM_GetClassDeclaredFields");
// Object address to be held directly in mirror & not visible to GC
oop mirror = JNIHandles::resolve_non_null(ofClass);
// If this ctor can hit a safepoint, moving objects around, then
ComplexConstructor foo;
// Boom! mirror may point to JUNK instead of the intended object
(some dereference of mirror)
// Here's another call that may block for GC, making mirror stale
MutexLocker ml(some_lock);
// And here's an initializer that can result in a stale oop
// all in one step.
oop o = call_that_can_throw_exception(TRAPS);
The solution is to keep the oop declaration BELOW the ctor or function
call that might cause a GC, do another resolve to reassign the oop, or
consider use of a Handle instead of an oop so there is immunity from object
motion. But note that the "QUICK" entries below do not have a handlemark
and thus can only support use of handles passed in.
*/
static void trace_class_resolution_impl(Klass* to_class, TRAPS) {
ResourceMark rm;
int line_number = -1;
const char * source_file = NULL;
const char * trace = "explicit";
InstanceKlass* caller = NULL;
JavaThread* jthread = JavaThread::current();
if (jthread->has_last_Java_frame()) {
vframeStream vfst(jthread);
// scan up the stack skipping ClassLoader, AccessController and PrivilegedAction frames
TempNewSymbol access_controller = SymbolTable::new_symbol("java/security/AccessController", CHECK);
Klass* access_controller_klass = SystemDictionary::resolve_or_fail(access_controller, false, CHECK);
TempNewSymbol privileged_action = SymbolTable::new_symbol("java/security/PrivilegedAction", CHECK);
Klass* privileged_action_klass = SystemDictionary::resolve_or_fail(privileged_action, false, CHECK);
Method* last_caller = NULL;
while (!vfst.at_end()) {
Method* m = vfst.method();
if (!vfst.method()->method_holder()->is_subclass_of(SystemDictionary::ClassLoader_klass())&&
!vfst.method()->method_holder()->is_subclass_of(access_controller_klass) &&
!vfst.method()->method_holder()->is_subclass_of(privileged_action_klass)) {
break;
}
last_caller = m;
vfst.next();
}
// if this is called from Class.forName0 and that is called from Class.forName,
// then print the caller of Class.forName. If this is Class.loadClass, then print
// that caller, otherwise keep quiet since this should be picked up elsewhere.
bool found_it = false;
if (!vfst.at_end() &&
vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
vfst.method()->name() == vmSymbols::forName0_name()) {
vfst.next();
if (!vfst.at_end() &&
vfst.method()->method_holder()->name() == vmSymbols::java_lang_Class() &&
vfst.method()->name() == vmSymbols::forName_name()) {
vfst.next();
found_it = true;
}
} else if (last_caller != NULL &&
last_caller->method_holder()->name() ==
vmSymbols::java_lang_ClassLoader() &&
last_caller->name() == vmSymbols::loadClass_name()) {
found_it = true;
} else if (!vfst.at_end()) {
if (vfst.method()->is_native()) {
// JNI call
found_it = true;
}
}
if (found_it && !vfst.at_end()) {
// found the caller
caller = vfst.method()->method_holder();
line_number = vfst.method()->line_number_from_bci(vfst.bci());
if (line_number == -1) {
// show method name if it's a native method
trace = vfst.method()->name_and_sig_as_C_string();
}
Symbol* s = caller->source_file_name();
if (s != NULL) {
source_file = s->as_C_string();
}
}
}
if (caller != NULL) {
if (to_class != caller) {
const char * from = caller->external_name();
const char * to = to_class->external_name();
// print in a single call to reduce interleaving between threads
if (source_file != NULL) {
log_debug(class, resolve)("%s %s %s:%d (%s)", from, to, source_file, line_number, trace);
} else {
log_debug(class, resolve)("%s %s (%s)", from, to, trace);
}
}
}
}
void trace_class_resolution(Klass* to_class) {
EXCEPTION_MARK;
trace_class_resolution_impl(to_class, THREAD);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
}
}
// Wrapper to trace JVM functions
#ifdef ASSERT
Histogram* JVMHistogram;
volatile int JVMHistogram_lock = 0;
class JVMHistogramElement : public HistogramElement {
public:
JVMHistogramElement(const char* name);
};
JVMHistogramElement::JVMHistogramElement(const char* elementName) {
_name = elementName;
uintx count = 0;
while (Atomic::cmpxchg(1, &JVMHistogram_lock, 0) != 0) {
while (OrderAccess::load_acquire(&JVMHistogram_lock) != 0) {
count +=1;
if ( (WarnOnStalledSpinLock > 0)
&& (count % WarnOnStalledSpinLock == 0)) {
warning("JVMHistogram_lock seems to be stalled");
}
}
}
if(JVMHistogram == NULL)
JVMHistogram = new Histogram("JVM Call Counts",100);
JVMHistogram->add_element(this);
Atomic::dec(&JVMHistogram_lock);
}
#define JVMCountWrapper(arg) \
static JVMHistogramElement* e = new JVMHistogramElement(arg); \
if (e != NULL) e->increment_count(); // Due to bug in VC++, we need a NULL check here eventhough it should never happen!
#define JVMWrapper(arg) JVMCountWrapper(arg);
#else
#define JVMWrapper(arg)
#endif
// Interface version /////////////////////////////////////////////////////////////////////
JVM_LEAF(jint, JVM_GetInterfaceVersion())
return JVM_INTERFACE_VERSION;
JVM_END
// java.lang.System //////////////////////////////////////////////////////////////////////
JVM_LEAF(jlong, JVM_CurrentTimeMillis(JNIEnv *env, jclass ignored))
JVMWrapper("JVM_CurrentTimeMillis");
return os::javaTimeMillis();
JVM_END
JVM_LEAF(jlong, JVM_NanoTime(JNIEnv *env, jclass ignored))
JVMWrapper("JVM_NanoTime");
return os::javaTimeNanos();
JVM_END
// The function below is actually exposed by jdk.internal.misc.VM and not
// java.lang.System, but we choose to keep it here so that it stays next
// to JVM_CurrentTimeMillis and JVM_NanoTime
const jlong MAX_DIFF_SECS = CONST64(0x0100000000); // 2^32
const jlong MIN_DIFF_SECS = -MAX_DIFF_SECS; // -2^32
JVM_LEAF(jlong, JVM_GetNanoTimeAdjustment(JNIEnv *env, jclass ignored, jlong offset_secs))
JVMWrapper("JVM_GetNanoTimeAdjustment");
jlong seconds;
jlong nanos;
os::javaTimeSystemUTC(seconds, nanos);
// We're going to verify that the result can fit in a long.
// For that we need the difference in seconds between 'seconds'
// and 'offset_secs' to be such that:
// |seconds - offset_secs| < (2^63/10^9)
// We're going to approximate 10^9 ~< 2^30 (1000^3 ~< 1024^3)
// which makes |seconds - offset_secs| < 2^33
// and we will prefer +/- 2^32 as the maximum acceptable diff
// as 2^32 has a more natural feel than 2^33...
//
// So if |seconds - offset_secs| >= 2^32 - we return a special
// sentinel value (-1) which the caller should take as an
// exception value indicating that the offset given to us is
// too far from range of the current time - leading to too big
// a nano adjustment. The caller is expected to recover by
// computing a more accurate offset and calling this method
// again. (For the record 2^32 secs is ~136 years, so that
// should rarely happen)
//
jlong diff = seconds - offset_secs;
if (diff >= MAX_DIFF_SECS || diff <= MIN_DIFF_SECS) {
return -1; // sentinel value: the offset is too far off the target
}
// return the adjustment. If you compute a time by adding
// this number of nanoseconds along with the number of seconds
// in the offset you should get the current UTC time.
return (diff * (jlong)1000000000) + nanos;
JVM_END
JVM_ENTRY(void, JVM_ArrayCopy(JNIEnv *env, jclass ignored, jobject src, jint src_pos,
jobject dst, jint dst_pos, jint length))
JVMWrapper("JVM_ArrayCopy");
// Check if we have null pointers
if (src == NULL || dst == NULL) {
THROW(vmSymbols::java_lang_NullPointerException());
}
arrayOop s = arrayOop(JNIHandles::resolve_non_null(src));
arrayOop d = arrayOop(JNIHandles::resolve_non_null(dst));
assert(oopDesc::is_oop(s), "JVM_ArrayCopy: src not an oop");
assert(oopDesc::is_oop(d), "JVM_ArrayCopy: dst not an oop");
// Do copy
s->klass()->copy_array(s, src_pos, d, dst_pos, length, thread);
JVM_END
static void set_property(Handle props, const char* key, const char* value, TRAPS) {
JavaValue r(T_OBJECT);
// public synchronized Object put(Object key, Object value);
HandleMark hm(THREAD);
Handle key_str = java_lang_String::create_from_platform_dependent_str(key, CHECK);
Handle value_str = java_lang_String::create_from_platform_dependent_str((value != NULL ? value : ""), CHECK);
JavaCalls::call_virtual(&r,
props,
SystemDictionary::Properties_klass(),
vmSymbols::put_name(),
vmSymbols::object_object_object_signature(),
key_str,
value_str,
THREAD);
}
#define PUTPROP(props, name, value) set_property((props), (name), (value), CHECK_(properties));
JVM_ENTRY(jobject, JVM_InitProperties(JNIEnv *env, jobject properties))
JVMWrapper("JVM_InitProperties");
ResourceMark rm;
Handle props(THREAD, JNIHandles::resolve_non_null(properties));
// System property list includes both user set via -D option and
// jvm system specific properties.
for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
PUTPROP(props, p->key(), p->value());
}
// Convert the -XX:MaxDirectMemorySize= command line flag
// to the sun.nio.MaxDirectMemorySize property.
// Do this after setting user properties to prevent people
// from setting the value with a -D option, as requested.
{
if (FLAG_IS_DEFAULT(MaxDirectMemorySize)) {
PUTPROP(props, "sun.nio.MaxDirectMemorySize", "-1");
} else {
char as_chars[256];
jio_snprintf(as_chars, sizeof(as_chars), JULONG_FORMAT, MaxDirectMemorySize);
PUTPROP(props, "sun.nio.MaxDirectMemorySize", as_chars);
}
}
// JVM monitoring and management support
// Add the sun.management.compiler property for the compiler's name
{
#undef CSIZE
#if defined(_LP64) || defined(_WIN64)
#define CSIZE "64-Bit "
#else
#define CSIZE
#endif // 64bit
#ifdef TIERED
const char* compiler_name = "HotSpot " CSIZE "Tiered Compilers";
#else
#if defined(COMPILER1)
const char* compiler_name = "HotSpot " CSIZE "Client Compiler";
#elif defined(COMPILER2)
const char* compiler_name = "HotSpot " CSIZE "Server Compiler";
#elif INCLUDE_JVMCI
#error "INCLUDE_JVMCI should imply TIERED"
#else
const char* compiler_name = "";
#endif // compilers
#endif // TIERED
if (*compiler_name != '\0' &&
(Arguments::mode() != Arguments::_int)) {
PUTPROP(props, "sun.management.compiler", compiler_name);
}
}
return properties;
JVM_END
/*
* Return the temporary directory that the VM uses for the attach
* and perf data files.
*
* It is important that this directory is well-known and the
* same for all VM instances. It cannot be affected by configuration
* variables such as java.io.tmpdir.
*/
JVM_ENTRY(jstring, JVM_GetTemporaryDirectory(JNIEnv *env))
JVMWrapper("JVM_GetTemporaryDirectory");
HandleMark hm(THREAD);
const char* temp_dir = os::get_temp_directory();
Handle h = java_lang_String::create_from_platform_dependent_str(temp_dir, CHECK_NULL);
return (jstring) JNIHandles::make_local(env, h());
JVM_END
// java.lang.Runtime /////////////////////////////////////////////////////////////////////////
extern volatile jint vm_created;
JVM_ENTRY_NO_ENV(void, JVM_BeforeHalt())
JVMWrapper("JVM_BeforeHalt");
EventShutdown event;
if (event.should_commit()) {
event.set_reason("Shutdown requested from Java");
event.commit();
}
JVM_END
JVM_ENTRY_NO_ENV(void, JVM_Halt(jint code))
before_exit(thread);
vm_exit(code);
JVM_END
JVM_ENTRY_NO_ENV(void, JVM_GC(void))
JVMWrapper("JVM_GC");
if (!DisableExplicitGC) {
Universe::heap()->collect(GCCause::_java_lang_system_gc);
}
JVM_END
JVM_LEAF(jlong, JVM_MaxObjectInspectionAge(void))
JVMWrapper("JVM_MaxObjectInspectionAge");
return Universe::heap()->millis_since_last_gc();
JVM_END
static inline jlong convert_size_t_to_jlong(size_t val) {
// In the 64-bit vm, a size_t can overflow a jlong (which is signed).
NOT_LP64 (return (jlong)val;)
LP64_ONLY(return (jlong)MIN2(val, (size_t)max_jlong);)
}
JVM_ENTRY_NO_ENV(jlong, JVM_TotalMemory(void))
JVMWrapper("JVM_TotalMemory");
size_t n = Universe::heap()->capacity();
return convert_size_t_to_jlong(n);
JVM_END
JVM_ENTRY_NO_ENV(jlong, JVM_FreeMemory(void))
JVMWrapper("JVM_FreeMemory");
CollectedHeap* ch = Universe::heap();
size_t n;
{
MutexLocker x(Heap_lock);
n = ch->capacity() - ch->used();
}
return convert_size_t_to_jlong(n);
JVM_END
JVM_ENTRY_NO_ENV(jlong, JVM_MaxMemory(void))
JVMWrapper("JVM_MaxMemory");
size_t n = Universe::heap()->max_capacity();
return convert_size_t_to_jlong(n);
JVM_END
JVM_ENTRY_NO_ENV(jint, JVM_ActiveProcessorCount(void))
JVMWrapper("JVM_ActiveProcessorCount");
return os::active_processor_count();
JVM_END
// java.lang.Throwable //////////////////////////////////////////////////////
JVM_ENTRY(void, JVM_FillInStackTrace(JNIEnv *env, jobject receiver))
JVMWrapper("JVM_FillInStackTrace");
Handle exception(thread, JNIHandles::resolve_non_null(receiver));
java_lang_Throwable::fill_in_stack_trace(exception);
JVM_END
// java.lang.StackTraceElement //////////////////////////////////////////////
JVM_ENTRY(void, JVM_InitStackTraceElementArray(JNIEnv *env, jobjectArray elements, jobject throwable))
JVMWrapper("JVM_InitStackTraceElementArray");
Handle exception(THREAD, JNIHandles::resolve(throwable));
objArrayOop st = objArrayOop(JNIHandles::resolve(elements));
objArrayHandle stack_trace(THREAD, st);
// Fill in the allocated stack trace
java_lang_Throwable::get_stack_trace_elements(exception, stack_trace, CHECK);
JVM_END
JVM_ENTRY(void, JVM_InitStackTraceElement(JNIEnv* env, jobject element, jobject stackFrameInfo))
JVMWrapper("JVM_InitStackTraceElement");
Handle stack_frame_info(THREAD, JNIHandles::resolve_non_null(stackFrameInfo));
Handle stack_trace_element(THREAD, JNIHandles::resolve_non_null(element));
java_lang_StackFrameInfo::to_stack_trace_element(stack_frame_info, stack_trace_element, THREAD);
JVM_END
// java.lang.StackWalker //////////////////////////////////////////////////////
JVM_ENTRY(jobject, JVM_CallStackWalk(JNIEnv *env, jobject stackStream, jlong mode,
jint skip_frames, jint frame_count, jint start_index,
jobjectArray frames))
JVMWrapper("JVM_CallStackWalk");
JavaThread* jt = (JavaThread*) THREAD;
if (!jt->is_Java_thread() || !jt->has_last_Java_frame()) {
THROW_MSG_(vmSymbols::java_lang_InternalError(), "doStackWalk: no stack trace", NULL);
}
Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
// frames array is a Class<?>[] array when only getting caller reference,
// and a StackFrameInfo[] array (or derivative) otherwise. It should never
// be null.
objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
objArrayHandle frames_array_h(THREAD, fa);
int limit = start_index + frame_count;
if (frames_array_h->length() < limit) {
THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers", NULL);
}
oop result = StackWalk::walk(stackStream_h, mode, skip_frames, frame_count,
start_index, frames_array_h, CHECK_NULL);
return JNIHandles::make_local(env, result);
JVM_END
JVM_ENTRY(jint, JVM_MoreStackWalk(JNIEnv *env, jobject stackStream, jlong mode, jlong anchor,
jint frame_count, jint start_index,
jobjectArray frames))
JVMWrapper("JVM_MoreStackWalk");
JavaThread* jt = (JavaThread*) THREAD;
// frames array is a Class<?>[] array when only getting caller reference,
// and a StackFrameInfo[] array (or derivative) otherwise. It should never
// be null.
objArrayOop fa = objArrayOop(JNIHandles::resolve_non_null(frames));
objArrayHandle frames_array_h(THREAD, fa);
int limit = start_index+frame_count;
if (frames_array_h->length() < limit) {
THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "not enough space in buffers");
}
Handle stackStream_h(THREAD, JNIHandles::resolve_non_null(stackStream));
return StackWalk::fetchNextBatch(stackStream_h, mode, anchor, frame_count,
start_index, frames_array_h, THREAD);
JVM_END
// java.lang.Object ///////////////////////////////////////////////
JVM_ENTRY(jint, JVM_IHashCode(JNIEnv* env, jobject handle))
JVMWrapper("JVM_IHashCode");
// as implemented in the classic virtual machine; return 0 if object is NULL
return handle == NULL ? 0 : ObjectSynchronizer::FastHashCode (THREAD, JNIHandles::resolve_non_null(handle)) ;
JVM_END
JVM_ENTRY(void, JVM_MonitorWait(JNIEnv* env, jobject handle, jlong ms))
JVMWrapper("JVM_MonitorWait");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
JavaThreadInObjectWaitState jtiows(thread, ms != 0);
if (JvmtiExport::should_post_monitor_wait()) {
JvmtiExport::post_monitor_wait((JavaThread *)THREAD, (oop)obj(), ms);
// The current thread already owns the monitor and it has not yet
// been added to the wait queue so the current thread cannot be
// made the successor. This means that the JVMTI_EVENT_MONITOR_WAIT
// event handler cannot accidentally consume an unpark() meant for
// the ParkEvent associated with this ObjectMonitor.
}
ObjectSynchronizer::wait(obj, ms, CHECK);
JVM_END
JVM_ENTRY(void, JVM_MonitorNotify(JNIEnv* env, jobject handle))
JVMWrapper("JVM_MonitorNotify");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
ObjectSynchronizer::notify(obj, CHECK);
JVM_END
JVM_ENTRY(void, JVM_MonitorNotifyAll(JNIEnv* env, jobject handle))
JVMWrapper("JVM_MonitorNotifyAll");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
ObjectSynchronizer::notifyall(obj, CHECK);
JVM_END
JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
JVMWrapper("JVM_Clone");
Handle obj(THREAD, JNIHandles::resolve_non_null(handle));
Klass* klass = obj->klass();
JvmtiVMObjectAllocEventCollector oam;
#ifdef ASSERT
// Just checking that the cloneable flag is set correct
if (obj->is_array()) {
guarantee(klass->is_cloneable(), "all arrays are cloneable");
} else {
guarantee(obj->is_instance(), "should be instanceOop");
bool cloneable = klass->is_subtype_of(SystemDictionary::Cloneable_klass());
guarantee(cloneable == klass->is_cloneable(), "incorrect cloneable flag");
}
#endif
// Check if class of obj supports the Cloneable interface.
// All arrays are considered to be cloneable (See JLS 20.1.5).
// All j.l.r.Reference classes are considered non-cloneable.
if (!klass->is_cloneable() ||
(klass->is_instance_klass() &&
InstanceKlass::cast(klass)->reference_type() != REF_NONE)) {
ResourceMark rm(THREAD);
THROW_MSG_0(vmSymbols::java_lang_CloneNotSupportedException(), klass->external_name());
}
// Make shallow object copy
const int size = obj->size();
oop new_obj_oop = NULL;
if (obj->is_array()) {
const int length = ((arrayOop)obj())->length();
new_obj_oop = Universe::heap()->array_allocate(klass, size, length,
/* do_zero */ true, CHECK_NULL);
} else {
new_obj_oop = Universe::heap()->obj_allocate(klass, size, CHECK_NULL);
}
HeapAccess<>::clone(obj(), new_obj_oop, size);
Handle new_obj(THREAD, new_obj_oop);
// Caution: this involves a java upcall, so the clone should be
// "gc-robust" by this stage.
if (klass->has_finalizer()) {
assert(obj->is_instance(), "should be instanceOop");
new_obj_oop = InstanceKlass::register_finalizer(instanceOop(new_obj()), CHECK_NULL);
new_obj = Handle(THREAD, new_obj_oop);
}
return JNIHandles::make_local(env, new_obj());
JVM_END
// java.io.File ///////////////////////////////////////////////////////////////
JVM_LEAF(char*, JVM_NativePath(char* path))
JVMWrapper("JVM_NativePath");
return os::native_path(path);
JVM_END
// Misc. class handling ///////////////////////////////////////////////////////////
JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env))
JVMWrapper("JVM_GetCallerClass");
// Getting the class of the caller frame.
//
// The call stack at this point looks something like this:
//
// [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]
// [1] [ @CallerSensitive API.method ]
// [.] [ (skipped intermediate frames) ]
// [n] [ caller ]
vframeStream vfst(thread);
// Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
Method* m = vfst.method();
assert(m != NULL, "sanity");
switch (n) {
case 0:
// This must only be called from Reflection.getCallerClass
if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
}
// fall-through
case 1:
// Frame 0 and 1 must be caller sensitive.
if (!m->caller_sensitive()) {
THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
}
break;
default:
if (!m->is_ignored_by_security_stack_walk()) {
// We have reached the desired frame; return the holder class.
return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());
}
break;
}
}
return NULL;
JVM_END
JVM_ENTRY(jclass, JVM_FindPrimitiveClass(JNIEnv* env, const char* utf))
JVMWrapper("JVM_FindPrimitiveClass");
oop mirror = NULL;
BasicType t = name2type(utf);
if (t != T_ILLEGAL && t != T_OBJECT && t != T_ARRAY) {
mirror = Universe::java_mirror(t);
}
if (mirror == NULL) {
THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), (char*) utf);
} else {
return (jclass) JNIHandles::make_local(env, mirror);
}
JVM_END
// Returns a class loaded by the bootstrap class loader; or null
// if not found. ClassNotFoundException is not thrown.
// FindClassFromBootLoader is exported to the launcher for windows.
JVM_ENTRY(jclass, JVM_FindClassFromBootLoader(JNIEnv* env,
const char* name))
JVMWrapper("JVM_FindClassFromBootLoader");
// Java libraries should ensure that name is never null...
if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
// It's impossible to create this class; the name cannot fit
// into the constant pool.
return NULL;
}
TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
Klass* k = SystemDictionary::resolve_or_null(h_name, CHECK_NULL);
if (k == NULL) {
return NULL;
}
if (log_is_enabled(Debug, class, resolve)) {
trace_class_resolution(k);
}
return (jclass) JNIHandles::make_local(env, k->java_mirror());
JVM_END
// Find a class with this name in this loader, using the caller's protection domain.
JVM_ENTRY(jclass, JVM_FindClassFromCaller(JNIEnv* env, const char* name,
jboolean init, jobject loader,
jclass caller))
JVMWrapper("JVM_FindClassFromCaller throws ClassNotFoundException");
// Java libraries should ensure that name is never null...
if (name == NULL || (int)strlen(name) > Symbol::max_length()) {
// It's impossible to create this class; the name cannot fit
// into the constant pool.
THROW_MSG_0(vmSymbols::java_lang_ClassNotFoundException(), name);
}
TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
oop loader_oop = JNIHandles::resolve(loader);
oop from_class = JNIHandles::resolve(caller);
oop protection_domain = NULL;
// If loader is null, shouldn't call ClassLoader.checkPackageAccess; otherwise get
// NPE. Put it in another way, the bootstrap class loader has all permission and
// thus no checkPackageAccess equivalence in the VM class loader.
// The caller is also passed as NULL by the java code if there is no security
// manager to avoid the performance cost of getting the calling class.
if (from_class != NULL && loader_oop != NULL) {
protection_domain = java_lang_Class::as_Klass(from_class)->protection_domain();
}
Handle h_loader(THREAD, loader_oop);
Handle h_prot(THREAD, protection_domain);
jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
h_prot, false, THREAD);
if (log_is_enabled(Debug, class, resolve) && result != NULL) {
trace_class_resolution(java_lang_Class::as_Klass(JNIHandles::resolve_non_null(result)));
}
return result;
JVM_END
// Currently only called from the old verifier.
JVM_ENTRY(jclass, JVM_FindClassFromClass(JNIEnv *env, const char *name,
jboolean init, jclass from))
JVMWrapper("JVM_FindClassFromClass");
if (name == NULL) {
THROW_MSG_0(vmSymbols::java_lang_NoClassDefFoundError(), "No class name given");
}
if ((int)strlen(name) > Symbol::max_length()) {
// It's impossible to create this class; the name cannot fit
// into the constant pool.
Exceptions::fthrow(THREAD_AND_LOCATION,
vmSymbols::java_lang_NoClassDefFoundError(),
"Class name exceeds maximum length of %d: %s",
Symbol::max_length(),
name);
return 0;
}
TempNewSymbol h_name = SymbolTable::new_symbol(name, CHECK_NULL);
oop from_class_oop = JNIHandles::resolve(from);
Klass* from_class = (from_class_oop == NULL)
? (Klass*)NULL
: java_lang_Class::as_Klass(from_class_oop);
oop class_loader = NULL;
oop protection_domain = NULL;
if (from_class != NULL) {
class_loader = from_class->class_loader();
protection_domain = from_class->protection_domain();
}
Handle h_loader(THREAD, class_loader);
Handle h_prot (THREAD, protection_domain);
jclass result = find_class_from_class_loader(env, h_name, init, h_loader,
h_prot, true, thread);
if (log_is_enabled(Debug, class, resolve) && result != NULL) {
// this function is generally only used for class loading during verification.
ResourceMark rm;
oop from_mirror = JNIHandles::resolve_non_null(from);
Klass* from_class = java_lang_Class::as_Klass(from_mirror);
const char * from_name = from_class->external_name();
oop mirror = JNIHandles::resolve_non_null(result);
Klass* to_class = java_lang_Class::as_Klass(mirror);
const char * to = to_class->external_name();
log_debug(class, resolve)("%s %s (verification)", from_name, to);
}
return result;
JVM_END
static void is_lock_held_by_thread(Handle loader, PerfCounter* counter, TRAPS) {
if (loader.is_null()) {
return;
}
// check whether the current caller thread holds the lock or not.
// If not, increment the corresponding counter
if (ObjectSynchronizer::query_lock_ownership((JavaThread*)THREAD, loader) !=
ObjectSynchronizer::owner_self) {
counter->inc();
}
}
// common code for JVM_DefineClass() and JVM_DefineClassWithSource()
static jclass jvm_define_class_common(JNIEnv *env, const char *name,
jobject loader, const jbyte *buf,
jsize len, jobject pd, const char *source,
TRAPS) {
if (source == NULL) source = "__JVM_DefineClass__";
assert(THREAD->is_Java_thread(), "must be a JavaThread");
JavaThread* jt = (JavaThread*) THREAD;
PerfClassTraceTime vmtimer(ClassLoader::perf_define_appclass_time(),
ClassLoader::perf_define_appclass_selftime(),
ClassLoader::perf_define_appclasses(),
jt->get_thread_stat()->perf_recursion_counts_addr(),
jt->get_thread_stat()->perf_timers_addr(),
PerfClassTraceTime::DEFINE_CLASS);
if (UsePerfData) {
ClassLoader::perf_app_classfile_bytes_read()->inc(len);
}
// Since exceptions can be thrown, class initialization can take place
// if name is NULL no check for class name in .class stream has to be made.
TempNewSymbol class_name = NULL;
if (name != NULL) {
const int str_len = (int)strlen(name);
if (str_len > Symbol::max_length()) {
// It's impossible to create this class; the name cannot fit
// into the constant pool.
Exceptions::fthrow(THREAD_AND_LOCATION,
vmSymbols::java_lang_NoClassDefFoundError(),
"Class name exceeds maximum length of %d: %s",
Symbol::max_length(),
name);
return 0;
}
class_name = SymbolTable::new_symbol(name, str_len, CHECK_NULL);
}
ResourceMark rm(THREAD);
ClassFileStream st((u1*)buf, len, source, ClassFileStream::verify);
Handle class_loader (THREAD, JNIHandles::resolve(loader));
if (UsePerfData) {
is_lock_held_by_thread(class_loader,
ClassLoader::sync_JVMDefineClassLockFreeCounter(),
THREAD);
}
Handle protection_domain (THREAD, JNIHandles::resolve(pd));
Klass* k = SystemDictionary::resolve_from_stream(class_name,
class_loader,
protection_domain,
&st,
CHECK_NULL);
if (log_is_enabled(Debug, class, resolve) && k != NULL) {
trace_class_resolution(k);
}
return (jclass) JNIHandles::make_local(env, k->java_mirror());
}
JVM_ENTRY(jclass, JVM_DefineClass(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd))
JVMWrapper("JVM_DefineClass");
return jvm_define_class_common(env, name, loader, buf, len, pd, NULL, THREAD);
JVM_END
JVM_ENTRY(jclass, JVM_DefineClassWithSource(JNIEnv *env, const char *name, jobject loader, const jbyte *buf, jsize len, jobject pd, const char *source))
JVMWrapper("JVM_DefineClassWithSource");
return jvm_define_class_common(env, name, loader, buf, len, pd, source, THREAD);
JVM_END
JVM_ENTRY(jclass, JVM_FindLoadedClass(JNIEnv *env, jobject loader, jstring name))
JVMWrapper("JVM_FindLoadedClass");
ResourceMark rm(THREAD);
Handle h_name (THREAD, JNIHandles::resolve_non_null(name));
Handle string = java_lang_String::internalize_classname(h_name, CHECK_NULL);
const char* str = java_lang_String::as_utf8_string(string());
// Sanity check, don't expect null
if (str == NULL) return NULL;
const int str_len = (int)strlen(str);
if (str_len > Symbol::max_length()) {
// It's impossible to create this class; the name cannot fit
// into the constant pool.
return NULL;
}
TempNewSymbol klass_name = SymbolTable::new_symbol(str, str_len, CHECK_NULL);
// Security Note:
// The Java level wrapper will perform the necessary security check allowing
// us to pass the NULL as the initiating class loader.
Handle h_loader(THREAD, JNIHandles::resolve(loader));
if (UsePerfData) {
is_lock_held_by_thread(h_loader,
ClassLoader::sync_JVMFindLoadedClassLockFreeCounter(),
THREAD);
}
Klass* k = SystemDictionary::find_instance_or_array_klass(klass_name,
h_loader,
Handle(),
CHECK_NULL);
#if INCLUDE_CDS
if (k == NULL) {
// If the class is not already loaded, try to see if it's in the shared
// archive for the current classloader (h_loader).
k = SystemDictionaryShared::find_or_load_shared_class(klass_name, h_loader, CHECK_NULL);
}
#endif
return (k == NULL) ? NULL :
(jclass) JNIHandles::make_local(env, k->java_mirror());
JVM_END
// Module support //////////////////////////////////////////////////////////////////////////////
JVM_ENTRY(void, JVM_DefineModule(JNIEnv *env, jobject module, jboolean is_open, jstring version,
jstring location, const char* const* packages, jsize num_packages))