1 /*
2  * Copyright (C) 2012 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 #include <ctype.h>
30 #include <elf.h>
31 #include <inttypes.h>
32 #include <link.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sys/mman.h>
37 #include <sys/uio.h>
38 #include <unistd.h>
39 
40 #include <vector>
41 
42 #include "MapData.h"
43 
44 // Format of /proc/<PID>/maps:
45 //   6f000000-6f01e000 rwxp 00000000 00:0c 16389419   /system/lib/libcomposer.so
parse_line(char * line)46 static MapEntry* parse_line(char* line) {
47   uintptr_t start;
48   uintptr_t end;
49   uintptr_t offset;
50   int flags;
51   char permissions[5];
52   int name_pos;
53   if (sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %4s %" PRIxPTR " %*x:%*x %*d %n", &start, &end,
54              permissions, &offset, &name_pos) < 2) {
55     return nullptr;
56   }
57 
58   const char* name = line + name_pos;
59   size_t name_len = strlen(name);
60   if (name_len && name[name_len - 1] == '\n') {
61     name_len -= 1;
62   }
63 
64   flags = 0;
65   if (permissions[0] == 'r') {
66     flags |= PROT_READ;
67   }
68   if (permissions[2] == 'x') {
69     flags |= PROT_EXEC;
70   }
71 
72   MapEntry* entry = new MapEntry(start, end, offset, name, name_len, flags);
73   if (!(flags & PROT_READ)) {
74     // This will make sure that an unreadable map will prevent attempts to read
75     // elf data from the map.
76     entry->SetInvalid();
77   }
78   return entry;
79 }
80 
Init()81 void MapEntry::Init() {
82   if (init_) {
83     return;
84   }
85   init_ = true;
86 
87   uintptr_t end_addr;
88   if (__builtin_add_overflow(start_, SELFMAG, &end_addr) || end_addr >= end_) {
89     return;
90   }
91 
92   ElfW(Ehdr) ehdr;
93   struct iovec src_io = {.iov_base = reinterpret_cast<void*>(start_), .iov_len = SELFMAG};
94   struct iovec dst_io = {.iov_base = ehdr.e_ident, .iov_len = SELFMAG};
95   ssize_t rc = process_vm_readv(getpid(), &dst_io, 1, &src_io, 1, 0);
96   valid_ = rc == SELFMAG && IS_ELF(ehdr);
97 }
98 
GetLoadBias()99 uintptr_t MapEntry::GetLoadBias() {
100   if (!valid_) {
101     return 0;
102   }
103 
104   if (load_bias_read_) {
105     return load_bias_;
106   }
107 
108   load_bias_read_ = true;
109 
110   ElfW(Ehdr) ehdr;
111   struct iovec src_io = {.iov_base = reinterpret_cast<void*>(start_), .iov_len = sizeof(ehdr)};
112   struct iovec dst_io = {.iov_base = &ehdr, .iov_len = sizeof(ehdr)};
113   ssize_t rc = process_vm_readv(getpid(), &dst_io, 1, &src_io, 1, 0);
114   if (rc != sizeof(ehdr)) {
115     return 0;
116   }
117 
118   uintptr_t addr = start_ + ehdr.e_phoff;
119   for (size_t i = 0; i < ehdr.e_phnum; i++) {
120     ElfW(Phdr) phdr;
121 
122     src_io.iov_base = reinterpret_cast<void*>(addr);
123     src_io.iov_len = sizeof(phdr);
124     dst_io.iov_base = &phdr;
125     dst_io.iov_len = sizeof(phdr);
126     rc = process_vm_readv(getpid(), &dst_io, 1, &src_io, 1, 0);
127     if (rc != sizeof(phdr)) {
128       return 0;
129     }
130     if ((phdr.p_type == PT_LOAD) && (phdr.p_flags & PF_X) ) {
131       load_bias_ = phdr.p_vaddr - phdr.p_offset;
132       return load_bias_;
133     }
134     addr += sizeof(phdr);
135   }
136   return 0;
137 }
138 
ReadMaps()139 void MapData::ReadMaps() {
140   std::lock_guard<std::mutex> lock(m_);
141   FILE* fp = fopen("/proc/self/maps", "re");
142   if (fp == nullptr) {
143     return;
144   }
145 
146   ClearEntries();
147 
148   std::vector<char> buffer(1024);
149   while (fgets(buffer.data(), buffer.size(), fp) != nullptr) {
150     MapEntry* entry = parse_line(buffer.data());
151     if (entry == nullptr) {
152       break;
153     }
154     entries_.insert(entry);
155   }
156   fclose(fp);
157 }
158 
ClearEntries()159 void MapData::ClearEntries() {
160   for (auto* entry : entries_) {
161     delete entry;
162   }
163   entries_.clear();
164 }
165 
~MapData()166 MapData::~MapData() {
167   ClearEntries();
168 }
169 
170 // Find the containing map info for the PC.
find(uintptr_t pc,uintptr_t * rel_pc)171 const MapEntry* MapData::find(uintptr_t pc, uintptr_t* rel_pc) {
172   MapEntry pc_entry(pc);
173 
174   std::lock_guard<std::mutex> lock(m_);
175   auto it = entries_.find(&pc_entry);
176   if (it == entries_.end()) {
177     return nullptr;
178   }
179 
180   MapEntry* entry = *it;
181   entry->Init();
182 
183   if (rel_pc != nullptr) {
184     // Need to check to see if this is a read-execute map and the read-only
185     // map is the previous one.
186     if (!entry->valid() && it != entries_.begin()) {
187       MapEntry* prev_entry = *--it;
188       if (prev_entry->flags() == PROT_READ && prev_entry->offset() < entry->offset() &&
189           prev_entry->name() == entry->name()) {
190         prev_entry->Init();
191 
192         if (prev_entry->valid()) {
193           entry->set_elf_start_offset(prev_entry->offset());
194           *rel_pc = pc - entry->start() + entry->offset() + prev_entry->GetLoadBias();
195           return entry;
196         }
197       }
198     }
199     *rel_pc = pc - entry->start() + entry->offset() + entry->GetLoadBias();
200   }
201   return entry;
202 }
203