blob: 53cf6b6ea3a1082c4a9f5cf7d580db5686a7ec21 [file] [log] [blame]
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -07001/*
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
24struct 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
38class Maps {
39 public:
40 static bool parse_maps(std::vector<map_record>* maps) {
Elliott Hughes15dfd632015-09-22 16:40:14 -070041 FILE* fp = fopen("/proc/self/maps", "re");
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -070042 if (fp == nullptr) {
43 return false;
44 }
45
46 auto fp_guard = make_scope_guard([&]() {
47 fclose(fp);
48 });
49
50 char line[BUFSIZ];
51 while (fgets(line, sizeof(line), fp) != nullptr) {
52 map_record record;
Dmitriy Ivanov1dce3ed2015-04-06 19:05:58 -070053 uint32_t dev_major, dev_minor;
Elliott Hughes15dfd632015-09-22 16:40:14 -070054 int path_offset;
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -070055 char prot[5]; // sizeof("rwxp")
Elliott Hughes15dfd632015-09-22 16:40:14 -070056 if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %" SCNxPTR " %x:%x %lu %n",
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -070057 &record.addr_start, &record.addr_end, prot, &record.offset,
Elliott Hughes15dfd632015-09-22 16:40:14 -070058 &dev_major, &dev_minor, &record.inode, &path_offset) == 7) {
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -070059 record.perms = 0;
60 if (prot[0] == 'r') {
61 record.perms |= PROT_READ;
62 }
63 if (prot[1] == 'w') {
64 record.perms |= PROT_WRITE;
65 }
66 if (prot[2] == 'x') {
67 record.perms |= PROT_EXEC;
68 }
69
70 // TODO: parse shared/private?
71
72 record.device = makedev(dev_major, dev_minor);
Elliott Hughes15dfd632015-09-22 16:40:14 -070073 record.pathname = line + path_offset;
74 if (!record.pathname.empty() && record.pathname.back() == '\n') {
75 record.pathname.pop_back();
76 }
Dmitriy Ivanovaae859c2015-03-31 11:14:03 -070077 maps->push_back(record);
78 }
79 }
80
81 return true;
82 }
83};
84
85#endif