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