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 <errno.h>
18 #include <fcntl.h>
19 #include <inttypes.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 
24 #include <android-base/unique_fd.h>
25 #include <procinfo/process_map.h>
26 
27 #include "ProcessMappings.h"
28 
29 namespace android {
30 
31 struct ReadMapCallback {
ReadMapCallbackandroid::ReadMapCallback32   ReadMapCallback(allocator::vector<Mapping>& mappings) : mappings_(mappings) {}
33 
operator ()android::ReadMapCallback34   void operator()(uint64_t start, uint64_t end, uint16_t flags, uint64_t, ino_t,
35                   const char* name) const {
36     mappings_.emplace_back(start, end, flags & PROT_READ, flags & PROT_WRITE, flags & PROT_EXEC,
37                            name);
38   }
39 
40   allocator::vector<Mapping>& mappings_;
41 };
42 
ProcessMappings(pid_t pid,allocator::vector<Mapping> & mappings)43 bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) {
44   char map_buffer[1024];
45   snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid);
46   android::base::unique_fd fd(open(map_buffer, O_RDONLY));
47   if (fd == -1) {
48     return false;
49   }
50   allocator::string content(mappings.get_allocator());
51   ssize_t n;
52   while ((n = TEMP_FAILURE_RETRY(read(fd, map_buffer, sizeof(map_buffer)))) > 0) {
53     content.append(map_buffer, n);
54   }
55   ReadMapCallback callback(mappings);
56   return android::procinfo::ReadMapFileContent(&content[0], callback);
57 }
58 
59 }  // namespace android
60