blob: 8e1be4c8c6678fd2781006b283a34a910901179d [file] [log] [blame]
Colin Crossab7c9f12016-01-14 15:35:40 -08001/*
2 * Copyright (C) 2016 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
Yabin Cuie998a2b2018-05-10 17:19:12 -070017#include <errno.h>
Colin Crossab7c9f12016-01-14 15:35:40 -080018#include <fcntl.h>
Colin Cross401319a2017-06-22 10:50:05 -070019#include <inttypes.h>
Colin Crossab7c9f12016-01-14 15:35:40 -080020#include <string.h>
Sandeep Patil659a20b2019-01-30 17:43:22 -080021#include <sys/types.h>
Colin Crossab7c9f12016-01-14 15:35:40 -080022#include <unistd.h>
23
24#include <android-base/unique_fd.h>
Yabin Cuie998a2b2018-05-10 17:19:12 -070025#include <procinfo/process_map.h>
Colin Crossab7c9f12016-01-14 15:35:40 -080026
Colin Crossab7c9f12016-01-14 15:35:40 -080027#include "ProcessMappings.h"
Colin Crossab7c9f12016-01-14 15:35:40 -080028
Colin Cross1fa81f52017-06-21 13:13:00 -070029namespace android {
30
Yabin Cuie998a2b2018-05-10 17:19:12 -070031struct ReadMapCallback {
32 ReadMapCallback(allocator::vector<Mapping>& mappings) : mappings_(mappings) {}
33
Sandeep Patil659a20b2019-01-30 17:43:22 -080034 void operator()(uint64_t start, uint64_t end, uint16_t flags, uint64_t, ino_t,
35 const char* name) const {
Yabin Cuie998a2b2018-05-10 17:19:12 -070036 mappings_.emplace_back(start, end, flags & PROT_READ, flags & PROT_WRITE, flags & PROT_EXEC,
37 name);
38 }
39
40 allocator::vector<Mapping>& mappings_;
41};
42
Colin Crossab7c9f12016-01-14 15:35:40 -080043bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) {
44 char map_buffer[1024];
45 snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid);
Elliott Hughes18417e62016-03-28 12:15:36 -070046 android::base::unique_fd fd(open(map_buffer, O_RDONLY));
47 if (fd == -1) {
Colin Crossab7c9f12016-01-14 15:35:40 -080048 return false;
49 }
Yabin Cuie998a2b2018-05-10 17:19:12 -070050 allocator::string content(mappings.get_allocator());
51 ssize_t n;
52 while ((n = TEMP_FAILURE_RETRY(read(fd, map_buffer, sizeof(map_buffer)))) > 0) {
53 content.append(map_buffer, n);
Colin Crossab7c9f12016-01-14 15:35:40 -080054 }
Yabin Cuie998a2b2018-05-10 17:19:12 -070055 ReadMapCallback callback(mappings);
56 return android::procinfo::ReadMapFileContent(&content[0], callback);
Colin Crossab7c9f12016-01-14 15:35:40 -080057}
Colin Cross1fa81f52017-06-21 13:13:00 -070058
59} // namespace android