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 <dirent.h>
20 #include <errno.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include <string>
28 #include <utility>
29 #include <vector>
30
31 #include <android-base/file.h>
32 #include <log/log.h>
33
34 #include "open_files_list.h"
35
36 #include "utility.h"
37
populate_open_files_list(pid_t pid,OpenFilesList * list)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
dump_open_files_list_to_log(const OpenFilesList & files,log_t * log,const char * prefix)64 void dump_open_files_list_to_log(const OpenFilesList& files, log_t* log, 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