blob: 7cca7c15df66853d35ff700b265775c5ea771693 [file] [log] [blame]
Colin Cross7add50d2016-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
17#include <inttypes.h>
18#include <fcntl.h>
19#include <string.h>
20#include <unistd.h>
21
22#include <android-base/unique_fd.h>
23
24#include "LineBuffer.h"
25#include "ProcessMappings.h"
26#include "log.h"
27
28// This function is not re-entrant since it uses a static buffer for
29// the line data.
30bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) {
31 char map_buffer[1024];
32 snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid);
33 int fd = open(map_buffer, O_RDONLY);
34 if (fd < 0) {
35 return false;
36 }
37 android::base::unique_fd fd_guard{fd};
38
39 LineBuffer line_buf(fd, map_buffer, sizeof(map_buffer));
40 char* line;
41 size_t line_len;
42 while (line_buf.GetLine(&line, &line_len)) {
43 int name_pos;
44 char perms[5];
45 Mapping mapping{};
46 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %*x %*x:%*x %*d %n",
47 &mapping.begin, &mapping.end, perms, &name_pos) == 3) {
48 if (perms[0] == 'r') {
49 mapping.read = true;
50 }
51 if (perms[1] == 'w') {
52 mapping.write = true;
53 }
54 if (perms[2] == 'x') {
55 mapping.execute = true;
56 }
57 if (perms[3] == 'p') {
58 mapping.priv = true;
59 }
60 if ((size_t)name_pos < line_len) {
61 strlcpy(mapping.name, line + name_pos, sizeof(mapping.name));
62 }
63 mappings.emplace_back(mapping);
64 }
65 }
66 return true;
67}