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 <procinfo/process.h>
18
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24
25 #include <string>
26
27 #include <android-base/unique_fd.h>
28
29 using android::base::unique_fd;
30
31 namespace android {
32 namespace procinfo {
33
SetError(std::string * error,int errno_value,const char * fmt,...)34 bool SetError(std::string* error, int errno_value, const char* fmt, ...) {
35 if (error == nullptr) return false;
36
37 std::string result;
38 va_list ap;
39 va_start(ap, fmt);
40 android::base::StringAppendV(&result, fmt, ap);
41 va_end(ap);
42
43 if (errno_value != 0) {
44 result += ": ";
45 result += strerror(errno_value);
46 }
47
48 *error = result;
49 return false;
50 }
51
GetProcessInfo(pid_t tid,ProcessInfo * process_info,std::string * error)52 bool GetProcessInfo(pid_t tid, ProcessInfo* process_info, std::string* error) {
53 char path[32];
54 snprintf(path, sizeof(path), "/proc/%d", tid);
55
56 unique_fd dirfd(open(path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
57 if (dirfd == -1) {
58 return SetError(error, errno, "failed to open %s", path);
59 }
60
61 return GetProcessInfoFromProcPidFd(dirfd.get(), tid, process_info, error);
62 }
63
parse_state(char state)64 static ProcessState parse_state(char state) {
65 switch (state) {
66 case 'R':
67 return kProcessStateRunning;
68 case 'S':
69 return kProcessStateSleeping;
70 case 'D':
71 return kProcessStateUninterruptibleWait;
72 case 'T':
73 return kProcessStateStopped;
74 case 'Z':
75 return kProcessStateZombie;
76 default:
77 return kProcessStateUnknown;
78 }
79 }
80
GetProcessInfoFromProcPidFd(int fd,int pid,ProcessInfo * process_info,std::string * error)81 bool GetProcessInfoFromProcPidFd(int fd, int pid, ProcessInfo* process_info,
82 std::string* error /* can be nullptr */) {
83 int status_fd = openat(fd, "status", O_RDONLY | O_CLOEXEC);
84 if (status_fd == -1) {
85 return SetError(error, errno,
86 "failed to open /proc/%d/status in GetProcessInfoFromProcPidFd", pid);
87 }
88
89 std::unique_ptr<FILE, decltype(&fclose)> fp(fdopen(status_fd, "re"), fclose);
90 if (!fp) {
91 close(status_fd);
92 return SetError(error, errno, "failed to open FILE for /proc/%d/status in GetProcessInfoFromProcPidFd", pid);
93 }
94
95 int field_bitmap = 0;
96 static constexpr int finished_bitmap = 63;
97 char* line = nullptr;
98 size_t len = 0;
99
100 while (getline(&line, &len, fp.get()) != -1 && field_bitmap != finished_bitmap) {
101 char* tab = strchr(line, '\t');
102 if (tab == nullptr) {
103 continue;
104 }
105
106 size_t header_len = tab - line;
107 std::string header = std::string(line, header_len);
108 if (header == "Name:") {
109 std::string name = line + header_len + 1;
110
111 // line includes the trailing newline.
112 name.pop_back();
113 process_info->name = std::move(name);
114
115 field_bitmap |= 1;
116 } else if (header == "Tgid:") {
117 process_info->pid = atoi(tab + 1);
118 field_bitmap |= 2;
119 } else if (header == "Pid:") {
120 process_info->tid = atoi(tab + 1);
121 field_bitmap |= 4;
122 } else if (header == "TracerPid:") {
123 process_info->tracer = atoi(tab + 1);
124 field_bitmap |= 8;
125 } else if (header == "Uid:") {
126 process_info->uid = atoi(tab + 1);
127 field_bitmap |= 16;
128 } else if (header == "Gid:") {
129 process_info->gid = atoi(tab + 1);
130 field_bitmap |= 32;
131 }
132 }
133
134 free(line);
135 if (field_bitmap != finished_bitmap) {
136 return SetError(error, 0, "failed to parse /proc/%d/status", pid);
137 }
138
139 unique_fd stat_fd(openat(fd, "stat", O_RDONLY | O_CLOEXEC));
140 if (stat_fd == -1) {
141 return SetError(error, errno, "failed to open /proc/%d/stat", pid);
142 }
143
144 std::string stat;
145 if (!android::base::ReadFdToString(stat_fd, &stat)) {
146 return SetError(error, errno, "failed to read /proc/%d/stat", pid);
147 }
148
149 // See man 5 proc. There's no reason comm can't contain ' ' or ')',
150 // so we search backwards for the end of it.
151 const char* end_of_comm = strrchr(stat.c_str(), ')');
152
153 static constexpr const char* pattern =
154 "%c " // state
155 "%d " // ppid
156 "%*d " // pgrp
157 "%*d " // session
158 "%*d " // tty_nr
159 "%*d " // tpgid
160 "%*u " // flags
161 "%*lu " // minflt
162 "%*lu " // cminflt
163 "%*lu " // majflt
164 "%*lu " // cmajflt
165 "%*lu " // utime
166 "%*lu " // stime
167 "%*ld " // cutime
168 "%*ld " // cstime
169 "%*ld " // priority
170 "%*ld " // nice
171 "%*ld " // num_threads
172 "%*ld " // itrealvalue
173 "%llu " // starttime
174 ;
175
176 char state = '\0';
177 int ppid = 0;
178 unsigned long long start_time = 0;
179 int rc = sscanf(end_of_comm + 2, pattern, &state, &ppid, &start_time);
180 if (rc != 3) {
181 return SetError(error, 0, "failed to parse /proc/%d/stat", pid);
182 }
183
184 process_info->state = parse_state(state);
185 process_info->ppid = ppid;
186 process_info->starttime = start_time;
187 return true;
188 }
189
190 } /* namespace procinfo */
191 } /* namespace android */
192