| Colin Cross | bcb4ed3 | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 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 <inttypes.h> | 
 | 18 | #include <fcntl.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 | // This function is not re-entrant since it uses a static buffer for | 
 | 29 | // the line data. | 
 | 30 | bool ProcessMappings(pid_t pid, allocator::vector<Mapping>& mappings) { | 
 | 31 |   char map_buffer[1024]; | 
 | 32 |   snprintf(map_buffer, sizeof(map_buffer), "/proc/%d/maps", pid); | 
| Elliott Hughes | 2c5d1d7 | 2016-03-28 12:15:36 -0700 | [diff] [blame] | 33 |   android::base::unique_fd fd(open(map_buffer, O_RDONLY)); | 
 | 34 |   if (fd == -1) { | 
| Colin Cross | bcb4ed3 | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 35 |     return false; | 
 | 36 |   } | 
| Colin Cross | bcb4ed3 | 2016-01-14 15:35:40 -0800 | [diff] [blame] | 37 |  | 
 | 38 |   LineBuffer line_buf(fd, map_buffer, sizeof(map_buffer)); | 
 | 39 |   char* line; | 
 | 40 |   size_t line_len; | 
 | 41 |   while (line_buf.GetLine(&line, &line_len)) { | 
 | 42 |     int name_pos; | 
 | 43 |     char perms[5]; | 
 | 44 |     Mapping mapping{}; | 
 | 45 |     if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %*x %*x:%*x %*d %n", | 
 | 46 |         &mapping.begin, &mapping.end, perms, &name_pos) == 3) { | 
 | 47 |       if (perms[0] == 'r') { | 
 | 48 |         mapping.read = true; | 
 | 49 |       } | 
 | 50 |       if (perms[1] == 'w') { | 
 | 51 |         mapping.write = true; | 
 | 52 |       } | 
 | 53 |       if (perms[2] == 'x') { | 
 | 54 |         mapping.execute = true; | 
 | 55 |       } | 
 | 56 |       if (perms[3] == 'p') { | 
 | 57 |         mapping.priv = true; | 
 | 58 |       } | 
 | 59 |       if ((size_t)name_pos < line_len) { | 
 | 60 |         strlcpy(mapping.name, line + name_pos, sizeof(mapping.name)); | 
 | 61 |       } | 
 | 62 |       mappings.emplace_back(mapping); | 
 | 63 |     } | 
 | 64 |   } | 
 | 65 |   return true; | 
 | 66 | } |