• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 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 #ifndef __TEST_UTILS_H
18 #define __TEST_UTILS_H
19 #include <inttypes.h>
20 #include <sys/mman.h>
21 
22 #include "private/ScopeGuard.h"
23 
24 struct map_record {
25   uintptr_t addr_start;
26   uintptr_t addr_end;
27 
28   int perms;
29 
30   size_t offset;
31 
32   dev_t device;
33   ino_t inode;
34 
35   std::string pathname;
36 };
37 
38 class Maps {
39  public:
parse_maps(std::vector<map_record> * maps)40   static bool parse_maps(std::vector<map_record>* maps) {
41     char path[64];
42     snprintf(path, sizeof(path), "/proc/self/task/%d/maps", getpid());
43     FILE* fp = fopen(path, "re");
44     if (fp == nullptr) {
45       return false;
46     }
47 
48     auto fp_guard = make_scope_guard([&]() {
49       fclose(fp);
50     });
51 
52     char line[BUFSIZ];
53     while (fgets(line, sizeof(line), fp) != nullptr) {
54       map_record record;
55       uint32_t dev_major, dev_minor;
56       char pathstr[BUFSIZ];
57       char prot[5]; // sizeof("rwxp")
58       if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %" SCNxPTR " %x:%x %lu %s",
59             &record.addr_start, &record.addr_end, prot, &record.offset,
60             &dev_major, &dev_minor, &record.inode, pathstr) == 8) {
61         record.perms = 0;
62         if (prot[0] == 'r') {
63           record.perms |= PROT_READ;
64         }
65         if (prot[1] == 'w') {
66           record.perms |= PROT_WRITE;
67         }
68         if (prot[2] == 'x') {
69           record.perms |= PROT_EXEC;
70         }
71 
72         // TODO: parse shared/private?
73 
74         record.device = makedev(dev_major, dev_minor);
75         record.pathname = pathstr;
76         maps->push_back(record);
77       }
78     }
79 
80     return true;
81   }
82 };
83 
84 #endif
85