1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 
  27 #if !defined(_WINDOWS) && !defined(__APPLE__)
  28 
  29 #include <string.h>
  30 #include <stdio.h>
  31 #include <limits.h>
  32 #include <new>
  33 
  34 #include "logging/log.hpp"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "utilities/decoder.hpp"
  38 #include "utilities/elfFile.hpp"
  39 #include "utilities/elfFuncDescTable.hpp"
  40 #include "utilities/elfStringTable.hpp"
  41 #include "utilities/elfSymbolTable.hpp"
  42 #include "utilities/ostream.hpp"
  43 
  44 // For test only, disable elf section cache and force to read from file directly.
  45 bool ElfFile::_do_not_cache_elf_section = false;
  46 
  47 ElfSection::ElfSection(FILE* fd, const Elf_Shdr& hdr) : _section_data(NULL) {
  48   _stat = load_section(fd, hdr);
  49 }
  50 
  51 ElfSection::~ElfSection() {
  52   if (_section_data != NULL) {
  53     os::free(_section_data);
  54   }
  55 }
  56 
  57 NullDecoder::decoder_status ElfSection::load_section(FILE* const fd, const Elf_Shdr& shdr) {
  58   memcpy((void*)&_section_hdr, (const void*)&shdr, sizeof(shdr));
  59 
  60   if (ElfFile::_do_not_cache_elf_section) {
  61     log_debug(decoder)("Elf section cache is disabled");
  62     return NullDecoder::no_error;
  63   }
  64 
  65   _section_data = os::malloc(shdr.sh_size, mtInternal);
  66   // No enough memory for caching. It is okay, we can try to read from
  67   // file instead.
  68   if (_section_data == NULL) return NullDecoder::no_error;
  69 
  70   MarkedFileReader mfd(fd);
  71   if (mfd.has_mark() &&
  72       mfd.set_position(shdr.sh_offset) &&
  73       mfd.read(_section_data, shdr.sh_size)) {
  74     return NullDecoder::no_error;
  75   } else {
  76     os::free(_section_data);
  77     _section_data = NULL;
  78     return NullDecoder::file_invalid;
  79   }
  80 }
  81 
  82 bool FileReader::read(void* buf, size_t size) {
  83   assert(buf != NULL, "no buffer");
  84   assert(size > 0, "no space");
  85   return fread(buf, size, 1, _fd) == 1;
  86 }
  87 
  88 int FileReader::read_buffer(void* buf, size_t size) {
  89   assert(buf != NULL, "no buffer");
  90   assert(size > 0, "no space");
  91   return fread(buf, 1, size, _fd);
  92 }
  93 
  94 bool FileReader::set_position(long offset) {
  95   return fseek(_fd, offset, SEEK_SET) == 0;
  96 }
  97 
  98 MarkedFileReader::MarkedFileReader(FILE* fd) : FileReader(fd) {
  99   _marked_pos = ftell(fd);
 100 }
 101 
 102 MarkedFileReader::~MarkedFileReader() {
 103   if (_marked_pos != -1) {
 104     set_position(_marked_pos);
 105   }
 106 }
 107 
 108 ElfFile::ElfFile(const char* filepath, bool load_debug_info) :
 109   _string_tables(NULL), _symbol_tables(NULL), _funcDesc_table(NULL),
 110   _next(NULL), _status(NullDecoder::no_error), _debuginfo(NULL),
 111   _shdr_string_table(NULL),  _file(NULL), _filepath(NULL) {
 112   memset(&_elfHdr, 0, sizeof(_elfHdr));
 113 
 114   int len = strlen(filepath) + 1;
 115   _filepath = (char*)os::malloc(len * sizeof(char), mtInternal);
 116   if (_filepath == NULL) {
 117     _status = NullDecoder::out_of_memory;
 118     return;
 119   }
 120   strcpy(_filepath, filepath);
 121 
 122   _status = parse_elf(filepath);
 123 
 124   // See if we should try to load external debug info
 125   if (_status == NullDecoder::no_debug_symbols && load_debug_info) {
 126     log_debug(decoder)("No debug symbols in %s, trying external debuginfo", _filepath);
 127     _debuginfo = load_debuginfo();
 128   }
 129 
 130   if (NullDecoder::is_error(_status)) {
 131     // Not be able to decode, cleanup
 132     cleanup_tables();
 133   } else {
 134     log_debug(decoder)("%s contains debug symbols", _filepath);
 135     // No longer need section header string table, which is not used for decoding
 136     if (_shdr_string_table != NULL) {
 137       delete _shdr_string_table;
 138       _shdr_string_table = NULL;
 139     }
 140   }
 141 }
 142 
 143 ElfFile::~ElfFile() {
 144   if (_shdr_string_table != NULL) {
 145     delete _shdr_string_table;
 146   }
 147 
 148   cleanup_tables();
 149 
 150   if (_file != NULL) {
 151     fclose(_file);
 152   }
 153 
 154   if (_filepath != NULL) {
 155     os::free((void*)_filepath);
 156   }
 157 
 158   if (_next != NULL) {
 159     delete _next;
 160   }
 161 }
 162 
 163 void ElfFile::cleanup_tables() {
 164   if (_string_tables != NULL) {
 165     delete _string_tables;
 166     _string_tables = NULL;
 167   }
 168 
 169   if (_symbol_tables != NULL) {
 170     delete _symbol_tables;
 171     _symbol_tables = NULL;
 172   }
 173 
 174   if (_funcDesc_table != NULL) {
 175     delete _funcDesc_table;
 176     _funcDesc_table = NULL;
 177   }
 178 }
 179 
 180 NullDecoder::decoder_status ElfFile::parse_elf(const char* filepath) {
 181   assert(filepath, "null file path");
 182 
 183   _file = fopen(filepath, "r");
 184   if (_file != NULL) {
 185     return load_tables();
 186   } else {
 187     return NullDecoder::file_not_found;
 188   }
 189 }
 190 
 191 //Check elf header to ensure the file is valid.
 192 bool ElfFile::is_elf_file(Elf_Ehdr& hdr) {
 193   return (ELFMAG0 == hdr.e_ident[EI_MAG0] &&
 194       ELFMAG1 == hdr.e_ident[EI_MAG1] &&
 195       ELFMAG2 == hdr.e_ident[EI_MAG2] &&
 196       ELFMAG3 == hdr.e_ident[EI_MAG3] &&
 197       ELFCLASSNONE != hdr.e_ident[EI_CLASS] &&
 198       ELFDATANONE != hdr.e_ident[EI_DATA]);
 199 }
 200 
 201 NullDecoder::decoder_status ElfFile::load_tables() {
 202   assert(_file, "file not open");
 203   assert(!NullDecoder::is_error(_status), "already in error");
 204 
 205   FileReader freader(fd());
 206   // read elf file header
 207   if (!freader.read(&_elfHdr, sizeof(_elfHdr))) {
 208     return NullDecoder::file_invalid;
 209   }
 210 
 211   // Check signature
 212   if (!is_elf_file(_elfHdr)) {
 213     return NullDecoder::file_invalid;
 214   }
 215 
 216   // test if the file contains debug symbols
 217   NullDecoder::decoder_status stat = NullDecoder::no_debug_symbols;
 218 
 219   // walk elf file's section headers, and load string tables
 220   Elf_Shdr shdr;
 221   if (!freader.set_position(_elfHdr.e_shoff)) {
 222     return NullDecoder::file_invalid;
 223   }
 224 
 225   for (int index = 0; index < _elfHdr.e_shnum; index ++) {
 226     if (!freader.read(&shdr, sizeof(shdr))) {
 227       return NullDecoder::file_invalid;
 228     }
 229 
 230     if (shdr.sh_type == SHT_STRTAB) {
 231       // string tables
 232       ElfStringTable* table = new (std::nothrow) ElfStringTable(fd(), shdr, index);
 233       if (table == NULL) {
 234         return NullDecoder::out_of_memory;
 235       }
 236       if (index == _elfHdr.e_shstrndx) {
 237         assert(_shdr_string_table == NULL, "Only set once");
 238         _shdr_string_table = table;
 239       } else {
 240         add_string_table(table);
 241       }
 242     } else if (shdr.sh_type == SHT_SYMTAB || shdr.sh_type == SHT_DYNSYM) {
 243       // symbol tables
 244       ElfSymbolTable* table = new (std::nothrow) ElfSymbolTable(fd(), shdr);
 245       if (table == NULL) {
 246         return NullDecoder::out_of_memory;
 247       }
 248       // see if we have debug symbols
 249       if (shdr.sh_type == SHT_SYMTAB) {
 250         stat = NullDecoder::no_error;
 251       }
 252       add_symbol_table(table);
 253     }
 254   }
 255 #if defined(PPC64) && !defined(ABI_ELFv2)
 256   // Now read the .opd section wich contains the PPC64 function descriptor table.
 257   // The .opd section is only available on PPC64 (see for example:
 258   // http://refspecs.linuxfoundation.org/LSB_3.1.1/LSB-Core-PPC64/LSB-Core-PPC64/specialsections.html)
 259   // so this code should do no harm on other platforms but because of performance reasons we only
 260   // execute it on PPC64 platforms.
 261   // Notice that we can only find the .opd section after we have successfully read in the string
 262   // tables in the previous loop, because we need to query the name of each section which is
 263   // contained in one of the string tables (i.e. the one with the index m_elfHdr.e_shstrndx).
 264 
 265   // Reset the file pointer
 266   int sect_index = section_by_name(".opd", shdr);
 267 
 268   if (sect_index == -1) {
 269     return NullDecoder::file_invalid;
 270   }
 271 
 272   _funcDesc_table = new (std::nothrow) ElfFuncDescTable(_file, shdr, sect_index);
 273   if (_funcDesc_table == NULL) {
 274       return NullDecoder::out_of_memory;
 275   }
 276 #endif
 277   return stat;
 278 }
 279 
 280 int ElfFile::section_by_name(const char* name, Elf_Shdr& hdr) {
 281   assert(name != NULL, "No section name");
 282   size_t len = strlen(name) + 1;
 283   ResourceMark rm;
 284   char* buf = NEW_RESOURCE_ARRAY(char, len);
 285   if (buf == NULL) {
 286     return -1;
 287   }
 288 
 289   assert(_shdr_string_table != NULL, "Section header string table should be loaded");
 290   ElfStringTable* const table = _shdr_string_table;
 291   MarkedFileReader mfd(fd());
 292   if (!mfd.has_mark() || !mfd.set_position(_elfHdr.e_shoff)) return -1;
 293 
 294   int sect_index = -1;
 295   for (int index = 0; index < _elfHdr.e_shnum; index ++) {
 296     if (!mfd.read((void*)&hdr, sizeof(hdr))) {
 297       break;
 298     }
 299     if (table->string_at(hdr.sh_name, buf, len)) {
 300       if (strncmp(buf, name, len) == 0) {
 301         sect_index = index;
 302         break;
 303       }
 304     }
 305   }
 306   return sect_index;
 307 }
 308 
 309 bool ElfFile::decode(address addr, char* buf, int buflen, int* offset) {
 310   if (_debuginfo != NULL) {
 311     return _debuginfo->decode(addr, buf, buflen, offset);
 312   } else {
 313     return decode_impl(addr, buf, buflen, offset);
 314   }
 315 }
 316 
 317 bool ElfFile::decode_impl(address addr, char* buf, int buflen, int* offset) {
 318   // something already went wrong, just give up
 319   if (NullDecoder::is_error(_status)) {
 320     return false;
 321   }
 322 
 323   int string_table_index;
 324   int pos_in_string_table;
 325   int off = INT_MAX;
 326   bool found_symbol = false;
 327   ElfSymbolTable* symbol_table = _symbol_tables;
 328 
 329   while (symbol_table != NULL) {
 330     if (symbol_table->lookup(addr, &string_table_index, &pos_in_string_table, &off, _funcDesc_table)) {
 331       found_symbol = true;
 332       break;
 333     }
 334     symbol_table = symbol_table->next();
 335   }
 336   if (!found_symbol) {
 337     return false;
 338   }
 339 
 340   ElfStringTable* string_table = get_string_table(string_table_index);
 341 
 342   if (string_table == NULL) {
 343     _status = NullDecoder::file_invalid;
 344     return false;
 345   }
 346   if (offset) *offset = off;
 347 
 348   return string_table->string_at(pos_in_string_table, buf, buflen);
 349 }
 350 
 351 void ElfFile::add_symbol_table(ElfSymbolTable* table) {
 352   if (_symbol_tables == NULL) {
 353     _symbol_tables = table;
 354   } else {
 355     table->set_next(_symbol_tables);
 356     _symbol_tables = table;
 357   }
 358 }
 359 
 360 void ElfFile::add_string_table(ElfStringTable* table) {
 361   if (_string_tables == NULL) {
 362     _string_tables = table;
 363   } else {
 364     table->set_next(_string_tables);
 365     _string_tables = table;
 366   }
 367 }
 368 
 369 ElfStringTable* ElfFile::get_string_table(int index) {
 370   ElfStringTable* p = _string_tables;
 371   while (p != NULL) {
 372     if (p->index() == index) return p;
 373     p = p->next();
 374   }
 375   return NULL;
 376 }
 377 
 378 #endif // !_WINDOWS && !__APPLE__