blob: 9a0687052f48234b9d7d3f9b8d1de57cc3da9694 [file] [log] [blame]
Colin Crossbcb4ed32016-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
Colin Crossbcb4ed32016-01-14 15:35:40 -080017#include <fcntl.h>
Colin Crossa83881e2017-06-22 10:50:05 -070018#include <inttypes.h>
Colin Crossbcb4ed32016-01-14 15:35:40 -080019#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
Colin Crossa9939e92017-06-21 13:13:00 -070028namespace android {
29
Colin Crossbcb4ed32016-01-14 15:35:40 -080030// This function is not re-entrant since it uses a static buffer for
31// the line data.
32bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) {
33 char map_buffer[1024];
34 snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid);
Elliott Hughes2c5d1d72016-03-28 12:15:36 -070035 android::base::unique_fd fd(open(map_buffer, O_RDONLY));
36 if (fd == -1) {
Colin Crossbcb4ed32016-01-14 15:35:40 -080037 return false;
38 }
Colin Crossbcb4ed32016-01-14 15:35:40 -080039
40 LineBuffer line_buf(fd, map_buffer, sizeof(map_buffer));
41 char* line;
42 size_t line_len;
43 while (line_buf.GetLine(&line, &line_len)) {
44 int name_pos;
45 char perms[5];
46 Mapping mapping{};
Colin Crossa83881e2017-06-22 10:50:05 -070047 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %*x %*x:%*x %*d %n", &mapping.begin,
48 &mapping.end, perms, &name_pos) == 3) {
Colin Crossbcb4ed32016-01-14 15:35:40 -080049 if (perms[0] == 'r') {
50 mapping.read = true;
51 }
52 if (perms[1] == 'w') {
53 mapping.write = true;
54 }
55 if (perms[2] == 'x') {
56 mapping.execute = true;
57 }
58 if (perms[3] == 'p') {
59 mapping.priv = true;
60 }
61 if ((size_t)name_pos < line_len) {
62 strlcpy(mapping.name, line + name_pos, sizeof(mapping.name));
63 }
64 mappings.emplace_back(mapping);
65 }
66 }
67 return true;
68}
Colin Crossa9939e92017-06-21 13:13:00 -070069
70} // namespace android