blob: 051f7006139ca6ba455aa2d803d8ba24c2809548 [file] [log] [blame]
Christopher Ferris0d7cf3e2017-04-19 15:42:19 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <sys/types.h>
18#include <unistd.h>
19
20#include <memory>
21#include <string>
22
23#include "Elf.h"
24#include "MapInfo.h"
25#include "Maps.h"
26#include "Memory.h"
27
28Memory* MapInfo::CreateMemory(pid_t pid) {
29 if (end <= start) {
30 return nullptr;
31 }
32
33 elf_offset = 0;
34
35 // First try and use the file associated with the info.
36 if (!name.empty()) {
37 // Fail on device maps.
38 if (flags & MAPS_FLAGS_DEVICE_MAP) {
39 return nullptr;
40 }
41
42 std::unique_ptr<MemoryFileAtOffset> file_memory(new MemoryFileAtOffset);
43 uint64_t map_size;
44 if (offset != 0) {
45 // Only map in a piece of the file.
46 map_size = end - start;
47 } else {
48 map_size = UINT64_MAX;
49 }
50 if (file_memory->Init(name, offset, map_size)) {
51 // It's possible that a non-zero offset might not be pointing to
52 // valid elf data. Check if this is a valid elf, and if not assume
53 // that this was meant to incorporate the entire file.
54 if (offset != 0 && !Elf::IsValidElf(file_memory.get())) {
55 // Don't bother checking the validity that will happen on the elf init.
56 if (file_memory->Init(name, 0)) {
57 elf_offset = offset;
58 return file_memory.release();
59 }
60 // Fall through if the init fails.
61 } else {
62 return file_memory.release();
63 }
64 }
65 }
66
67 Memory* memory = nullptr;
68 if (pid == getpid()) {
69 memory = new MemoryLocal();
70 } else {
71 memory = new MemoryRemote(pid);
72 }
73 return new MemoryRange(memory, start, end);
74}
75
76Elf* MapInfo::GetElf(pid_t pid, bool) {
77 if (elf) {
78 return elf;
79 }
80
81 elf = new Elf(CreateMemory(pid));
82 elf->Init();
83 // If the init fails, keep the elf around as an invalid object so we
84 // don't try to reinit the object.
85 return elf;
86}