1 /*
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
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <inttypes.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23
24 #include <android-base/unique_fd.h>
25 #include <procinfo/process_map.h>
26
27 #include "ProcessMappings.h"
28
29 namespace android {
30
31 struct ReadMapCallback {
ReadMapCallbackandroid::ReadMapCallback32 ReadMapCallback(allocator::vector<Mapping>& mappings) : mappings_(mappings) {}
33
operator ()android::ReadMapCallback34 void operator()(uint64_t start, uint64_t end, uint16_t flags, uint64_t, ino_t, const char* name,
35 bool) const {
36 mappings_.emplace_back(start, end, flags & PROT_READ,
37 flags & PROT_WRITE, flags & PROT_EXEC,
38 name);
39 }
40
41 allocator::vector<Mapping>& mappings_;
42 };
43
ProcessMappings(pid_t pid,allocator::vector<Mapping> & mappings)44 bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) {
45 char map_buffer[1024];
46 snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid);
47 android::base::unique_fd fd(open(map_buffer, O_RDONLY));
48 if (fd == -1) {
49 return false;
50 }
51 allocator::string content(mappings.get_allocator());
52 ssize_t n;
53 while ((n = TEMP_FAILURE_RETRY(read(fd, map_buffer, sizeof(map_buffer)))) > 0) {
54 content.append(map_buffer, n);
55 }
56 ReadMapCallback callback(mappings);
57 return android::procinfo::ReadMapFileContent(&content[0], callback);
58 }
59
60 } // namespace android
61