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