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