Home | History | Annotate | Download | only in libdebuggerd
      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 #define LOG_TAG "DEBUG"
     18 
     19 #include "libdebuggerd/open_files_list.h"
     20 
     21 #include <dirent.h>
     22 #include <errno.h>
     23 #include <stdio.h>
     24 #include <stdlib.h>
     25 #include <string.h>
     26 #include <sys/types.h>
     27 #include <unistd.h>
     28 
     29 #include <string>
     30 #include <utility>
     31 #include <vector>
     32 
     33 #include <android-base/file.h>
     34 #include <log/log.h>
     35 
     36 #include "libdebuggerd/utility.h"
     37 
     38 void populate_open_files_list(pid_t pid, OpenFilesList* list) {
     39   std::string fd_dir_name = "/proc/" + std::to_string(pid) + "/fd";
     40   std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(fd_dir_name.c_str()), closedir);
     41   if (dir == nullptr) {
     42     ALOGE("failed to open directory %s: %s", fd_dir_name.c_str(), strerror(errno));
     43     return;
     44   }
     45 
     46   struct dirent* de;
     47   while ((de = readdir(dir.get())) != nullptr) {
     48     if (*de->d_name == '.') {
     49       continue;
     50     }
     51 
     52     int fd = atoi(de->d_name);
     53     std::string path = fd_dir_name + "/" + std::string(de->d_name);
     54     std::string target;
     55     if (android::base::Readlink(path, &target)) {
     56       list->emplace_back(fd, target);
     57     } else {
     58       ALOGE("failed to readlink %s: %s", path.c_str(), strerror(errno));
     59       list->emplace_back(fd, "???");
     60     }
     61   }
     62 }
     63 
     64 void dump_open_files_list(log_t* log, const OpenFilesList& files, const char* prefix) {
     65   for (auto& file : files) {
     66     _LOG(log, logtype::OPEN_FILES, "%sfd %i: %s\n", prefix, file.first, file.second.c_str());
     67   }
     68 }
     69 
     70