• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fcntl.h>
18 #include <inttypes.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 namespace android {
29 
30 // This function is not re-entrant since it uses a static buffer for
31 // the line data.
ProcessMappings(pid_t pid,allocator::vector<Mapping> & mappings)32 bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) {
33   char map_buffer[1024];
34   snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid);
35   android::base::unique_fd fd(open(map_buffer, O_RDONLY));
36   if (fd == -1) {
37     return false;
38   }
39 
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{};
47     if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %*x %*x:%*x %*d %n", &mapping.begin,
48                &mapping.end, perms, &name_pos) == 3) {
49       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 }
69 
70 }  // namespace android
71