1 /*
  2  * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "logging/log.hpp"
 26 #include "memory/metaspace.hpp"
 27 #include "oops/compressedKlass.inline.hpp"
 28 #include "runtime/globals.hpp"
 29 #include "runtime/java.hpp"
 30 #include "runtime/os.hpp"
 31 #include "utilities/debug.hpp"
 32 #include "utilities/formatBuffer.hpp"
 33 #include "utilities/globalDefinitions.hpp"
 34 #include "utilities/ostream.hpp"
 35 
 36 int CompressedKlassPointers::_narrow_klass_pointer_bits = -1;
 37 int CompressedKlassPointers::_max_shift = -1;
 38 
 39 address CompressedKlassPointers::_base = (address)-1;
 40 int CompressedKlassPointers::_shift = -1;
 41 address CompressedKlassPointers::_klass_range_start = nullptr;
 42 address CompressedKlassPointers::_klass_range_end = nullptr;
 43 narrowKlass CompressedKlassPointers::_lowest_valid_narrow_klass_id = (narrowKlass)-1;
 44 narrowKlass CompressedKlassPointers::_highest_valid_narrow_klass_id = (narrowKlass)-1;
 45 size_t CompressedKlassPointers::_protection_zone_size = 0;
 46 
 47 #ifdef _LP64
 48 
 49 size_t CompressedKlassPointers::max_klass_range_size() {
 50   // We disallow klass range sizes larger than 4GB even if the encoding
 51   // range would allow for a larger Klass range (e.g. Base=zero, shift=3 -> 32GB).
 52   // That is because many CPU-specific compiler decodings do not want the
 53   // shifted narrow Klass to spill over into the third quadrant of the 64-bit target
 54   // address, e.g. to use a 16-bit move for a simplified base addition.
 55   return MIN2(4 * G, max_encoding_range_size());
 56 }
 57 
 58 void CompressedKlassPointers::pre_initialize() {
 59   if (UseCompactObjectHeaders) {
 60     _narrow_klass_pointer_bits = narrow_klass_pointer_bits_coh;
 61     _max_shift = max_shift_coh;
 62   } else {
 63     _narrow_klass_pointer_bits = narrow_klass_pointer_bits_noncoh;
 64     _max_shift = max_shift_noncoh;
 65   }
 66 }
 67 
 68 #ifdef ASSERT
 69 void CompressedKlassPointers::sanity_check_after_initialization() {
 70   // In expectation of an assert, prepare condensed info to be printed with the assert.
 71   char tmp[256];
 72   os::snprintf(tmp, sizeof(tmp), "klass range: " RANGE2FMT ","
 73       " base " PTR_FORMAT ", shift %d, lowest/highest valid narrowKlass %u/%u",
 74       RANGE2FMTARGS(_klass_range_start, _klass_range_end),
 75       p2i(_base), _shift, _lowest_valid_narrow_klass_id, _highest_valid_narrow_klass_id);
 76 #define ASSERT_HERE(cond) assert(cond, " (%s)", tmp);
 77 #define ASSERT_HERE_2(cond, msg) assert(cond, msg " (%s)", tmp);
 78 
 79   // All values must be inited
 80   ASSERT_HERE(_max_shift != -1);
 81   ASSERT_HERE(_klass_range_start != (address)-1);
 82   ASSERT_HERE(_klass_range_end != (address)-1);
 83   ASSERT_HERE(_lowest_valid_narrow_klass_id != (narrowKlass)-1);
 84   ASSERT_HERE(_base != (address)-1);
 85   ASSERT_HERE(_shift != -1);
 86 
 87   const size_t klass_align = klass_alignment_in_bytes();
 88 
 89   // must be aligned enough hold 64-bit data
 90   ASSERT_HERE(is_aligned(klass_align, sizeof(uint64_t)));
 91 
 92   // should be smaller than the minimum metaspace chunk size (soft requirement)
 93   ASSERT_HERE(klass_align <= K);
 94 
 95   ASSERT_HERE(_klass_range_end > _klass_range_start);
 96 
 97   // Check that Klass range is fully engulfed in the encoding range
 98   const address encoding_start = _base;
 99   const address encoding_end = (address)(p2u(_base) + (uintptr_t)nth_bit(narrow_klass_pointer_bits() + _shift));
100   ASSERT_HERE_2(_klass_range_start >= _base && _klass_range_end <= encoding_end,
101                 "Resulting encoding range does not fully cover the class range");
102 
103   // Check that Klass range is aligned to Klass alignment. Note that this should never be
104   // an issue since the Klass range is handed in by either CDS- or Metaspace-initialization, and
105   // it should be the result of an mmap operation that operates on page sizes. So as long as
106   // the Klass alignment is <= page size, we are fine.
107   ASSERT_HERE_2(is_aligned(_klass_range_start, klass_align) &&
108                 is_aligned(_klass_range_end, klass_align),
109                 "Klass range must start and end at a properly aligned address");
110 
111   // Check _lowest_valid_narrow_klass_id and _highest_valid_narrow_klass_id
112   ASSERT_HERE_2(_lowest_valid_narrow_klass_id > 0, "Null is not a valid narrowKlass");
113   ASSERT_HERE(_highest_valid_narrow_klass_id > _lowest_valid_narrow_klass_id);
114 
115   Klass* const k1 = decode_not_null_without_asserts(_lowest_valid_narrow_klass_id, _base, _shift);
116   if (encoding_start == _klass_range_start) {
117     ASSERT_HERE_2((address)k1 == _klass_range_start + klass_align, "Not lowest");
118   } else {
119     ASSERT_HERE_2((address)k1 == _klass_range_start, "Not lowest");
120   }
121   narrowKlass nk1 = encode_not_null_without_asserts(k1, _base, _shift);
122   ASSERT_HERE_2(nk1 == _lowest_valid_narrow_klass_id, "not reversible");
123 
124   Klass* const k2 = decode_not_null_without_asserts(_highest_valid_narrow_klass_id, _base, _shift);
125   ASSERT_HERE((address)k2 == _klass_range_end - klass_align);
126   narrowKlass nk2 = encode_not_null_without_asserts(k2, _base, _shift);
127   ASSERT_HERE_2(nk2 == _highest_valid_narrow_klass_id, "not reversible");
128 
129 #ifdef AARCH64
130   // On aarch64, we never expect a shift value > 0 in standard (non-coh) mode
131   ASSERT_HERE_2(UseCompactObjectHeaders || _shift == 0, "Shift > 0 in non-coh mode?");
132 #endif
133 #undef ASSERT_HERE
134 #undef ASSERT_HERE_2
135 }
136 #endif // ASSERT
137 
138 // Helper function: given current Klass Range, Base and Shift, calculate the lowest and highest values
139 // of narrowKlass we can expect.
140 void CompressedKlassPointers::calc_lowest_highest_narrow_klass_id() {
141   address lowest_possible_klass_location = _klass_range_start;
142 
143   // A Klass will never be placed at the Encoding range start, since that would translate to a narrowKlass=0, which
144   // is disallowed. Note that both Metaspace and CDS prvent allocation at the first address for this reason.
145   if (lowest_possible_klass_location == _base) {
146     lowest_possible_klass_location += klass_alignment_in_bytes();
147   }
148   _lowest_valid_narrow_klass_id = (narrowKlass) ((uintptr_t)(lowest_possible_klass_location - _base) >> _shift);
149 
150   address highest_possible_klass_location = _klass_range_end - klass_alignment_in_bytes();
151   _highest_valid_narrow_klass_id = (narrowKlass) ((uintptr_t)(highest_possible_klass_location - _base) >> _shift);
152 }
153 
154 // Given a klass range [addr, addr+len) and a given encoding scheme, assert that this scheme covers the range, then
155 // set this encoding scheme. Used by CDS at runtime to re-instate the scheme used to pre-compute klass ids for
156 // archived heap objects.
157 void CompressedKlassPointers::initialize_for_given_encoding(address addr, size_t len, address requested_base, int requested_shift) {
158   if (len > max_klass_range_size()) {
159     stringStream ss;
160     ss.print("Class space size and CDS archive size combined (%zu) "
161              "exceed the maximum possible size (%zu)",
162              len, max_klass_range_size());
163     vm_exit_during_initialization(ss.base());
164   }
165 
166   // Remember Klass range:
167   _klass_range_start = addr;
168   _klass_range_end = addr + len;
169 
170   _base = requested_base;
171   _shift = requested_shift;
172 
173   calc_lowest_highest_narrow_klass_id();
174 
175   // This has already been checked for SharedBaseAddress and if this fails, it's a bug in the allocation code.
176   if (!set_klass_decode_mode()) {
177     fatal("base=" PTR_FORMAT " given with shift %d, cannot be used to encode class pointers",
178           p2i(_base), _shift);
179   }
180 
181   DEBUG_ONLY(sanity_check_after_initialization();)
182 }
183 
184 char* CompressedKlassPointers::reserve_address_space_X(uintptr_t from, uintptr_t to, size_t size, size_t alignment, bool aslr) {
185   alignment = MAX2(Metaspace::reserve_alignment(), alignment);
186   return os::attempt_reserve_memory_between((char*)from, (char*)to, size, alignment, aslr);
187 }
188 
189 char* CompressedKlassPointers::reserve_address_space_for_unscaled_encoding(size_t size, bool aslr) {
190   const size_t unscaled_max = nth_bit(narrow_klass_pointer_bits());
191   return reserve_address_space_X(0, unscaled_max, size, Metaspace::reserve_alignment(), aslr);
192 }
193 
194 char* CompressedKlassPointers::reserve_address_space_for_zerobased_encoding(size_t size, bool aslr) {
195   const size_t unscaled_max = nth_bit(narrow_klass_pointer_bits());
196   const size_t zerobased_max = nth_bit(narrow_klass_pointer_bits() + max_shift());
197   return reserve_address_space_X(unscaled_max, zerobased_max, size, Metaspace::reserve_alignment(), aslr);
198 }
199 
200 char* CompressedKlassPointers::reserve_address_space_for_16bit_move(size_t size, bool aslr) {
201   return reserve_address_space_X(nth_bit(32), nth_bit(48), size, nth_bit(32), aslr);
202 }
203 
204 void CompressedKlassPointers::initialize(address addr, size_t len) {
205 
206   if (len > max_klass_range_size()) {
207     stringStream ss;
208     ss.print("Class space size (%zu) exceeds the maximum possible size (%zu)",
209               len, max_klass_range_size());
210     vm_exit_during_initialization(ss.base());
211   }
212 
213   // Remember the Klass range:
214   _klass_range_start = addr;
215   _klass_range_end = addr + len;
216 
217   // Calculate Base and Shift:
218 
219   if (UseCompactObjectHeaders) {
220 
221     // In compact object header mode, with 22-bit narrowKlass, we don't attempt for
222     // zero-based mode. Instead, we set the base to the start of the klass range and
223     // then try for the smallest shift possible that still covers the whole range.
224     // The reason is that we want to avoid, if possible, shifts larger than
225     // a cacheline size.
226     _base = addr;
227 
228     const int log_cacheline = exact_log2(DEFAULT_CACHE_LINE_SIZE);
229     int s = max_shift();
230     while (s > log_cacheline && ((size_t)nth_bit(narrow_klass_pointer_bits() + s - 1) > len)) {
231       s--;
232     }
233     _shift = s;
234 
235   } else {
236 
237     // Traditional (non-compact) header mode
238     const uintptr_t unscaled_max = nth_bit(narrow_klass_pointer_bits());
239     const uintptr_t zerobased_max = nth_bit(narrow_klass_pointer_bits() + max_shift());
240 
241 #ifdef AARCH64
242     // Aarch64 avoids zero-base shifted mode (_base=0 _shift>0), instead prefers
243     // non-zero-based mode with a zero shift.
244     _shift = 0;
245     address const end = addr + len;
246     _base = (end <= (address)unscaled_max) ? nullptr : addr;
247 #else
248     // We try, in order of preference:
249     // -unscaled    (base=0 shift=0)
250     // -zero-based  (base=0 shift>0)
251     // -nonzero-base (base>0 shift=0)
252     // Note that base>0 shift>0 should never be needed, since the klass range will
253     // never exceed 4GB.
254     address const end = addr + len;
255     if (end <= (address)unscaled_max) {
256       _base = nullptr;
257       _shift = 0;
258     } else {
259       if (end <= (address)zerobased_max) {
260         _base = nullptr;
261         _shift = max_shift();
262       } else {
263         _base = addr;
264         _shift = 0;
265       }
266     }
267 #endif // AARCH64
268   }
269 
270   calc_lowest_highest_narrow_klass_id();
271 
272   // Initialize klass decode mode and check compability with decode instructions
273   if (!set_klass_decode_mode()) {
274 
275     // Give fatal error if this is a specified address
276     if (CompressedClassSpaceBaseAddress == (size_t)_base) {
277       vm_exit_during_initialization(
278             err_msg("CompressedClassSpaceBaseAddress=" PTR_FORMAT " given with shift %d, cannot be used to encode class pointers",
279                     CompressedClassSpaceBaseAddress, _shift));
280     } else {
281       // If this fails, it's a bug in the allocation code.
282       fatal("CompressedClassSpaceBaseAddress=" PTR_FORMAT " given with shift %d, cannot be used to encode class pointers",
283             p2i(_base), _shift);
284     }
285   }
286 #ifdef ASSERT
287   sanity_check_after_initialization();
288 #endif
289 }
290 
291 void CompressedKlassPointers::print_mode(outputStream* st) {
292   st->print_cr("UseCompressedClassPointers %d, UseCompactObjectHeaders %d",
293                UseCompressedClassPointers, UseCompactObjectHeaders);
294   if (UseCompressedClassPointers) {
295     st->print_cr("Narrow klass pointer bits %d, Max shift %d",
296                  _narrow_klass_pointer_bits, _max_shift);
297     st->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: %d",
298                   p2i(base()), shift());
299     st->print_cr("Encoding Range: " RANGE2FMT, RANGE2FMTARGS(_base, encoding_range_end()));
300     st->print_cr("Klass Range:    " RANGE2FMT, RANGE2FMTARGS(_klass_range_start, _klass_range_end));
301     st->print_cr("Klass ID Range:  [%u - %u) (%u)", _lowest_valid_narrow_klass_id, _highest_valid_narrow_klass_id + 1,
302                  _highest_valid_narrow_klass_id + 1 - _lowest_valid_narrow_klass_id);
303     if (_protection_zone_size > 0) {
304       st->print_cr("Protection zone: " RANGEFMT, RANGEFMTARGS(_base, _protection_zone_size));
305     } else {
306       st->print_cr("No protection zone.");
307     }
308   } else {
309     st->print_cr("UseCompressedClassPointers off");
310   }
311 }
312 
313 // On AIX, we cannot mprotect archive space or class space since they are reserved with SystemV shm.
314 static constexpr bool can_mprotect_archive_space = NOT_AIX(true) AIX_ONLY(false);
315 
316 // Protect a zone a the start of the encoding range
317 void CompressedKlassPointers::establish_protection_zone(address addr, size_t size) {
318   assert(_protection_zone_size == 0, "just once");
319   assert(addr == base(), "Protection zone not at start of encoding range?");
320   assert(size > 0 && is_aligned(size, os::vm_page_size()), "Protection zone not page sized");
321   const bool rc = can_mprotect_archive_space && os::protect_memory((char*)addr, size, os::MEM_PROT_NONE, false);
322   log_info(metaspace)("%s Narrow Klass Protection zone " RANGEFMT,
323       (rc ? "Established" : "FAILED to establish "),
324       RANGEFMTARGS(addr, size));
325   if (!rc) {
326     // If we fail to establish the protection zone, we fill it with a clear pattern to make it
327     // stick out in register values (0x50 aka 'P', repeated)
328     os::commit_memory((char*)addr, size, false);
329     memset(addr, 'P', size);
330   }
331   _protection_zone_size = size;
332 }
333 
334 bool CompressedKlassPointers::is_in_protection_zone(address addr) {
335   return _protection_zone_size > 0 ?
336       (addr >= base() && addr < base() + _protection_zone_size) : false;
337 }
338 
339 #endif // _LP64