-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathSCCache.cpp
4565 lines (4278 loc) · 165 KB
/
SCCache.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) 2023, 2025, 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 "asm/macroAssembler.hpp"
#include "cds/cdsAccess.hpp"
#include "cds/cdsConfig.hpp"
#include "cds/heapShared.hpp"
#include "cds/metaspaceShared.hpp"
#include "ci/ciConstant.hpp"
#include "ci/ciEnv.hpp"
#include "ci/ciField.hpp"
#include "ci/ciMethod.hpp"
#include "ci/ciMethodData.hpp"
#include "ci/ciObject.hpp"
#include "ci/ciUtilities.inline.hpp"
#include "classfile/javaAssertions.hpp"
#include "classfile/stringTable.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmClasses.hpp"
#include "classfile/vmIntrinsics.hpp"
#include "code/codeBlob.hpp"
#include "code/codeCache.hpp"
#include "code/oopRecorder.inline.hpp"
#include "code/SCCache.hpp"
#include "compiler/abstractCompiler.hpp"
#include "compiler/compilationPolicy.hpp"
#include "compiler/compileBroker.hpp"
#include "compiler/compileTask.hpp"
#include "gc/g1/g1BarrierSetRuntime.hpp"
#include "gc/shared/gcConfig.hpp"
#include "logging/log.hpp"
#include "memory/universe.hpp"
#include "oops/klass.inline.hpp"
#include "oops/method.inline.hpp"
#include "oops/trainingData.hpp"
#include "prims/jvmtiThreadState.hpp"
#include "runtime/atomic.hpp"
#include "runtime/flags/flagSetting.hpp"
#include "runtime/globals_extension.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/jniHandles.inline.hpp"
#include "runtime/os.inline.hpp"
#include "runtime/sharedRuntime.hpp"
#include "runtime/stubCodeGenerator.hpp"
#include "runtime/stubRoutines.hpp"
#include "runtime/timerTrace.hpp"
#include "runtime/threadIdentifier.hpp"
#include "utilities/ostream.hpp"
#include "utilities/spinYield.hpp"
#ifdef COMPILER1
#include "c1/c1_Runtime1.hpp"
#include "c1/c1_LIRAssembler.hpp"
#include "gc/shared/c1/barrierSetC1.hpp"
#include "gc/g1/c1/g1BarrierSetC1.hpp"
#if INCLUDE_SHENANDOAHGC
#include "gc/shenandoah/c1/shenandoahBarrierSetC1.hpp"
#endif
#include "gc/z/c1/zBarrierSetC1.hpp"
#endif
#ifdef COMPILER2
#include "opto/runtime.hpp"
#endif
#if INCLUDE_JVMCI
#include "jvmci/jvmci.hpp"
#endif
#if INCLUDE_SHENANDOAHGC
#include "gc/shenandoah/shenandoahRuntime.hpp"
#endif
#include <sys/stat.h>
#include <errno.h>
#ifndef O_BINARY // if defined (Win32) use binary files.
#define O_BINARY 0 // otherwise do nothing.
#endif
static elapsedTimer _t_totalLoad;
static elapsedTimer _t_totalRegister;
static elapsedTimer _t_totalFind;
static elapsedTimer _t_totalStore;
SCCache* SCCache::_cache = nullptr;
static bool enable_timers() {
return CITime || log_is_enabled(Info, init);
}
static void exit_vm_on_load_failure() {
// Treat SCC warnings as error when RequireSharedSpaces is on.
if (RequireSharedSpaces) {
vm_exit_during_initialization("Unable to used startup cached code.", nullptr);
}
}
static void exit_vm_on_store_failure() {
// Treat SCC warnings as error when RequireSharedSpaces is on.
if (RequireSharedSpaces) {
tty->print_cr("Unable to create startup cached code.");
// Failure during AOT code caching, we don't want to dump core
vm_abort(false);
}
}
void SCCache::initialize() {
if (LoadCachedCode && !UseSharedSpaces) {
return;
}
if (StoreCachedCode || LoadCachedCode) {
if (FLAG_IS_DEFAULT(ClassInitBarrierMode)) {
FLAG_SET_DEFAULT(ClassInitBarrierMode, 1);
}
} else if (ClassInitBarrierMode > 0) {
log_info(scc, init)("Set ClassInitBarrierMode to 0 because StoreCachedCode and LoadCachedCode are false.");
FLAG_SET_DEFAULT(ClassInitBarrierMode, 0);
}
if ((LoadCachedCode || StoreCachedCode) && CachedCodeFile != nullptr) {
const int len = (int)strlen(CachedCodeFile);
// cache file path
char* path = NEW_C_HEAP_ARRAY(char, len+1, mtCode);
memcpy(path, CachedCodeFile, len);
path[len] = '\0';
if (!open_cache(path)) {
exit_vm_on_load_failure();
return;
}
if (StoreCachedCode) {
FLAG_SET_DEFAULT(FoldStableValues, false);
FLAG_SET_DEFAULT(ForceUnreachable, true);
}
FLAG_SET_DEFAULT(DelayCompilerStubsGeneration, false);
}
}
void SCCache::init2() {
if (!is_on()) {
return;
}
// After Universe initialized
BarrierSet* bs = BarrierSet::barrier_set();
if (bs->is_a(BarrierSet::CardTableBarrierSet)) {
address byte_map_base = ci_card_table_address_as<address>();
if (is_on_for_write() && !external_word_Relocation::can_be_relocated(byte_map_base)) {
// Bail out since we can't encode card table base address with relocation
log_warning(scc, init)("Can't create Startup Code Cache because card table base address is not relocatable: " INTPTR_FORMAT, p2i(byte_map_base));
close();
exit_vm_on_load_failure();
}
}
// initialize aot runtime constants as appropriate to this runtime
AOTRuntimeConstants::initialize_from_runtime();
if (!verify_vm_config()) {
close();
exit_vm_on_load_failure();
}
// initialize the table of external routines so we can save
// generated code blobs that reference them
init_extrs_table();
// initialize the table of initial stubs so we can save
// generated code blobs that reference them
init_early_stubs_table();
}
void SCCache::print_timers_on(outputStream* st) {
if (LoadCachedCode) {
st->print_cr (" SC Load Time: %7.3f s", _t_totalLoad.seconds());
st->print_cr (" nmethod register: %7.3f s", _t_totalRegister.seconds());
st->print_cr (" find cached code: %7.3f s", _t_totalFind.seconds());
}
if (StoreCachedCode) {
st->print_cr (" SC Store Time: %7.3f s", _t_totalStore.seconds());
}
}
bool SCCache::is_C3_on() {
#if INCLUDE_JVMCI
if (UseJVMCICompiler) {
return (StoreCachedCode || LoadCachedCode) && UseC2asC3;
}
#endif
return false;
}
bool SCCache::is_code_load_thread_on() {
return UseCodeLoadThread && LoadCachedCode;
}
bool SCCache::gen_preload_code(ciMethod* m, int entry_bci) {
VM_ENTRY_MARK;
return (entry_bci == InvocationEntryBci) && is_on() && _cache->gen_preload_code() &&
CDSAccess::can_generate_cached_code(m->get_Method());
}
static void print_helper(nmethod* nm, outputStream* st) {
SCCache::iterate([&](SCCEntry* e) {
if (e->method() == nm->method()) {
ResourceMark rm;
stringStream ss;
ss.print("A%s%d", (e->for_preload() ? "P" : ""), e->comp_level());
if (e->decompile() > 0) {
ss.print("+D%d", e->decompile());
}
ss.print("[%s%s%s]",
(e->is_loaded() ? "L" : ""),
(e->load_fail() ? "F" : ""),
(e->not_entrant() ? "I" : ""));
ss.print("#%d", e->comp_id());
st->print(" %s", ss.freeze());
}
});
}
void SCCache::close() {
if (is_on()) {
if (SCCache::is_on_for_read()) {
LogStreamHandle(Info, init) log;
if (log.is_enabled()) {
log.print_cr("Startup Code Cache statistics (when closed): ");
SCCache::print_statistics_on(&log);
log.cr();
SCCache::print_timers_on(&log);
LogStreamHandle(Info, scc, init) log1;
if (log1.is_enabled()) {
SCCache::print_unused_entries_on(&log1);
}
LogStreamHandle(Info, scc, codecache) info_scc;
// need a lock to traverse the code cache
MutexLocker locker(CodeCache_lock, Mutex::_no_safepoint_check_flag);
if (info_scc.is_enabled()) {
NMethodIterator iter(NMethodIterator::all);
while (iter.next()) {
nmethod* nm = iter.method();
if (nm->is_in_use() && !nm->is_native_method() && !nm->is_osr_method()) {
info_scc.print("%5d:%c%c%c%d:", nm->compile_id(),
(nm->method()->is_shared() ? 'S' : ' '),
(nm->is_scc() ? 'A' : ' '),
(nm->preloaded() ? 'P' : ' '),
nm->comp_level());
print_helper(nm, &info_scc);
info_scc.print(": ");
CompileTask::print(&info_scc, nm, nullptr, true /*short_form*/);
LogStreamHandle(Debug, scc, codecache) debug_scc;
if (debug_scc.is_enabled()) {
MethodTrainingData* mtd = MethodTrainingData::find(methodHandle(Thread::current(), nm->method()));
if (mtd != nullptr) {
mtd->iterate_all_compiles([&](CompileTrainingData* ctd) {
debug_scc.print(" CTD: "); ctd->print_on(&debug_scc); debug_scc.cr();
});
}
}
}
}
}
}
}
delete _cache; // Free memory
_cache = nullptr;
}
}
void SCCache::invalidate(SCCEntry* entry) {
// This could be concurent execution
if (entry != nullptr && is_on()) { // Request could come after cache is closed.
_cache->invalidate_entry(entry);
}
}
bool SCCache::is_loaded(SCCEntry* entry) {
if (is_on() && _cache->cache_buffer() != nullptr) {
return (uint)((char*)entry - _cache->cache_buffer()) < _cache->load_size();
}
return false;
}
void SCCache::preload_code(JavaThread* thread) {
if ((ClassInitBarrierMode == 0) || !is_on_for_read()) {
return;
}
if ((DisableCachedCode & (1 << 3)) != 0) {
return; // no preloaded code (level 5);
}
_cache->preload_startup_code(thread);
}
SCCEntry* SCCache::find_code_entry(const methodHandle& method, uint comp_level) {
switch (comp_level) {
case CompLevel_simple:
if ((DisableCachedCode & (1 << 0)) != 0) {
return nullptr;
}
break;
case CompLevel_limited_profile:
if ((DisableCachedCode & (1 << 1)) != 0) {
return nullptr;
}
break;
case CompLevel_full_optimization:
if ((DisableCachedCode & (1 << 2)) != 0) {
return nullptr;
}
break;
default: return nullptr; // Level 1, 2, and 4 only
}
TraceTime t1("SC total find code time", &_t_totalFind, enable_timers(), false);
if (is_on() && _cache->cache_buffer() != nullptr) {
MethodData* md = method->method_data();
uint decomp = (md == nullptr) ? 0 : md->decompile_count();
ResourceMark rm;
const char* target_name = method->name_and_sig_as_C_string();
uint hash = java_lang_String::hash_code((const jbyte*)target_name, (int)strlen(target_name));
SCCEntry* entry = _cache->find_entry(SCCEntry::Code, hash, comp_level, decomp);
if (entry == nullptr) {
log_info(scc, nmethod)("Missing entry for '%s' (comp_level %d, decomp: %d, hash: " UINT32_FORMAT_X_0 ")", target_name, (uint)comp_level, decomp, hash);
#ifdef ASSERT
} else {
uint name_offset = entry->offset() + entry->name_offset();
uint name_size = entry->name_size(); // Includes '/0'
const char* name = _cache->cache_buffer() + name_offset;
if (strncmp(target_name, name, name_size) != 0) {
assert(false, "SCA: saved nmethod's name '%s' is different from '%s', hash: " UINT32_FORMAT_X_0, name, target_name, hash);
}
#endif
}
DirectiveSet* directives = DirectivesStack::getMatchingDirective(method, nullptr);
if (directives->IgnorePrecompiledOption) {
LogStreamHandle(Info, scc, compilation) log;
if (log.is_enabled()) {
log.print("Ignore cached code entry on level %d for ", comp_level);
method->print_value_on(&log);
}
return nullptr;
}
return entry;
}
return nullptr;
}
void SCCache::add_C_string(const char* str) {
if (is_on_for_write()) {
_cache->add_new_C_string(str);
}
}
bool SCCache::allow_const_field(ciConstant& value) {
return !is_on() || !StoreCachedCode // Restrict only when we generate cache
// Can not trust primitive too || !is_reference_type(value.basic_type())
// May disable this too for now || is_reference_type(value.basic_type()) && value.as_object()->should_be_constant()
;
}
bool SCCache::open_cache(const char* cache_path) {
if (LoadCachedCode) {
log_info(scc)("Trying to load Startup Code Cache '%s'", cache_path);
struct stat st;
if (os::stat(cache_path, &st) != 0) {
log_warning(scc, init)("Specified Startup Code Cache file not found '%s'", cache_path);
return false;
} else if ((st.st_mode & S_IFMT) != S_IFREG) {
log_warning(scc, init)("Specified Startup Code Cache is not file '%s'", cache_path);
return false;
}
int fd = os::open(cache_path, O_RDONLY | O_BINARY, 0);
if (fd < 0) {
if (errno == ENOENT) {
log_warning(scc, init)("Specified Startup Code Cache file not found '%s'", cache_path);
} else {
log_warning(scc, init)("Failed to open Startup Code Cache file '%s': (%s)", cache_path, os::strerror(errno));
}
return false;
} else {
log_info(scc, init)("Opened for read Startup Code Cache '%s'", cache_path);
}
SCCache* cache = new SCCache(cache_path, fd, (uint)st.st_size);
bool failed = cache->failed();
if (::close(fd) < 0) {
log_warning(scc)("Failed to close for read Startup Code Cache file '%s'", cache_path);
failed = true;
}
if (failed) {
delete cache;
_cache = nullptr;
return false;
}
_cache = cache;
}
if (_cache == nullptr && StoreCachedCode) {
SCCache* cache = new SCCache(cache_path, -1 /* fd */, 0 /* size */);
if (cache->failed()) {
delete cache;
_cache = nullptr;
return false;
}
_cache = cache;
}
return true;
}
class CachedCodeDirectory : public CachedCodeDirectoryInternal {
public:
int _some_number;
InstanceKlass* _some_klass;
size_t _my_data_length;
void* _my_data;
};
// Skeleton code for including cached code in CDS:
//
// [1] Use CachedCodeDirectory to keep track of all of data related to cached code.
// E.g., you can build a hashtable to record what methods have been archived.
//
// [2] Memory for all data for cached code, including CachedCodeDirectory, should be
// allocated using CDSAccess::allocate_from_code_cache().
//
// [3] CachedCodeDirectory must be the very first allocation.
//
// [4] Two kinds of pointer can be stored:
// - A pointer p that points to metadata. CDSAccess::can_generate_cached_code(p) must return true.
// - A pointer to a buffer returned by CDSAccess::allocate_from_code_cache().
// (It's OK to point to an interior location within this buffer).
// Such pointers must be stored using CDSAccess::set_pointer()
//
// The buffers allocated by CDSAccess::allocate_from_code_cache() are in a contiguous region. At runtime, this
// region is mapped to the beginning of the CodeCache (see _cds_code_space in codeCache.cpp). All the pointers
// in this buffer are relocated as necessary (e.g., to account for the runtime location of the CodeCache).
//
// Example:
//
// # make sure hw.cds doesn't exist, so that it's regenerated (1.5 step training)
// $ rm -f hw.cds; java -Xlog:cds,scc::uptime,tags,pid -XX:CacheDataStore=hw.cds -cp ~/tmp/HelloWorld.jar HelloWorld
//
// # After training is finish, hw.cds should contain a CachedCodeDirectory. You can see the effect of relocation
// # from the [scc] log.
// $ java -Xlog:cds,scc -XX:CacheDataStore=hw.cds -cp ~/tmp/HelloWorld.jar HelloWorld
// [0.016s][info][scc] new workflow: cached code mapped at 0x7fef97ebc000
// [0.016s][info][scc] _cached_code_directory->_some_klass = 0x800009ca8 (java.lang.String)
// [0.016s][info][scc] _cached_code_directory->_some_number = 0
// [0.016s][info][scc] _cached_code_directory->_my_data_length = 0
// [0.016s][info][scc] _cached_code_directory->_my_data = 0x7fef97ebc020 (32 bytes offset from base)
//
// The 1.5 step training may be hard to debug. If you want to run in a debugger, run the above training step
// with an additional "-XX:+CDSManualFinalImage" command-line argument.
// This is always at the very beginning of the mmaped CDS "cc" (cached code) region
static CachedCodeDirectory* _cached_code_directory = nullptr;
#if INCLUDE_CDS_JAVA_HEAP
void SCCache::new_workflow_start_writing_cache() {
CachedCodeDirectory* dir = (CachedCodeDirectory*)CDSAccess::allocate_from_code_cache(sizeof(CachedCodeDirectory));
_cached_code_directory = dir;
CDSAccess::set_pointer(&dir->_some_klass, vmClasses::String_klass());
size_t n = 120;
void* d = (void*)CDSAccess::allocate_from_code_cache(n);
CDSAccess::set_pointer(&dir->_my_data, d);
}
void SCCache::new_workflow_end_writing_cache() {
_cached_code_directory->dumptime_init_internal();
}
void SCCache::new_workflow_load_cache() {
void* ptr = CodeCache::map_cached_code();
if (ptr != nullptr) {
ResourceMark rm;
_cached_code_directory = (CachedCodeDirectory*)ptr;
// CDS uses this to implement CDSAccess::get_archived_object(k)
_cached_code_directory->runtime_init_internal();
// At this point:
// - CodeCache::initialize_heaps() has finished.
// - CDS archive is fully mapped ("metadata", "heap" and "cached_code" regions are mapped)
// - All pointers in the mapped CDS regions are relocated.
// - CDSAccess::get_archived_object() works.
// Data used by AOT compiler
InstanceKlass* k = _cached_code_directory->_some_klass;
log_info(scc)("new workflow: cached code mapped at %p", ptr);
log_info(scc)("_cached_code_directory->_some_klass = %p (%s)", k, k->external_name());
log_info(scc)("_cached_code_directory->_some_number = %d", _cached_code_directory->_some_number);
log_info(scc)("_cached_code_directory->_my_data_length = %zu", _cached_code_directory->_my_data_length);
log_info(scc)("_cached_code_directory->_my_data = %p (%zu bytes offset from base)", _cached_code_directory->_my_data,
pointer_delta((address)_cached_code_directory->_my_data, (address)_cached_code_directory, 1));
}
}
#endif // INCLUDE_CDS_JAVA_HEAP
#define DATA_ALIGNMENT HeapWordSize
SCCache::SCCache(const char* cache_path, int fd, uint load_size) {
_load_header = nullptr;
_cache_path = cache_path;
_for_read = LoadCachedCode;
_for_write = StoreCachedCode;
_load_size = load_size;
_store_size = 0;
_write_position = 0;
_closing = false;
_failed = false;
_lookup_failed = false;
_table = nullptr;
_load_entries = nullptr;
_store_entries = nullptr;
_C_strings_buf = nullptr;
_load_buffer = nullptr;
_store_buffer = nullptr;
_C_load_buffer = nullptr;
_C_store_buffer = nullptr;
_store_entries_cnt = 0;
_gen_preload_code = false;
_for_preload = false; // changed while storing entry data
_has_clinit_barriers = false;
_compile_id = 0;
_comp_level = 0;
_use_meta_ptrs = UseSharedSpaces ? UseMetadataPointers : false;
// Read header at the begining of cache
uint header_size = sizeof(SCCHeader);
if (_for_read) {
// Read cache
_C_load_buffer = NEW_C_HEAP_ARRAY(char, load_size + DATA_ALIGNMENT, mtCode);
_load_buffer = align_up(_C_load_buffer, DATA_ALIGNMENT);
uint n = (uint)::read(fd, _load_buffer, load_size);
if (n != load_size) {
log_warning(scc, init)("Failed to read %d bytes at address " INTPTR_FORMAT " from Startup Code Cache file '%s'", load_size, p2i(_load_buffer), _cache_path);
set_failed();
return;
}
log_info(scc, init)("Read %d bytes at address " INTPTR_FORMAT " from Startup Code Cache '%s'", load_size, p2i(_load_buffer), _cache_path);
_load_header = (SCCHeader*)addr(0);
const char* scc_jvm_version = addr(_load_header->jvm_version_offset());
if (strncmp(scc_jvm_version, VM_Version::internal_vm_info_string(), strlen(scc_jvm_version)) != 0) {
log_warning(scc, init)("Disable Startup Code Cache: JVM version '%s' recorded in '%s' does not match current version '%s'", scc_jvm_version, _cache_path, VM_Version::internal_vm_info_string());
set_failed();
return;
}
if (!_load_header->verify_config(_cache_path, load_size)) {
set_failed();
return;
}
log_info(scc, init)("Read header from Startup Code Cache '%s'", cache_path);
if (_load_header->has_meta_ptrs()) {
assert(UseSharedSpaces, "should be verified already");
_use_meta_ptrs = true; // Regardless UseMetadataPointers
UseMetadataPointers = true;
}
// Read strings
load_strings();
}
if (_for_write) {
_gen_preload_code = _use_meta_ptrs && (ClassInitBarrierMode > 0);
_C_store_buffer = NEW_C_HEAP_ARRAY(char, CachedCodeMaxSize + DATA_ALIGNMENT, mtCode);
_store_buffer = align_up(_C_store_buffer, DATA_ALIGNMENT);
// Entries allocated at the end of buffer in reverse (as on stack).
_store_entries = (SCCEntry*)align_up(_C_store_buffer + CachedCodeMaxSize, DATA_ALIGNMENT);
log_info(scc, init)("Allocated store buffer at address " INTPTR_FORMAT " of size %d", p2i(_store_buffer), CachedCodeMaxSize);
}
_table = new SCAddressTable();
}
void SCCache::init_extrs_table() {
SCAddressTable* table = addr_table();
if (table != nullptr) {
table->init_extrs();
}
}
void SCCache::init_early_stubs_table() {
SCAddressTable* table = addr_table();
if (table != nullptr) {
table->init_early_stubs();
}
}
void SCCache::init_shared_blobs_table() {
SCAddressTable* table = addr_table();
if (table != nullptr) {
table->init_shared_blobs();
}
}
void SCCache::init_stubs_table() {
SCAddressTable* table = addr_table();
if (table != nullptr) {
table->init_stubs();
}
}
void SCCache::init_opto_table() {
SCAddressTable* table = addr_table();
if (table != nullptr) {
table->init_opto();
}
}
void SCCache::init_c1_table() {
SCAddressTable* table = addr_table();
if (table != nullptr) {
table->init_c1();
}
}
void SCConfig::record(bool use_meta_ptrs) {
_flags = 0;
if (use_meta_ptrs) {
_flags |= metadataPointers;
}
#ifdef ASSERT
_flags |= debugVM;
#endif
if (UseCompressedOops) {
_flags |= compressedOops;
}
if (UseCompressedClassPointers) {
_flags |= compressedClassPointers;
}
if (UseTLAB) {
_flags |= useTLAB;
}
if (JavaAssertions::systemClassDefault()) {
_flags |= systemClassAssertions;
}
if (JavaAssertions::userClassDefault()) {
_flags |= userClassAssertions;
}
if (EnableContended) {
_flags |= enableContendedPadding;
}
if (RestrictContended) {
_flags |= restrictContendedPadding;
}
_compressedOopShift = CompressedOops::shift();
_compressedKlassShift = CompressedKlassPointers::shift();
_contendedPaddingWidth = ContendedPaddingWidth;
_objectAlignment = ObjectAlignmentInBytes;
_gc = (uint)Universe::heap()->kind();
}
bool SCConfig::verify(const char* cache_path) const {
#ifdef ASSERT
if ((_flags & debugVM) == 0) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created by product VM, it can't be used by debug VM", cache_path);
return false;
}
#else
if ((_flags & debugVM) != 0) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created by debug VM, it can't be used by product VM", cache_path);
return false;
}
#endif
CollectedHeap::Name scc_gc = (CollectedHeap::Name)_gc;
if (scc_gc != Universe::heap()->kind()) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with different GC: %s vs current %s", cache_path, GCConfig::hs_err_name(scc_gc), GCConfig::hs_err_name());
return false;
}
if (((_flags & compressedOops) != 0) != UseCompressedOops) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with UseCompressedOops = %s", cache_path, UseCompressedOops ? "false" : "true");
return false;
}
if (((_flags & compressedClassPointers) != 0) != UseCompressedClassPointers) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with UseCompressedClassPointers = %s", cache_path, UseCompressedClassPointers ? "false" : "true");
return false;
}
if (((_flags & systemClassAssertions) != 0) != JavaAssertions::systemClassDefault()) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with JavaAssertions::systemClassDefault() = %s", cache_path, JavaAssertions::systemClassDefault() ? "disabled" : "enabled");
return false;
}
if (((_flags & userClassAssertions) != 0) != JavaAssertions::userClassDefault()) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with JavaAssertions::userClassDefault() = %s", cache_path, JavaAssertions::userClassDefault() ? "disabled" : "enabled");
return false;
}
if (((_flags & enableContendedPadding) != 0) != EnableContended) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with EnableContended = %s", cache_path, EnableContended ? "false" : "true");
return false;
}
if (((_flags & restrictContendedPadding) != 0) != RestrictContended) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with RestrictContended = %s", cache_path, RestrictContended ? "false" : "true");
return false;
}
if (_compressedOopShift != (uint)CompressedOops::shift()) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with CompressedOops::shift() = %d vs current %d", cache_path, _compressedOopShift, CompressedOops::shift());
return false;
}
if (_compressedKlassShift != (uint)CompressedKlassPointers::shift()) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with CompressedKlassPointers::shift() = %d vs current %d", cache_path, _compressedKlassShift, CompressedKlassPointers::shift());
return false;
}
if (_contendedPaddingWidth != (uint)ContendedPaddingWidth) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with ContendedPaddingWidth = %d vs current %d", cache_path, _contendedPaddingWidth, ContendedPaddingWidth);
return false;
}
if (_objectAlignment != (uint)ObjectAlignmentInBytes) {
log_warning(scc, init)("Disable Startup Code Cache: '%s' was created with ObjectAlignmentInBytes = %d vs current %d", cache_path, _objectAlignment, ObjectAlignmentInBytes);
return false;
}
return true;
}
bool SCCHeader::verify_config(const char* cache_path, uint load_size) const {
if (_version != SCC_VERSION) {
log_warning(scc, init)("Disable Startup Code Cache: different SCC version %d vs %d recorded in '%s'", SCC_VERSION, _version, cache_path);
return false;
}
if (_cache_size != load_size) {
log_warning(scc, init)("Disable Startup Code Cache: different cached code size %d vs %d recorded in '%s'", load_size, _cache_size, cache_path);
return false;
}
if (has_meta_ptrs() && !UseSharedSpaces) {
log_warning(scc, init)("Disable Startup Cached Code: '%s' contains metadata pointers but CDS is off", cache_path);
return false;
}
return true;
}
volatile int SCCache::_nmethod_readers = 0;
SCCache::~SCCache() {
if (_closing) {
return; // Already closed
}
// Stop any further access to cache.
// Checked on entry to load_nmethod() and store_nmethod().
_closing = true;
if (_for_read) {
// Wait for all load_nmethod() finish.
wait_for_no_nmethod_readers();
}
// Prevent writing code into cache while we are closing it.
// This lock held by ciEnv::register_method() which calls store_nmethod().
MutexLocker ml(Compile_lock);
if (for_write()) { // Finalize cache
finish_write();
}
FREE_C_HEAP_ARRAY(char, _cache_path);
if (_C_load_buffer != nullptr) {
FREE_C_HEAP_ARRAY(char, _C_load_buffer);
_C_load_buffer = nullptr;
_load_buffer = nullptr;
}
if (_C_store_buffer != nullptr) {
FREE_C_HEAP_ARRAY(char, _C_store_buffer);
_C_store_buffer = nullptr;
_store_buffer = nullptr;
}
if (_table != nullptr) {
delete _table;
_table = nullptr;
}
}
SCCache* SCCache::open_for_read() {
if (SCCache::is_on_for_read()) {
return SCCache::cache();
}
return nullptr;
}
SCCache* SCCache::open_for_write() {
if (SCCache::is_on_for_write()) {
SCCache* cache = SCCache::cache();
cache->clear_lookup_failed(); // Reset bit
return cache;
}
return nullptr;
}
void copy_bytes(const char* from, address to, uint size) {
assert(size > 0, "sanity");
bool by_words = true;
if ((size > 2 * HeapWordSize) && (((intptr_t)from | (intptr_t)to) & (HeapWordSize - 1)) == 0) {
// Use wordwise copies if possible:
Copy::disjoint_words((HeapWord*)from,
(HeapWord*)to,
((size_t)size + HeapWordSize-1) / HeapWordSize);
} else {
by_words = false;
Copy::conjoint_jbytes(from, to, (size_t)size);
}
log_trace(scc)("Copied %d bytes as %s from " INTPTR_FORMAT " to " INTPTR_FORMAT, size, (by_words ? "HeapWord" : "bytes"), p2i(from), p2i(to));
}
void SCCReader::set_read_position(uint pos) {
if (pos == _read_position) {
return;
}
assert(pos < _cache->load_size(), "offset:%d >= file size:%d", pos, _cache->load_size());
_read_position = pos;
}
bool SCCache::set_write_position(uint pos) {
if (pos == _write_position) {
return true;
}
if (_store_size < _write_position) {
_store_size = _write_position; // Adjust during write
}
assert(pos < _store_size, "offset:%d >= file size:%d", pos, _store_size);
_write_position = pos;
return true;
}
static char align_buffer[256] = { 0 };
bool SCCache::align_write() {
// We are not executing code from cache - we copy it by bytes first.
// No need for big alignment (or at all).
uint padding = DATA_ALIGNMENT - (_write_position & (DATA_ALIGNMENT - 1));
if (padding == DATA_ALIGNMENT) {
return true;
}
uint n = write_bytes((const void*)&align_buffer, padding);
if (n != padding) {
return false;
}
log_trace(scc)("Adjust write alignment in Startup Code Cache '%s'", _cache_path);
return true;
}
uint SCCache::write_bytes(const void* buffer, uint nbytes) {
assert(for_write(), "Code Cache file is not created");
if (nbytes == 0) {
return 0;
}
uint new_position = _write_position + nbytes;
if (new_position >= (uint)((char*)_store_entries - _store_buffer)) {
log_warning(scc)("Failed to write %d bytes at offset %d to Startup Code Cache file '%s'. Increase CachedCodeMaxSize.",
nbytes, _write_position, _cache_path);
set_failed();
exit_vm_on_store_failure();
return 0;
}
copy_bytes((const char* )buffer, (address)(_store_buffer + _write_position), nbytes);
log_trace(scc)("Wrote %d bytes at offset %d to Startup Code Cache '%s'", nbytes, _write_position, _cache_path);
_write_position += nbytes;
if (_store_size < _write_position) {
_store_size = _write_position;
}
return nbytes;
}
void SCCEntry::update_method_for_writing() {
if (_method != nullptr) {
_method = CDSAccess::method_in_cached_code(_method);
}
}
void SCCEntry::print(outputStream* st) const {
st->print_cr(" SCA entry " INTPTR_FORMAT " [kind: %d, id: " UINT32_FORMAT_X_0 ", offset: %d, size: %d, comp_level: %d, comp_id: %d, decompiled: %d, %s%s%s%s%s]",
p2i(this), (int)_kind, _id, _offset, _size, _comp_level, _comp_id, _decompile,
(_not_entrant? "not_entrant" : "entrant"),
(_loaded ? ", loaded" : ""),
(_has_clinit_barriers ? ", has_clinit_barriers" : ""),
(_for_preload ? ", for_preload" : ""),
(_ignore_decompile ? ", ignore_decomp" : ""));
}
void* SCCEntry::operator new(size_t x, SCCache* cache) {
return (void*)(cache->add_entry());
}
bool skip_preload(methodHandle mh) {
if (!mh->method_holder()->is_loaded()) {
return true;
}
DirectiveSet* directives = DirectivesStack::getMatchingDirective(mh, nullptr);
if (directives->DontPreloadOption) {
LogStreamHandle(Info, scc, init) log;
if (log.is_enabled()) {
log.print("Exclude preloading code for ");
mh->print_value_on(&log);
}
return true;
}
return false;
}
void SCCache::preload_startup_code(TRAPS) {
if (CompilationPolicy::compiler_count(CompLevel_full_optimization) == 0) {
// Since we reuse the CompilerBroker API to install cached code, we're required to have a JIT compiler for the
// level we want (that is CompLevel_full_optimization).
return;
}
assert(_for_read, "sanity");
uint count = _load_header->entries_count();
if (_load_entries == nullptr) {
// Read it
_search_entries = (uint*)addr(_load_header->entries_offset()); // [id, index]
_load_entries = (SCCEntry*)(_search_entries + 2 * count);
log_info(scc, init)("Read %d entries table at offset %d from Startup Code Cache '%s'", count, _load_header->entries_offset(), _cache_path);
}
uint preload_entries_count = _load_header->preload_entries_count();
if (preload_entries_count > 0) {
uint* entries_index = (uint*)addr(_load_header->preload_entries_offset());
log_info(scc, init)("Load %d preload entries from Startup Code Cache '%s'", preload_entries_count, _cache_path);
uint count = MIN2(preload_entries_count, SCLoadStop);
for (uint i = SCLoadStart; i < count; i++) {
uint index = entries_index[i];
SCCEntry* entry = &(_load_entries[index]);
if (entry->not_entrant()) {
continue;
}
methodHandle mh(THREAD, entry->method());
assert((mh.not_null() && MetaspaceShared::is_in_shared_metaspace((address)mh())), "sanity");
if (skip_preload(mh)) {
continue; // Exclude preloading for this method
}
assert(mh->method_holder()->is_loaded(), "");
if (!mh->method_holder()->is_linked()) {
assert(!HAS_PENDING_EXCEPTION, "");
mh->method_holder()->link_class(THREAD);
if (HAS_PENDING_EXCEPTION) {
LogStreamHandle(Info, scc) log;
if (log.is_enabled()) {
ResourceMark rm;
log.print("Linkage failed for %s: ", mh->method_holder()->external_name());
THREAD->pending_exception()->print_value_on(&log);
if (log_is_enabled(Debug, scc)) {
THREAD->pending_exception()->print_on(&log);
}
}
CLEAR_PENDING_EXCEPTION;
}
}
if (mh->scc_entry() != nullptr) {
// Second C2 compilation of the same method could happen for
// different reasons without marking first entry as not entrant.
continue; // Keep old entry to avoid issues
}
mh->set_scc_entry(entry);
CompileBroker::compile_method(mh, InvocationEntryBci, CompLevel_full_optimization, methodHandle(), 0, false, CompileTask::Reason_Preload, CHECK);
}
}
}
static bool check_entry(SCCEntry::Kind kind, uint id, uint comp_level, uint decomp, SCCEntry* entry) {
if (entry->kind() == kind) {
assert(entry->id() == id, "sanity");
if (kind != SCCEntry::Code || (!entry->not_entrant() && !entry->has_clinit_barriers() &&
(entry->comp_level() == comp_level) &&
(entry->ignore_decompile() || entry->decompile() == decomp))) {
return true; // Found
}
}
return false;
}
SCCEntry* SCCache::find_entry(SCCEntry::Kind kind, uint id, uint comp_level, uint decomp) {
assert(_for_read, "sanity");
uint count = _load_header->entries_count();
if (_load_entries == nullptr) {
// Read it
_search_entries = (uint*)addr(_load_header->entries_offset()); // [id, index]
_load_entries = (SCCEntry*)(_search_entries + 2 * count);
log_info(scc, init)("Read %d entries table at offset %d from Startup Code Cache '%s'", count, _load_header->entries_offset(), _cache_path);
}
// Binary search
int l = 0;
int h = count - 1;
while (l <= h) {
int mid = (l + h) >> 1;
int ix = mid * 2;
uint is = _search_entries[ix];