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