Home | History | Annotate | Download | only in linker
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  * All rights reserved.
      4  *
      5  * Redistribution and use in source and binary forms, with or without
      6  * modification, are permitted provided that the following conditions
      7  * are met:
      8  *  * Redistributions of source code must retain the above copyright
      9  *    notice, this list of conditions and the following disclaimer.
     10  *  * Redistributions in binary form must reproduce the above copyright
     11  *    notice, this list of conditions and the following disclaimer in
     12  *    the documentation and/or other materials provided with the
     13  *    distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
     19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
     22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
     25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     26  * SUCH DAMAGE.
     27  */
     28 
     29 #if !defined(__LP64__) && __mips_isa_rev >= 5
     30 #include <sys/prctl.h>
     31 #endif
     32 
     33 #include "linker.h"
     34 #include "linker_debug.h"
     35 #include "linker_phdr.h"
     36 #include "linker_relocs.h"
     37 #include "linker_reloc_iterators.h"
     38 #include "linker_sleb128.h"
     39 
     40 template bool soinfo::relocate<plain_reloc_iterator>(const VersionTracker& version_tracker,
     41                                                      plain_reloc_iterator&& rel_iterator,
     42                                                      const soinfo_list_t& global_group,
     43                                                      const soinfo_list_t& local_group);
     44 
     45 template bool soinfo::relocate<packed_reloc_iterator<sleb128_decoder>>(
     46     const VersionTracker& version_tracker,
     47     packed_reloc_iterator<sleb128_decoder>&& rel_iterator,
     48     const soinfo_list_t& global_group,
     49     const soinfo_list_t& local_group);
     50 
     51 template <typename ElfRelIteratorT>
     52 bool soinfo::relocate(const VersionTracker& version_tracker,
     53                       ElfRelIteratorT&& rel_iterator,
     54                       const soinfo_list_t& global_group,
     55                       const soinfo_list_t& local_group) {
     56   for (size_t idx = 0; rel_iterator.has_next(); ++idx) {
     57     const auto rel = rel_iterator.next();
     58 
     59     if (rel == nullptr) {
     60       return false;
     61     }
     62 
     63     ElfW(Word) type = ELFW(R_TYPE)(rel->r_info);
     64     ElfW(Word) sym = ELFW(R_SYM)(rel->r_info);
     65 
     66     ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
     67     ElfW(Addr) sym_addr = 0;
     68     const char* sym_name = nullptr;
     69 
     70     DEBUG("Processing \"%s\" relocation at index %zd", get_realpath(), idx);
     71     if (type == R_GENERIC_NONE) {
     72       continue;
     73     }
     74 
     75     const ElfW(Sym)* s = nullptr;
     76     soinfo* lsi = nullptr;
     77 
     78     if (sym != 0) {
     79       sym_name = get_string(symtab_[sym].st_name);
     80       const version_info* vi = nullptr;
     81 
     82       if (!lookup_version_info(version_tracker, sym, sym_name, &vi)) {
     83         return false;
     84       }
     85 
     86       if (!soinfo_do_lookup(this, sym_name, vi, &lsi, global_group, local_group, &s)) {
     87         return false;
     88       }
     89 
     90       if (s == nullptr) {
     91         // mips does not support relocation with weak-undefined symbols
     92         DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...",
     93                sym_name, get_realpath());
     94         return false;
     95       } else {
     96         // We got a definition.
     97         sym_addr = lsi->resolve_symbol_address(s);
     98       }
     99       count_relocation(kRelocSymbol);
    100     }
    101 
    102     switch (type) {
    103       case R_MIPS_REL32:
    104 #if defined(__LP64__)
    105         // MIPS Elf64_Rel entries contain compound relocations
    106         // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case
    107         if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 ||
    108             ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) {
    109           DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)",
    110                  type, static_cast<unsigned>(ELF64_R_TYPE2(rel->r_info)),
    111                  static_cast<unsigned>(ELF64_R_TYPE3(rel->r_info)), rel, idx);
    112           return false;
    113         }
    114 #endif
    115         count_relocation(s == nullptr ? kRelocAbsolute : kRelocRelative);
    116         MARK(rel->r_offset);
    117         TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
    118                    static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
    119         if (s != nullptr) {
    120           *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
    121         } else {
    122           *reinterpret_cast<ElfW(Addr)*>(reloc) += load_bias;
    123         }
    124         break;
    125       default:
    126         DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
    127         return false;
    128     }
    129   }
    130   return true;
    131 }
    132 
    133 bool soinfo::mips_relocate_got(const VersionTracker& version_tracker,
    134                                const soinfo_list_t& global_group,
    135                                const soinfo_list_t& local_group) {
    136   ElfW(Addr)** got = plt_got_;
    137   if (got == nullptr) {
    138     return true;
    139   }
    140 
    141   // got[0] is the address of the lazy resolver function.
    142   // got[1] may be used for a GNU extension.
    143   // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start).
    144   // FIXME: maybe this should be in a separate routine?
    145   if ((flags_ & FLAG_LINKER) == 0) {
    146     size_t g = 0;
    147     got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadbeef);
    148     if (reinterpret_cast<intptr_t>(got[g]) < 0) {
    149       got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
    150     }
    151     // Relocate the local GOT entries.
    152     for (; g < mips_local_gotno_; g++) {
    153       got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + load_bias);
    154     }
    155   }
    156 
    157   // Now for the global GOT entries...
    158   got = plt_got_ + mips_local_gotno_;
    159   for (ElfW(Word) sym = mips_gotsym_; sym < mips_symtabno_; sym++, got++) {
    160     // This is an undefined reference... try to locate it.
    161     const ElfW(Sym)* local_sym = symtab_ + sym;
    162     const char* sym_name = get_string(local_sym->st_name);
    163     soinfo* lsi = nullptr;
    164     const ElfW(Sym)* s = nullptr;
    165 
    166     ElfW(Word) st_visibility = (local_sym->st_other & 0x3);
    167 
    168     if (st_visibility == STV_DEFAULT) {
    169       const version_info* vi = nullptr;
    170 
    171       if (!lookup_version_info(version_tracker, sym, sym_name, &vi)) {
    172         return false;
    173       }
    174 
    175       if (!soinfo_do_lookup(this, sym_name, vi, &lsi, global_group, local_group, &s)) {
    176         return false;
    177       }
    178     } else if (st_visibility == STV_PROTECTED) {
    179       if (local_sym->st_value == 0) {
    180         DL_ERR("%s: invalid symbol \"%s\" (PROTECTED/UNDEFINED) ",
    181                get_realpath(), sym_name);
    182         return false;
    183       }
    184       s = local_sym;
    185       lsi = this;
    186     } else {
    187       DL_ERR("%s: invalid symbol \"%s\" visibility: 0x%x",
    188              get_realpath(), sym_name, st_visibility);
    189       return false;
    190     }
    191 
    192     if (s == nullptr) {
    193       // We only allow an undefined symbol if this is a weak reference.
    194       if (ELF_ST_BIND(local_sym->st_info) != STB_WEAK) {
    195         DL_ERR("%s: cannot locate \"%s\"...", get_realpath(), sym_name);
    196         return false;
    197       }
    198       *got = 0;
    199     } else {
    200       // FIXME: is this sufficient?
    201       // For reference see NetBSD link loader
    202       // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
    203       *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
    204     }
    205   }
    206   return true;
    207 }
    208 
    209 #if !defined(__LP64__)
    210 
    211 // Checks for mips32's various floating point abis.
    212 // (Mips64 Android has a single floating point abi and doesn't need any checks)
    213 
    214 // Linux kernel has declarations similar to the following
    215 //   in <linux>/arch/mips/include/asm/elf.h,
    216 // but that non-uapi internal header file will never be imported
    217 // into bionic's kernel headers.
    218 
    219 #define PT_MIPS_ABIFLAGS  0x70000003	// is .MIPS.abiflags segment
    220 
    221 struct mips_elf_abiflags_v0 {
    222   uint16_t version;  // version of this structure
    223   uint8_t  isa_level, isa_rev, gpr_size, cpr1_size, cpr2_size;
    224   uint8_t  fp_abi;  // mips32 ABI variants for floating point
    225   uint32_t isa_ext, ases, flags1, flags2;
    226 };
    227 
    228 // Bits of flags1:
    229 #define MIPS_AFL_FLAGS1_ODDSPREG 1  // Uses odd-numbered single-prec fp regs
    230 
    231 // Some values of fp_abi:        via compiler flag:
    232 #define MIPS_ABI_FP_DOUBLE 1  // -mdouble-float
    233 #define MIPS_ABI_FP_XX     5  // -mfpxx
    234 #define MIPS_ABI_FP_64A    7  // -mips32r* -mfp64 -mno-odd-spreg
    235 
    236 #if __mips_isa_rev >= 5
    237 static bool mips_fre_mode_on = false;  // have set FRE=1 mode for process
    238 #endif
    239 
    240 bool soinfo::mips_check_and_adjust_fp_modes() {
    241   mips_elf_abiflags_v0* abiflags = nullptr;
    242   int mips_fpabi;
    243 
    244   // Find soinfo's optional .MIPS.abiflags segment
    245   for (size_t i = 0; i<phnum; ++i) {
    246     const ElfW(Phdr)& ph = phdr[i];
    247     if (ph.p_type == PT_MIPS_ABIFLAGS) {
    248       if (ph.p_filesz < sizeof (mips_elf_abiflags_v0)) {
    249         DL_ERR("Corrupt PT_MIPS_ABIFLAGS header found \"%s\"", get_realpath());
    250         return false;
    251       }
    252       abiflags = reinterpret_cast<mips_elf_abiflags_v0*>(ph.p_vaddr + load_bias);
    253       break;
    254     }
    255   }
    256 
    257   // FP ABI-variant compatibility checks for MIPS o32 ABI
    258   if (abiflags == nullptr) {
    259     // Old compilers and some translators don't emit the new abiflags section.
    260     const char* filename = get_realpath();
    261     size_t len = strlen(filename);
    262     if (len > 4 && (strcmp(filename+len-4, ".dex") == 0 ||
    263                     strcmp(filename+len-4, ".oat") == 0   )) {
    264       // Assume dex2oat is compatible with target
    265       mips_fpabi = MIPS_ABI_FP_XX;
    266     } else {
    267       // Old Android compilers used -mfp32 -mdouble-float -modd-spreg defaults,
    268       //   ie FP32 aka DOUBLE, using FR=0 mode fpregs & odd single-prec fpregs
    269       mips_fpabi = MIPS_ABI_FP_DOUBLE;
    270     }
    271   } else {
    272     mips_fpabi = abiflags->fp_abi;
    273     if ( (abiflags->flags1 & MIPS_AFL_FLAGS1_ODDSPREG)
    274          && (mips_fpabi == MIPS_ABI_FP_XX ||
    275              mips_fpabi == MIPS_ABI_FP_64A   ) ) {
    276       // Android supports fewer cases than Linux
    277       DL_ERR("Unsupported odd-single-prec FloatPt reg uses in \"%s\"",
    278              get_realpath());
    279       return false;
    280     }
    281   }
    282   if (!(mips_fpabi == MIPS_ABI_FP_DOUBLE ||
    283 #if __mips_isa_rev >= 5
    284         mips_fpabi == MIPS_ABI_FP_64A    ||
    285 #endif
    286         mips_fpabi == MIPS_ABI_FP_XX       )) {
    287     DL_ERR("Unsupported MIPS32 FloatPt ABI %d found in \"%s\"",
    288            mips_fpabi, get_realpath());
    289     return false;
    290   }
    291 
    292 #if __mips_isa_rev >= 5
    293   // Adjust process's FR Emulation mode, if needed
    294   //
    295   // On Mips R5 & R6, Android runs continuously in FR=1 64bit-fpreg mode.
    296   // NDK mips32 apps compiled with old compilers generate FP32 code
    297   //   which expects FR=0 32-bit fp registers.
    298   // NDK mips32 apps compiled with newer compilers generate modeless
    299   //   FPXX code which runs on both FR=0 and FR=1 modes.
    300   // Android itself is compiled in FP64A which requires FR=1 mode.
    301   // FP32, FPXX, and FP64A all interlink okay, without dynamic FR mode
    302   //   changes during calls.  For details, see
    303   //   http://dmz-portal.mips.com/wiki/MIPS_O32_ABI_-_FR0_and_FR1_Interlinking
    304   // Processes containing FR32 FR=0 code are run via kernel software assist,
    305   //   which maps all odd-numbered single-precision reg refs onto the
    306   //   upper half of the paired even-numbered double-precision reg.
    307   // FRE=1 triggers traps to the kernel's emulator on every single-precision
    308   //   fp op (for both odd and even-numbered registers).
    309   // Turning on FRE=1 traps is done at most once per process, simultanously
    310   //   for all threads of that process, when dlopen discovers FP32 code.
    311   // The kernel repacks threads' registers when FRE mode is turn on or off.
    312   //   These asynchronous adjustments are wrong if any thread was executing
    313   //   FPXX code using odd-numbered single-precision regs.
    314   // Current Android compilers default to the -mno-oddspreg option,
    315   //   and this requirement is checked by Android's dlopen.
    316   //   So FRE can always be safely turned on for FP32, anytime.
    317   // Deferred enhancement: Allow loading of odd-spreg FPXX modules.
    318 
    319   if (mips_fpabi == MIPS_ABI_FP_DOUBLE && !mips_fre_mode_on) {
    320     // Turn on FRE mode, which emulates mode-sensitive FR=0 code on FR=1
    321     //   register files, by trapping to kernel on refs to single-precision regs
    322     if (prctl(PR_SET_FP_MODE, PR_FP_MODE_FR|PR_FP_MODE_FRE)) {
    323       DL_ERR("Kernel or cpu failed to set FRE mode required for running \"%s\"",
    324              get_realpath());
    325       return false;
    326     }
    327     DL_WARN("Using FRE=1 mode to run \"%s\"", get_realpath());
    328     mips_fre_mode_on = true;  // Avoid future redundant mode-switch calls
    329     // FRE mode is never turned back off.
    330     // Deferred enhancement:
    331     //   Reset FRE mode when dlclose() removes all FP32 modules
    332   }
    333 #else
    334   // Android runs continuously in FR=0 32bit-fpreg mode.
    335 #endif  // __mips_isa_rev
    336   return true;
    337 }
    338 
    339 #endif  // __LP64___
    340