1 /* 2 * Copyright (c) 2016, 2018, 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 26 package jdk.tools.jaotc.binformat; 27 28 import static org.graalvm.compiler.hotspot.meta.HotSpotAOTProfilingPlugin.Options.TieredAOT; 29 30 import java.io.ByteArrayOutputStream; 31 import java.io.DataOutputStream; 32 import java.io.IOException; 33 import java.util.ArrayList; 34 import java.util.HashMap; 35 import java.util.List; 36 import java.util.Map; 37 38 import jdk.tools.jaotc.binformat.Symbol.Binding; 39 import jdk.tools.jaotc.binformat.Symbol.Kind; 40 import jdk.tools.jaotc.binformat.elf.JELFRelocObject; 41 import jdk.tools.jaotc.binformat.macho.JMachORelocObject; 42 import jdk.tools.jaotc.binformat.pecoff.JPECoffRelocObject; 43 import org.graalvm.compiler.hotspot.GraalHotSpotVMConfig; 44 import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderConfiguration; 45 import org.graalvm.compiler.options.OptionValues; 46 47 /** 48 * A format-agnostic container class that holds various components of a binary. 49 * 50 * <p> 51 * This class holds information necessary to create platform-specific binary containers such as 52 * ELFContainer for Linux and Solaris operating systems or MachOContainer for Mac OS or PEContainer 53 * for MS Windows operating systems. 54 * 55 * <p> 56 * Method APIs provided by this class are used to construct and populate platform-independent 57 * contents of a binary as the first step to create a binary representation of code generated by a 58 * compiler backend such as Graal. 59 * 60 * <p> 61 * Methods to record and access code section contents, symbols and relocations are provided. 62 */ 63 public final class BinaryContainer implements SymbolTable { 64 private final OptionValues graalOptions; 65 66 private final int codeSegmentSize; 67 68 private final int codeEntryAlignment; 69 70 private final boolean threadLocalHandshakes; 71 72 /** 73 * Container holding code bits and any other related information. 74 */ 75 private final CodeContainer codeContainer; 76 77 /** 78 * Container holding global offset data for hotspot linkage. 79 */ 80 private final ByteContainer extLinkageGOTContainer; 81 82 /** 83 * Patched by HotSpot, contains Klass pointers. 84 */ 85 private final ByteContainer klassesGotContainer; 86 87 /** 88 * Patched by HotSpot, contains MethodCounters pointers. 89 */ 90 private final ByteContainer countersGotContainer; 91 92 /** 93 * Patched lazily by hotspot, contains klass/method pointers. 94 */ 95 private final ByteContainer metadataGotContainer; 96 97 /** 98 * BSS container, contains method state array. 99 */ 100 private final ByteContainer methodStateContainer; 101 102 /** 103 * Patched by hotspot, contains java object pointers. 104 */ 105 private final ByteContainer oopGotContainer; 106 107 // Containers holding read-only data 108 private final ReadOnlyDataContainer configContainer; 109 private final ReadOnlyDataContainer metaspaceNamesContainer; 110 private final ReadOnlyDataContainer methodsOffsetsContainer; 111 private final ReadOnlyDataContainer klassesOffsetsContainer; 112 private final ReadOnlyDataContainer klassesDependenciesContainer; 113 private final HeaderContainer headerContainer; 114 private final ReadOnlyDataContainer stubsOffsetsContainer; 115 private final ReadOnlyDataContainer codeSegmentsContainer; 116 117 // This cannot be read only since we need to patch the metadata at runtime.. 118 private final ReadOnlyDataContainer methodMetadataContainer; 119 120 /** 121 * Container containing constant data used by code. 122 */ 123 private final ReadOnlyDataContainer constantDataContainer; 124 125 /** 126 * Map holding the Strings table. 127 */ 128 private final Map<String, Integer> offsetStringTable = new HashMap<>(); 129 130 private final Map<String, Integer> metaspaceNames = new HashMap<>(); 131 132 // List of relocation table entries - (symbolName, relocationInfo) 133 private final Map<String, Symbol> symbolTable = new HashMap<>(); 134 private final Map<Symbol, List<Relocation>> relocationTable = new HashMap<>(); 135 private final Map<Symbol, Relocation> uniqueRelocationTable = new HashMap<>(); 136 137 /** 138 * Mapping of local VM function names to known global symbols generated in the output binary. 139 */ 140 private static final HashMap<String, String> functionNamesToAOTSymbols = new HashMap<>(); 141 142 //@formatter:off 143 private static final String[][] map = { 144 {"CompilerToVM::Data::SharedRuntime_deopt_blob_unpack", "_aot_deopt_blob_unpack"}, 145 {"CompilerToVM::Data::SharedRuntime_deopt_blob_uncommon_trap", "_aot_deopt_blob_uncommon_trap"}, 146 {"CompilerToVM::Data::SharedRuntime_ic_miss_stub", "_aot_ic_miss_stub"}, 147 {"CompilerToVM::Data::SharedRuntime_handle_wrong_method_stub", "_aot_handle_wrong_method_stub"}, 148 {"SharedRuntime::exception_handler_for_return_address", "_aot_exception_handler_for_return_address"}, 149 {"SharedRuntime::register_finalizer", "_aot_register_finalizer"}, 150 {"SharedRuntime::OSR_migration_end", "_aot_OSR_migration_end"}, 151 {"SharedRuntime::enable_stack_reserved_zone", "_aot_enable_stack_reserved_zone"}, 152 {"CompilerRuntime::resolve_dynamic_invoke", "_aot_resolve_dynamic_invoke"}, 153 {"CompilerRuntime::resolve_string_by_symbol", "_aot_resolve_string_by_symbol"}, 154 {"CompilerRuntime::resolve_klass_by_symbol", "_aot_resolve_klass_by_symbol"}, 155 {"CompilerRuntime::resolve_method_by_symbol_and_load_counters", "_aot_resolve_method_by_symbol_and_load_counters"}, 156 {"CompilerRuntime::initialize_klass_by_symbol", "_aot_initialize_klass_by_symbol"}, 157 {"CompilerRuntime::invocation_event", "_aot_invocation_event"}, 158 {"CompilerRuntime::backedge_event", "_aot_backedge_event"}, 159 160 {"CompilerToVM::Data::dpow", "_aot_shared_runtime_dpow"}, 161 {"CompilerToVM::Data::dexp", "_aot_shared_runtime_dexp"}, 162 {"CompilerToVM::Data::dcos", "_aot_shared_runtime_dcos"}, 163 {"CompilerToVM::Data::dsin", "_aot_shared_runtime_dsin"}, 164 {"CompilerToVM::Data::dtan", "_aot_shared_runtime_dtan"}, 165 {"CompilerToVM::Data::dlog", "_aot_shared_runtime_dlog"}, 166 {"CompilerToVM::Data::dlog10", "_aot_shared_runtime_dlog10"}, 167 168 {"StubRoutines::_jbyte_arraycopy", "_aot_stub_routines_jbyte_arraycopy"}, 169 {"StubRoutines::_jshort_arraycopy", "_aot_stub_routines_jshort_arraycopy"}, 170 {"StubRoutines::_jint_arraycopy", "_aot_stub_routines_jint_arraycopy"}, 171 {"StubRoutines::_jlong_arraycopy", "_aot_stub_routines_jlong_arraycopy"}, 172 {"StubRoutines::_oop_arraycopy", "_aot_stub_routines_oop_arraycopy"}, 173 {"StubRoutines::_oop_arraycopy_uninit", "_aot_stub_routines_oop_arraycopy_uninit"}, 174 175 {"StubRoutines::_jbyte_disjoint_arraycopy", "_aot_stub_routines_jbyte_disjoint_arraycopy"}, 176 {"StubRoutines::_jshort_disjoint_arraycopy", "_aot_stub_routines_jshort_disjoint_arraycopy"}, 177 {"StubRoutines::_jint_disjoint_arraycopy", "_aot_stub_routines_jint_disjoint_arraycopy"}, 178 {"StubRoutines::_jlong_disjoint_arraycopy", "_aot_stub_routines_jlong_disjoint_arraycopy"}, 179 {"StubRoutines::_oop_disjoint_arraycopy", "_aot_stub_routines_oop_disjoint_arraycopy"}, 180 {"StubRoutines::_oop_disjoint_arraycopy_uninit", "_aot_stub_routines_oop_disjoint_arraycopy_uninit"}, 181 182 {"StubRoutines::_arrayof_jbyte_arraycopy", "_aot_stub_routines_arrayof_jbyte_arraycopy"}, 183 {"StubRoutines::_arrayof_jshort_arraycopy", "_aot_stub_routines_arrayof_jshort_arraycopy"}, 184 {"StubRoutines::_arrayof_jint_arraycopy", "_aot_stub_routines_arrayof_jint_arraycopy"}, 185 {"StubRoutines::_arrayof_jlong_arraycopy", "_aot_stub_routines_arrayof_jlong_arraycopy"}, 186 {"StubRoutines::_arrayof_oop_arraycopy", "_aot_stub_routines_arrayof_oop_arraycopy"}, 187 {"StubRoutines::_arrayof_oop_arraycopy_uninit", "_aot_stub_routines_arrayof_oop_arraycopy_uninit"}, 188 189 {"StubRoutines::_arrayof_jbyte_disjoint_arraycopy", "_aot_stub_routines_arrayof_jbyte_disjoint_arraycopy"}, 190 {"StubRoutines::_arrayof_jshort_disjoint_arraycopy", "_aot_stub_routines_arrayof_jshort_disjoint_arraycopy"}, 191 {"StubRoutines::_arrayof_jint_disjoint_arraycopy", "_aot_stub_routines_arrayof_jint_disjoint_arraycopy"}, 192 {"StubRoutines::_arrayof_jlong_disjoint_arraycopy", "_aot_stub_routines_arrayof_jlong_disjoint_arraycopy"}, 193 {"StubRoutines::_arrayof_oop_disjoint_arraycopy", "_aot_stub_routines_arrayof_oop_disjoint_arraycopy"}, 194 {"StubRoutines::_arrayof_oop_disjoint_arraycopy_uninit", "_aot_stub_routines_arrayof_oop_disjoint_arraycopy_uninit"}, 195 196 {"StubRoutines::_unsafe_arraycopy", "_aot_stub_routines_unsafe_arraycopy"}, 197 198 {"StubRoutines::_checkcast_arraycopy", "_aot_stub_routines_checkcast_arraycopy"}, 199 200 {"StubRoutines::_generic_arraycopy", "_aot_stub_routines_generic_arraycopy"}, 201 202 {"StubRoutines::_aescrypt_encryptBlock", "_aot_stub_routines_aescrypt_encryptBlock"}, 203 {"StubRoutines::_aescrypt_decryptBlock", "_aot_stub_routines_aescrypt_decryptBlock"}, 204 {"StubRoutines::_cipherBlockChaining_encryptAESCrypt", "_aot_stub_routines_cipherBlockChaining_encryptAESCrypt"}, 205 {"StubRoutines::_cipherBlockChaining_decryptAESCrypt", "_aot_stub_routines_cipherBlockChaining_decryptAESCrypt"}, 206 {"StubRoutines::_updateBytesCRC32", "_aot_stub_routines_update_bytes_crc32"}, 207 {"StubRoutines::_crc_table_adr", "_aot_stub_routines_crc_table_adr"}, 208 209 {"StubRoutines::_sha1_implCompress", "_aot_stub_routines_sha1_implCompress" }, 210 {"StubRoutines::_sha1_implCompressMB", "_aot_stub_routines_sha1_implCompressMB" }, 211 {"StubRoutines::_sha256_implCompress", "_aot_stub_routines_sha256_implCompress" }, 212 {"StubRoutines::_sha256_implCompressMB", "_aot_stub_routines_sha256_implCompressMB" }, 213 {"StubRoutines::_sha512_implCompress", "_aot_stub_routines_sha512_implCompress" }, 214 {"StubRoutines::_sha512_implCompressMB", "_aot_stub_routines_sha512_implCompressMB" }, 215 {"StubRoutines::_multiplyToLen", "_aot_stub_routines_multiplyToLen" }, 216 217 {"StubRoutines::_counterMode_AESCrypt", "_aot_stub_routines_counterMode_AESCrypt" }, 218 {"StubRoutines::_ghash_processBlocks", "_aot_stub_routines_ghash_processBlocks" }, 219 {"StubRoutines::_base64_encodeBlock", "_aot_stub_routines_base64_encodeBlock" }, 220 {"StubRoutines::_crc32c_table_addr", "_aot_stub_routines_crc32c_table_addr" }, 221 {"StubRoutines::_updateBytesCRC32C", "_aot_stub_routines_updateBytesCRC32C" }, 222 {"StubRoutines::_updateBytesAdler32", "_aot_stub_routines_updateBytesAdler32" }, 223 {"StubRoutines::_squareToLen", "_aot_stub_routines_squareToLen" }, 224 {"StubRoutines::_mulAdd", "_aot_stub_routines_mulAdd" }, 225 {"StubRoutines::_montgomeryMultiply", "_aot_stub_routines_montgomeryMultiply" }, 226 {"StubRoutines::_montgomerySquare", "_aot_stub_routines_montgomerySquare" }, 227 {"StubRoutines::_vectorizedMismatch", "_aot_stub_routines_vectorizedMismatch" }, 228 229 {"StubRoutines::_throw_delayed_StackOverflowError_entry", "_aot_stub_routines_throw_delayed_StackOverflowError_entry" }, 230 231 232 {"os::javaTimeMillis", "_aot_os_javaTimeMillis"}, 233 {"os::javaTimeNanos", "_aot_os_javaTimeNanos"}, 234 235 {"JVMCIRuntime::monitorenter", "_aot_jvmci_runtime_monitorenter"}, 236 {"JVMCIRuntime::monitorexit", "_aot_jvmci_runtime_monitorexit"}, 237 {"JVMCIRuntime::object_notify", "_aot_object_notify"}, 238 {"JVMCIRuntime::object_notifyAll", "_aot_object_notifyAll"}, 239 {"JVMCIRuntime::log_object", "_aot_jvmci_runtime_log_object"}, 240 {"JVMCIRuntime::log_printf", "_aot_jvmci_runtime_log_printf"}, 241 {"JVMCIRuntime::vm_message", "_aot_jvmci_runtime_vm_message"}, 242 {"JVMCIRuntime::new_instance", "_aot_jvmci_runtime_new_instance"}, 243 {"JVMCIRuntime::log_primitive", "_aot_jvmci_runtime_log_primitive"}, 244 {"JVMCIRuntime::new_multi_array", "_aot_jvmci_runtime_new_multi_array"}, 245 {"JVMCIRuntime::validate_object", "_aot_jvmci_runtime_validate_object"}, 246 {"JVMCIRuntime::dynamic_new_array", "_aot_jvmci_runtime_dynamic_new_array"}, 247 {"JVMCIRuntime::write_barrier_pre", "_aot_jvmci_runtime_write_barrier_pre"}, 248 {"JVMCIRuntime::identity_hash_code", "_aot_jvmci_runtime_identity_hash_code"}, 249 {"JVMCIRuntime::write_barrier_post", "_aot_jvmci_runtime_write_barrier_post"}, 250 {"JVMCIRuntime::dynamic_new_instance", "_aot_jvmci_runtime_dynamic_new_instance"}, 251 {"JVMCIRuntime::thread_is_interrupted", "_aot_jvmci_runtime_thread_is_interrupted"}, 252 {"JVMCIRuntime::exception_handler_for_pc", "_aot_jvmci_runtime_exception_handler_for_pc"}, 253 {"JVMCIRuntime::test_deoptimize_call_int", "_aot_jvmci_runtime_test_deoptimize_call_int"}, 254 255 {"JVMCIRuntime::throw_and_post_jvmti_exception", "_aot_jvmci_runtime_throw_and_post_jvmti_exception"}, 256 {"JVMCIRuntime::throw_klass_external_name_exception", "_aot_jvmci_runtime_throw_klass_external_name_exception"}, 257 {"JVMCIRuntime::throw_class_cast_exception", "_aot_jvmci_runtime_throw_class_cast_exception"}, 258 259 {"JVMCIRuntime::vm_error", "_aot_jvmci_runtime_vm_error"}, 260 {"JVMCIRuntime::new_array", "_aot_jvmci_runtime_new_array"} 261 }; 262 //@formatter:on 263 264 static { 265 for (String[] entry : map) { 266 functionNamesToAOTSymbols.put(entry[0], entry[1]); 267 } 268 } 269 270 /** 271 * Allocates a {@code BinaryContainer} object whose content will be generated in a file with the 272 * prefix {@code prefix}. It also initializes internal code container, symbol table and 273 * relocation tables. 274 * 275 * @param graalOptions 276 */ 277 public BinaryContainer(OptionValues graalOptions, GraalHotSpotVMConfig graalHotSpotVMConfig, GraphBuilderConfiguration graphBuilderConfig, int gc, String jvmVersion) { 278 this.graalOptions = graalOptions; 279 280 this.codeSegmentSize = graalHotSpotVMConfig.codeSegmentSize; 281 if (codeSegmentSize < 1 || codeSegmentSize > 1024) { 282 throw new InternalError("codeSegmentSize is not in range [1, 1024] bytes: (" + codeSegmentSize + "), update JPECoffRelocObject"); 283 } 284 if ((codeSegmentSize & (codeSegmentSize - 1)) != 0) { 285 throw new InternalError("codeSegmentSize is not power of 2: (" + codeSegmentSize + "), update JPECoffRelocObject"); 286 } 287 288 this.codeEntryAlignment = graalHotSpotVMConfig.codeEntryAlignment; 289 290 this.threadLocalHandshakes = graalHotSpotVMConfig.threadLocalHandshakes; 291 292 // Section unique name is limited to 8 characters due to limitation on Windows. 293 // Name could be longer but only first 8 characters are stored on Windows. 294 295 // read only, code 296 codeContainer = new CodeContainer(".text", this); 297 298 // read only, info 299 headerContainer = new HeaderContainer(jvmVersion, new ReadOnlyDataContainer(".header", this)); 300 configContainer = new ReadOnlyDataContainer(".config", this); 301 metaspaceNamesContainer = new ReadOnlyDataContainer(".meta.names", this); 302 methodsOffsetsContainer = new ReadOnlyDataContainer(".meth.offsets", this); 303 klassesOffsetsContainer = new ReadOnlyDataContainer(".kls.offsets", this); 304 klassesDependenciesContainer = new ReadOnlyDataContainer(".kls.dependencies", this); 305 306 stubsOffsetsContainer = new ReadOnlyDataContainer(".stubs.offsets", this); 307 codeSegmentsContainer = new ReadOnlyDataContainer(".code.segments", this); 308 constantDataContainer = new ReadOnlyDataContainer(".meth.constdata", this); 309 methodMetadataContainer = new ReadOnlyDataContainer(".meth.metadata", this); 310 311 // writable sections 312 oopGotContainer = new ByteContainer(".oop.got", this); 313 klassesGotContainer = new ByteContainer(".kls.got", this); 314 countersGotContainer = new ByteContainer(".cnt.got", this); 315 metadataGotContainer = new ByteContainer(".meta.got", this); 316 methodStateContainer = new ByteContainer(".meth.state", this); 317 extLinkageGOTContainer = new ByteContainer(".got.linkage", this); 318 319 addGlobalSymbols(); 320 321 recordConfiguration(graalHotSpotVMConfig, graphBuilderConfig, gc); 322 } 323 324 private void recordConfiguration(GraalHotSpotVMConfig graalHotSpotVMConfig, GraphBuilderConfiguration graphBuilderConfig, int gc) { 325 // @Checkstyle: stop 326 // @formatter:off 327 boolean[] booleanFlags = { graalHotSpotVMConfig.cAssertions, // Debug VM 328 graalHotSpotVMConfig.useCompressedOops, 329 graalHotSpotVMConfig.useCompressedClassPointers, 330 graalHotSpotVMConfig.compactFields, 331 graalHotSpotVMConfig.useTLAB, 332 graalHotSpotVMConfig.useBiasedLocking, 333 TieredAOT.getValue(graalOptions), 334 graalHotSpotVMConfig.enableContended, 335 graalHotSpotVMConfig.restrictContended, 336 graphBuilderConfig.omitAssertions(), 337 graalHotSpotVMConfig.threadLocalHandshakes 338 }; 339 340 int[] intFlags = { graalHotSpotVMConfig.getOopEncoding().getShift(), 341 graalHotSpotVMConfig.getKlassEncoding().getShift(), 342 graalHotSpotVMConfig.contendedPaddingWidth, 343 graalHotSpotVMConfig.fieldsAllocationStyle, 344 1 << graalHotSpotVMConfig.logMinObjAlignment(), 345 graalHotSpotVMConfig.codeSegmentSize, 346 gc 347 }; 348 // @formatter:on 349 // @Checkstyle: resume 350 351 byte[] booleanFlagsAsBytes = flagsToByteArray(booleanFlags); 352 int size0 = configContainer.getByteStreamSize(); 353 354 // @formatter:off 355 int computedSize = booleanFlagsAsBytes.length * Byte.BYTES + // size of boolean flags 356 intFlags.length * Integer.BYTES + // size of int flags 357 Integer.BYTES; // size of the "computedSize" 358 359 configContainer.appendInt(computedSize). 360 appendInts(intFlags). 361 appendBytes(booleanFlagsAsBytes); 362 // @formatter:on 363 364 int size = configContainer.getByteStreamSize() - size0; 365 assert size == computedSize; 366 } 367 368 private static byte[] flagsToByteArray(boolean[] flags) { 369 byte[] byteArray = new byte[flags.length]; 370 for (int i = 0; i < flags.length; ++i) { 371 byteArray[i] = boolToByte(flags[i]); 372 } 373 return byteArray; 374 } 375 376 private static byte boolToByte(boolean flag) { 377 return (byte) (flag ? 1 : 0); 378 } 379 380 /** 381 * Free some memory. 382 */ 383 public void freeMemory() { 384 offsetStringTable.clear(); 385 metaspaceNames.clear(); 386 } 387 388 /* 389 * Global symbol names in generated DSO corresponding to VM's symbols. VM needs to look up this 390 * symbol in DSO and link it with VM's corresponding symbol: store VM's symbol address or value 391 * in the named GOT cell. 392 */ 393 394 public static String getCardTableAddressSymbolName() { 395 return "_aot_card_table_address"; 396 } 397 398 public static String getHeapTopAddressSymbolName() { 399 return "_aot_heap_top_address"; 400 } 401 402 public static String getHeapEndAddressSymbolName() { 403 return "_aot_heap_end_address"; 404 } 405 406 public static String getCrcTableAddressSymbolName() { 407 return "_aot_stub_routines_crc_table_adr"; 408 } 409 410 public static String getPollingPageSymbolName() { 411 return "_aot_polling_page"; 412 } 413 414 public static String getResolveStaticEntrySymbolName() { 415 return "_resolve_static_entry"; 416 } 417 418 public static String getResolveVirtualEntrySymbolName() { 419 return "_resolve_virtual_entry"; 420 } 421 422 public static String getResolveOptVirtualEntrySymbolName() { 423 return "_resolve_opt_virtual_entry"; 424 } 425 426 public static String getNarrowKlassBaseAddressSymbolName() { 427 return "_aot_narrow_klass_base_address"; 428 } 429 430 public static String getNarrowOopBaseAddressSymbolName() { 431 return "_aot_narrow_oop_base_address"; 432 } 433 434 public static String getLogOfHeapRegionGrainBytesSymbolName() { 435 return "_aot_log_of_heap_region_grain_bytes"; 436 } 437 438 public static String getInlineContiguousAllocationSupportedSymbolName() { 439 return "_aot_inline_contiguous_allocation_supported"; 440 } 441 442 public int getCodeSegmentSize() { 443 return codeSegmentSize; 444 } 445 446 public int getCodeEntryAlignment() { 447 return codeEntryAlignment; 448 } 449 450 public boolean getThreadLocalHandshakes() { 451 return threadLocalHandshakes; 452 } 453 454 /** 455 * Gets the global AOT symbol associated with the function name. 456 * 457 * @param functionName function name 458 * @return AOT symbol for the given function name, or null if there is no mapping. 459 */ 460 public static String getAOTSymbolForVMFunctionName(String functionName) { 461 return functionNamesToAOTSymbols.get(functionName); 462 } 463 464 private void addGlobalSymbols() { 465 // Create global symbols for all containers. 466 createContainerSymbol(codeContainer); 467 createContainerSymbol(configContainer); 468 createContainerSymbol(methodsOffsetsContainer); 469 createContainerSymbol(klassesOffsetsContainer); 470 createContainerSymbol(klassesDependenciesContainer); 471 createContainerSymbol(klassesGotContainer); 472 createContainerSymbol(countersGotContainer); 473 createContainerSymbol(metadataGotContainer); 474 createContainerSymbol(methodStateContainer); 475 createContainerSymbol(oopGotContainer); 476 createContainerSymbol(metaspaceNamesContainer); 477 createContainerSymbol(methodMetadataContainer); 478 createContainerSymbol(stubsOffsetsContainer); 479 createContainerSymbol(headerContainer.getContainer()); 480 createContainerSymbol(codeSegmentsContainer); 481 482 createGotSymbol(getResolveStaticEntrySymbolName()); 483 createGotSymbol(getResolveVirtualEntrySymbolName()); 484 createGotSymbol(getResolveOptVirtualEntrySymbolName()); 485 createGotSymbol(getCardTableAddressSymbolName()); 486 createGotSymbol(getHeapTopAddressSymbolName()); 487 createGotSymbol(getHeapEndAddressSymbolName()); 488 createGotSymbol(getNarrowKlassBaseAddressSymbolName()); 489 createGotSymbol(getNarrowOopBaseAddressSymbolName()); 490 createGotSymbol(getPollingPageSymbolName()); 491 createGotSymbol(getLogOfHeapRegionGrainBytesSymbolName()); 492 createGotSymbol(getInlineContiguousAllocationSupportedSymbolName()); 493 494 for (HashMap.Entry<String, String> entry : functionNamesToAOTSymbols.entrySet()) { 495 createGotSymbol(entry.getValue()); 496 } 497 } 498 499 /** 500 * Creates a global symbol of the form {@code "A" + container name}. Note, linker on Windows 501 * does not allow names which start with '.' 502 * 503 * @param container container to create a symbol for 504 */ 505 private static void createContainerSymbol(ByteContainer container) { 506 container.createSymbol(0, Kind.OBJECT, Binding.GLOBAL, 0, "A" + container.getContainerName()); 507 } 508 509 /** 510 * Creates a global GOT symbol of the form {@code "got." + name}. 511 * 512 * @param name name for the GOT symbol 513 */ 514 private void createGotSymbol(String name) { 515 String s = "got." + name; 516 Symbol gotSymbol = extLinkageGOTContainer.createGotSymbol(s); 517 extLinkageGOTContainer.createSymbol(gotSymbol.getOffset(), Kind.OBJECT, Binding.GLOBAL, 8, name); 518 } 519 520 /** 521 * Create a platform-specific binary file representing the content of the 522 * {@code BinaryContainer} object. 523 * 524 * This method is called after creating and performing any necessary changes to the contents of 525 * code stream, symbol tables and relocation tables is completely finalized 526 * 527 * @param outputFileName name of output file 528 * 529 * @throws IOException in case of file creation failure 530 */ 531 public void createBinary(String outputFileName) throws IOException { 532 String osName = System.getProperty("os.name"); 533 switch (osName) { 534 case "Linux": 535 case "SunOS": 536 JELFRelocObject elfobj = JELFRelocObject.newInstance(this, outputFileName); 537 elfobj.createELFRelocObject(relocationTable, symbolTable.values()); 538 break; 539 case "Mac OS X": 540 JMachORelocObject machobj = new JMachORelocObject(this, outputFileName); 541 machobj.createMachORelocObject(relocationTable, symbolTable.values()); 542 break; 543 default: 544 if (osName.startsWith("Windows")) { 545 JPECoffRelocObject pecoffobj = new JPECoffRelocObject(this, outputFileName); 546 pecoffobj.createPECoffRelocObject(relocationTable, symbolTable.values()); 547 break; 548 } else { 549 throw new InternalError("Unsupported platform: " + osName); 550 } 551 } 552 } 553 554 /** 555 * Add symbol to the symbol table. If the existing symbol is undefined and the specified symbol 556 * is not undefined, replace the existing symbol information with that specified. 557 * 558 * @param symInfo symbol information to be added 559 */ 560 @Override 561 public void addSymbol(Symbol symInfo) { 562 if (symInfo.getName().startsWith("got.") && !(symInfo instanceof GotSymbol)) { 563 throw new InternalError("adding got. without being GotSymbol"); 564 } 565 if (symbolTable.containsKey(symInfo.getName())) { 566 throw new InternalError("Symbol: " + symInfo.getName() + " already exists in SymbolTable"); 567 } else { 568 // System.out.println("# Symbol [" + name + "] [" + symInfo.getValue() + "] [" + 569 // symInfo.getSection().getContainerName() + "] [" + symInfo.getSize() + "]"); 570 symbolTable.put(symInfo.getName(), symInfo); 571 } 572 } 573 574 public boolean addStringOffset(String name, Integer offset) { 575 offsetStringTable.put(name, offset); 576 return true; 577 } 578 579 /** 580 * Add relocation entry for {@code symName}. Multiple relocation entries for a given symbol may 581 * exist. 582 * 583 * @param info relocation information to be added 584 */ 585 public void addRelocation(Relocation info) { 586 // System.out.println("# Relocation [" + info.getSymbol() + "] [" + info.getOffset() + "] [" 587 // + 588 // info.getSection().getContainerName() + "] [" + info.getSymbol().getName() + "] [" + 589 // info.getSymbol().getOffset() + " @ " + info.getSymbol().getSection().getContainerName() + 590 // "]"); 591 if (relocationTable.containsKey(info.getSymbol())) { 592 relocationTable.get(info.getSymbol()).add(info); 593 } else if (uniqueRelocationTable.containsKey(info.getSymbol())) { 594 // promote 595 ArrayList<Relocation> list = new ArrayList<>(2); 596 list.add(uniqueRelocationTable.get(info.getSymbol())); 597 list.add(info); 598 relocationTable.put(info.getSymbol(), list); 599 uniqueRelocationTable.remove(info.getSymbol()); 600 } else { 601 uniqueRelocationTable.put(info.getSymbol(), info); 602 } 603 } 604 605 /** 606 * Get symbol with name {@code symName}. 607 * 608 * @param symName name of symbol for which symbol table information is being queried 609 * @return success or failure of insertion operation 610 */ 611 @Override 612 public Symbol getSymbol(String symName) { 613 return symbolTable.get(symName); 614 } 615 616 @Override 617 public Symbol createSymbol(int offset, Kind kind, Binding binding, int size, String name) { 618 if (kind != Kind.NATIVE_FUNCTION) { 619 throw new UnsupportedOperationException("Must be external functions: " + name); 620 } 621 Symbol symbol = new Symbol(offset, kind, binding, null, size, name); 622 addSymbol(symbol); 623 return symbol; 624 } 625 626 /** 627 * Get offset in got section with name {@code symName}. 628 * 629 * @param name for which String table information is being queried 630 * @return success or failure of insertion operation 631 */ 632 public Integer getStringOffset(String name) { 633 return offsetStringTable.get(name); 634 } 635 636 /** 637 * Insert {@code targetCode} to code stream with {@code size} at {@code offset}. 638 * 639 * @param targetCode byte array of native code 640 * @param offset offset at which {@code targetCode} is to be inserted 641 * @param size size of {@code targetCode} 642 */ 643 private static void appendBytes(ByteContainer byteContainer, byte[] targetCode, int offset, int size) { 644 byteContainer.appendBytes(targetCode, offset, size); 645 } 646 647 public void appendCodeBytes(byte[] targetCode, int offset, int size) { 648 appendBytes(codeContainer, targetCode, offset, size); 649 } 650 651 public void appendIntToCode(int value) { 652 codeContainer.appendInt(value); 653 } 654 655 public int appendExtLinkageGotBytes(byte[] bytes, int offset, int size) { 656 int startOffset = extLinkageGOTContainer.getByteStreamSize(); 657 appendBytes(extLinkageGOTContainer, bytes, offset, size); 658 return startOffset; 659 } 660 661 public void addMetadataGotEntry(int offset) { 662 metadataGotContainer.appendLong(offset); 663 } 664 665 public int addMetaspaceName(String name) { 666 Integer value = metaspaceNames.get(name); 667 if (value != null) { 668 return value.intValue(); 669 } 670 // Get the current length of the stubsNameContainer 671 // align on 8-byte boundary 672 int nameOffset = alignUp(metaspaceNamesContainer, 8); 673 674 try { 675 // Add the name of the symbol to the .stubs.names section 676 // Modify them to sequence of utf8 strings with length: 677 // "<u2_size>Ljava/lang/ThreadGroup;<u2_size>addUnstarted<u2_size>()V" 678 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 679 DataOutputStream out = new DataOutputStream(bout); 680 int len = name.length(); 681 if (name.startsWith("Stub")) { // Stub 682 out.writeUTF(name); 683 } else { // Method or Klass 684 int parenthesesIndex = name.lastIndexOf('(', len - 1); 685 if (parenthesesIndex > 0) { // Method name 686 int dotIndex = name.lastIndexOf('.', parenthesesIndex - 1); 687 assert dotIndex > 0 : "method's full name should have '.' : " + name; 688 String klassName = name.substring(0, dotIndex); 689 out.writeUTF(klassName); 690 String methodName = name.substring(dotIndex + 1, parenthesesIndex); 691 out.writeUTF(methodName); 692 String signature = name.substring(parenthesesIndex, len); 693 out.writeUTF(signature); 694 } else { 695 out.writeUTF(name); // Klass 696 } 697 } 698 out.writeShort(0); // Terminate by 0. 699 byte[] b = bout.toByteArray(); 700 metaspaceNamesContainer.appendBytes(b, 0, b.length); 701 702 metaspaceNames.put(name, nameOffset); 703 return nameOffset; 704 } catch (IOException e) { 705 throw new InternalError("Failed to append bytes to stubs sections", e); 706 } 707 } 708 709 /** 710 * Add oop symbol by as follows. Extend the oop.got section with another slot for the VM to 711 * patch. 712 * 713 * @param oopName name of the oop symbol 714 */ 715 public Integer addOopSymbol(String oopName) { 716 Integer oopGotOffset = getStringOffset(oopName); 717 if (oopGotOffset != null) { 718 return oopGotOffset; 719 } 720 return newOopSymbol(oopName); 721 } 722 723 private Integer newOopSymbol(String oopName) { 724 // Reference to String resolution (ldc). 725 int offset = oopGotContainer.getByteStreamSize(); 726 String gotName = "got.ldc." + offset; 727 Symbol relocationSymbol = oopGotContainer.createGotSymbol(gotName); 728 729 if (offset != relocationSymbol.getOffset()) { 730 throw new InternalError("offset must equal! (" + offset + " vs " + relocationSymbol.getOffset()); 731 } 732 733 addStringOffset(oopName, relocationSymbol.getOffset()); 734 return relocationSymbol.getOffset(); 735 } 736 737 public int addCountersSymbol(String metaspaceName) { 738 String gotName = "got." + metaspaceName; 739 Symbol relocationSymbol = getGotSymbol(gotName); 740 int metaspaceOffset = -1; 741 if (relocationSymbol == null) { 742 // Add slots when asked in the .metaspace.got section: 743 countersGotContainer.createGotSymbol(gotName); 744 } 745 return metaspaceOffset; 746 } 747 748 public Symbol getGotSymbol(String name) { 749 assert name.startsWith("got."); 750 return symbolTable.get(name); 751 } 752 753 /** 754 * Add klass symbol by as follows. - Adding the symbol name to the metaspace.names section - Add 755 * the offset of the name in metaspace.names to metaspace.offsets - Extend the klasses.got 756 * section with another slot for the VM to patch 757 * 758 * @param klassName name of the metaspace symbol 759 * @return the got offset in the klasses.got of the metaspace symbol 760 */ 761 public int addTwoSlotKlassSymbol(String klassName) { 762 String gotName = "got." + klassName; 763 Symbol previous = getGotSymbol(gotName); 764 assert previous == null : "should be called only once for: " + klassName; 765 // Add slots when asked in the .metaspace.got section: 766 // First slot 767 String gotInitName = "got.init." + klassName; 768 GotSymbol slot1Symbol = klassesGotContainer.createGotSymbol(gotInitName); 769 GotSymbol slot2Symbol = klassesGotContainer.createGotSymbol(gotName); 770 771 slot1Symbol.getIndex(); // check alignment and ignore result 772 // Get the index (offset/8) to the got in the .metaspace.got section 773 return slot2Symbol.getIndex(); 774 } 775 776 public static int addMethodsCount(int count, ReadOnlyDataContainer container) { 777 return appendInt(count, container); 778 } 779 780 private static int appendInt(int count, ReadOnlyDataContainer container) { 781 int offset = container.getByteStreamSize(); 782 container.appendInt(count); 783 return offset; 784 } 785 786 /** 787 * Add constant data as follows. - Adding the data to the meth.constdata section 788 * 789 * @param data 790 * @param alignment 791 * @return the offset in the meth.constdata of the data 792 */ 793 public int addConstantData(byte[] data, int alignment) { 794 // Get the current length of the metaspaceNameContainer 795 int constantDataOffset = alignUp(constantDataContainer, alignment); 796 constantDataContainer.appendBytes(data, 0, data.length); 797 alignUp(constantDataContainer, alignment); // Post alignment 798 return constantDataOffset; 799 } 800 801 public static int alignUp(ByteContainer container, int alignment) { 802 if (Integer.bitCount(alignment) != 1) { 803 throw new IllegalArgumentException("Must be a power of 2"); 804 } 805 int offset = container.getByteStreamSize(); 806 int aligned = (offset + (alignment - 1)) & -alignment; 807 if (aligned < offset || (aligned & (alignment - 1)) != 0) { 808 throw new RuntimeException("Error aligning: " + offset + " -> " + aligned); 809 } 810 if (aligned != offset) { 811 int nullArraySz = aligned - offset; 812 byte[] nullArray = new byte[nullArraySz]; 813 container.appendBytes(nullArray, 0, nullArraySz); 814 offset = aligned; 815 } 816 return offset; 817 } 818 819 public void addCodeSegments(int start, int end) { 820 assert (start % codeSegmentSize) == 0 : "not aligned code"; 821 int currentOffset = codeSegmentsContainer.getByteStreamSize(); 822 int offset = start / codeSegmentSize; 823 int emptySize = offset - currentOffset; 824 // add empty segments if needed 825 if (emptySize > 0) { 826 byte[] emptyArray = new byte[emptySize]; 827 for (int i = 0; i < emptySize; i++) { 828 emptyArray[i] = (byte) 0xff; 829 } 830 appendBytes(codeSegmentsContainer, emptyArray, 0, emptySize); 831 } 832 int alignedEnd = (end + (codeSegmentSize - 1)) & -codeSegmentSize; 833 int segmentsCount = (alignedEnd / codeSegmentSize) - offset; 834 byte[] segments = new byte[segmentsCount]; 835 int idx = 0; 836 for (int i = 0; i < segmentsCount; i++) { 837 segments[i] = (byte) idx; 838 idx = (idx == 0xfe) ? 1 : (idx + 1); 839 } 840 appendBytes(codeSegmentsContainer, segments, 0, segmentsCount); 841 } 842 843 public ByteContainer getExtLinkageGOTContainer() { 844 return extLinkageGOTContainer; 845 } 846 847 public ReadOnlyDataContainer getMethodMetadataContainer() { 848 return methodMetadataContainer; 849 } 850 851 public ReadOnlyDataContainer getMetaspaceNamesContainer() { 852 return metaspaceNamesContainer; 853 } 854 855 public ReadOnlyDataContainer getMethodsOffsetsContainer() { 856 return methodsOffsetsContainer; 857 } 858 859 public ReadOnlyDataContainer getKlassesOffsetsContainer() { 860 return klassesOffsetsContainer; 861 } 862 863 public ReadOnlyDataContainer getKlassesDependenciesContainer() { 864 return klassesDependenciesContainer; 865 } 866 867 public ReadOnlyDataContainer getStubsOffsetsContainer() { 868 return stubsOffsetsContainer; 869 } 870 871 public ReadOnlyDataContainer getCodeSegmentsContainer() { 872 return codeSegmentsContainer; 873 } 874 875 public ReadOnlyDataContainer getConstantDataContainer() { 876 return constantDataContainer; 877 } 878 879 public ByteContainer getKlassesGotContainer() { 880 return klassesGotContainer; 881 } 882 883 public ByteContainer getCountersGotContainer() { 884 return countersGotContainer; 885 } 886 887 public ByteContainer getMetadataGotContainer() { 888 return metadataGotContainer; 889 } 890 891 public ByteContainer getMethodStateContainer() { 892 return methodStateContainer; 893 } 894 895 public ByteContainer getOopGotContainer() { 896 return oopGotContainer; 897 } 898 899 public CodeContainer getCodeContainer() { 900 return codeContainer; 901 } 902 903 public ReadOnlyDataContainer getConfigContainer() { 904 return configContainer; 905 } 906 907 public Map<Symbol, Relocation> getUniqueRelocationTable() { 908 return uniqueRelocationTable; 909 } 910 911 public HeaderContainer getHeaderContainer() { 912 return headerContainer; 913 } 914 915 }