summaryrefslogtreecommitdiff
path: root/src/procfs.c
blob: 12968095033bdd9909edbd031f0bf6b826bff27a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
 * Copyright (c) 2018 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Flora License, Version 1.1 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://floralicense.org/license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>

#include "procfs.h"
#include "log.h"
#include "err-check.h"

#define LOADAVG_FILEPATH "/proc/loadavg"
#define UPTIME_FILEPATH  "/proc/uptime"
#define POSSIBLE_CPUS_FILEPATH  "/sys/devices/system/cpu/possible"
#define MEMINFO_FILEPATH "/proc/meminfo"
#define STAT_FILEPATH "/proc/stat"
#define PIDSTAT_FILEPATH "/proc/%d/stat"
#define SMAPS_FILEPATH "/proc/%d/smaps"
#define PROC_DIR_PATH "/proc/"
#define PROC_PID_EXE_PATH "/proc/%d/exe"
#define PROC_PID_CMDLINE_PATH "/proc/%d/cmdline"

int procfs_read_system_load_average(struct procfs_load_average_info *info)
{
	float a1, a5, a15;

	ON_NULL_RETURN_VAL(info, -1);

	FILE *loadavg_fp = fopen(LOADAVG_FILEPATH, "r");
	if (!loadavg_fp) {
		ERR("failed to open " LOADAVG_FILEPATH);
		return -1;
	}

	if (fscanf(loadavg_fp, "%f %f %f", &a1, &a5, &a15) != 3) {
		ERR("failed to read " LOADAVG_FILEPATH);
		fclose(loadavg_fp);
		return -1;
	}

	info->one_min_avg = a1;
	info->five_min_avg = a5;
	info->fifteen_min_avg = a15;

	fclose(loadavg_fp);

	return 0;
}

int procfs_read_system_cpu_usage(struct procfs_system_cpu_usage_info *usage)
{
	ON_NULL_RETURN_VAL(usage, -1);

	char line[256];
	struct procfs_system_cpu_usage_info tmp;
	const char *prefix = "cpu ";

	FILE *stat_fp = fopen(STAT_FILEPATH, "r");
	if (!stat_fp) {
		ERR("failed to open " STAT_FILEPATH);
		return -1;
	}

	while (fgets(line, sizeof(line), stat_fp)) {
		if (!strncmp(line, prefix, strlen(prefix)) &&
		    sscanf(line + 4, "%llu %llu %llu %llu %llu %llu %llu",
				&tmp.user, &tmp.nice, &tmp.system, &tmp.idle,
				&tmp.iowait, &tmp.irq, &tmp.softirq) == 7) {
			*usage = tmp;
			fclose(stat_fp);
			return 0;
		}
	}

	fclose(stat_fp);

	return -1;
}

int procfs_read_system_percpu_usage(int max_cpus, struct procfs_system_cpu_usage_info usage[])
{
	return -1;
}

int procfs_read_system_memory_usage(struct procfs_system_memory_usage_info *usage)
{
	ON_NULL_RETURN_VAL(usage, -1);

	char line[128];
	unsigned long value;
	unsigned long mem_total = 0;
	unsigned long mem_free = 0;
	unsigned long cached = 0;
	unsigned long mem_available = 0;
	unsigned long swap_total = 0;
	unsigned long swap_free = 0;

	FILE *meminfo_fp = fopen(MEMINFO_FILEPATH, "r");
	if (!meminfo_fp) {
		ERR("failed to open " MEMINFO_FILEPATH);
		return -1;
	}

	while (fgets(line, sizeof(line), meminfo_fp)) {
		if (sscanf(line, "MemTotal: %lu", &mem_total) == 1)
			usage->total = mem_total;
		else if (sscanf(line, "MemFree: %lu", &mem_free) == 1)
			usage->free = mem_free;
		else if (sscanf(line, "Cached: %lu", &cached) == 1)
			usage->cache = cached;
		else if (sscanf(line, "MemAvailable: %lu", &value) == 1)
			mem_available = value;
		else if (sscanf(line, "SwapTotal: %lu", &value) == 1)
			swap_total = value;
		else if (sscanf(line, "SwapFree: %lu", &value) == 1)
			swap_free = value;
	}

	// Calculate used memory
	// MemAvailable is exposed since Linux 3.14, so handle also previous
	// kernel versions
	usage->used = 0;
	if (mem_available > 0) {
		if (mem_total > mem_available)
			usage->used = mem_total - mem_available;
	} else {
		if ((mem_total > mem_free) && ((mem_total - mem_free) > cached))
			usage->used = mem_total - mem_free - cached;
	}

	usage->swap = (swap_total > swap_free) ? (swap_total - swap_free) : 0;

	fclose(meminfo_fp);

	return 0;
}

int procfs_read_process_memory_usage(int pid, struct procfs_process_memory_usage_info *usage)
{
	ON_NULL_RETURN_VAL(usage, -1);
	ON_TRUE_RETURN_VAL(pid <= 0, -1);

	char smapspath[64], line[256];
	unsigned long value;

	snprintf(smapspath, sizeof(smapspath), SMAPS_FILEPATH, pid);

	FILE *smaps_fp = fopen(smapspath, "r");
	if (!smaps_fp) {
		 ERR("failed to open path: %s", smapspath);
		 return -1;
	}

	memset(usage, 0x0, sizeof(struct procfs_process_memory_usage_info));

	while (fgets(line, sizeof(line), smaps_fp)) {
		if (sscanf(line, "Size: %lu", &value) == 1)
			usage->vsz += value;
		else if (sscanf(line, "Rss: %lu", &value) == 1)
			usage->rss += value;
		else if (sscanf(line, "Pss: %lu", &value) == 1)
			usage->pss += value;
		else if (sscanf(line, "Shared_Clean: %lu", &value) == 1)
			usage->shared_clean += value;
		else if (sscanf(line, "Shared_Dirty: %lu", &value) == 1)
			usage->shared_dirty += value;
		else if (sscanf(line, "Private_Clean: %lu", &value) == 1)
			usage->private_clean += value;
		else if (sscanf(line, "Private_Dirty: %lu", &value) == 1)
			usage->private_dirty += value;
	}

	fclose(smaps_fp);

	return 0;
}

int procfs_read_process_cpu_usage(int pid, struct procfs_process_cpu_usage_info *usage)
{
	ON_NULL_RETURN_VAL(usage, -1);
	ON_TRUE_RETURN_VAL(pid <= 0, -1);

	char statpath[64];
	unsigned long long utime, stime;

	snprintf(statpath, sizeof(statpath), PIDSTAT_FILEPATH, pid);

	FILE *stat_fp = fopen(statpath, "r");
	if (!stat_fp) {
		ERR("failed to open %s", statpath);
		return -1;
	}

	if (fscanf(stat_fp, "%*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s") < 0) {
		ERR("reading pid stat file failed");
		fclose(stat_fp);
		return -1;
	}

	if (fscanf(stat_fp, "%llu %llu", &utime, &stime) != 2) {
		ERR("reading pid stat file failed");
		fclose(stat_fp);
		return -1;
	}

	usage->utime = utime;
	usage->stime = stime;

	fclose(stat_fp);
	return 0;
}

int procfs_read_uptime(unsigned long *uptime)
{
	ON_NULL_RETURN_VAL(uptime, -1);

	double duptime;

	FILE *uptime_fp = fopen(UPTIME_FILEPATH, "r");
	if (!uptime_fp) {
		ERR("failed to open " UPTIME_FILEPATH);
		return -1;
	}

	if (fscanf(uptime_fp, "%lf ", &duptime) != 1) {
		ERR("failed to read " UPTIME_FILEPATH);
		fclose(uptime_fp);
		return -1;
	}

	fclose(uptime_fp);
	*uptime = (unsigned long)duptime;

	return 0;
}

int procfs_read_cpu_count(int *cpu_count)
{
	ON_NULL_RETURN_VAL(cpu_count, -1);

	int cpus, dummy;

	FILE *possible_fp = fopen(POSSIBLE_CPUS_FILEPATH, "r");
	if (!possible_fp) {
		ERR("failed to open " POSSIBLE_CPUS_FILEPATH);
		return -1;
	}

	if (fscanf(possible_fp, "%d-%d", &dummy, &cpus) != 2) {
		ERR("failed to read " POSSIBLE_CPUS_FILEPATH);
		fclose(possible_fp);
		return -1;
	}

	*cpu_count = cpus + 1;

	fclose(possible_fp);

	return 0;
}

bool _procfs_dirname_parse_pid(const char *dirname, int *pid)
{
	int parsed_pid;

	if (!isdigit(*dirname))
		return false;

	if (sscanf(dirname, "%d", &parsed_pid) != 1) {
		return false;
	}
	*pid = parsed_pid;
	return true;
}

int procfs_iterate_pids(procfs_pid_iterator_cb iterator, void *user_data)
{
	ON_NULL_RETURN_VAL(iterator, -1);

	struct dirent *entry;
	int pid;

	DIR *dir = opendir(PROC_DIR_PATH);
	if (!dir) {
		ERR("opendir failed.");
		return -1;
	}

	// According to POSIX docs readdir is not-thread safe.
	// however in glib recent implementations readdir
	// is thread safe, so we can avoid using locks here.
	while ((entry = readdir(dir)) != NULL) {
		if (!_procfs_dirname_parse_pid(entry->d_name, &pid))
			continue;

		if (iterator(pid, user_data))
			continue;
		else
			break;;
	}

	closedir(dir);
	return 0;
}

int procfs_read_exe(int pid, char **exe)
{
	ON_TRUE_RETURN_VAL(pid < 0, -1);
	ON_NULL_RETURN_VAL(exe, -1);

	char buf[256];
	size_t size = 32;
	char *buffer = NULL;
	int ret;

	snprintf(buf, sizeof(buf), PROC_PID_EXE_PATH, pid);

	do
	{
		size *= 2;
		char *tmp = realloc(buffer, size);
		if (!tmp) {
			free(buffer);
			return -1;
		}
		buffer = tmp;
		ret = readlink(buf, buffer, size);
		if (ret == -1) {
			free(buffer);
			return -1;
		}
		buffer[ret] = '\0';
	} while (ret >= size);

	*exe = buffer;
	return 0;
}

int procfs_read_cmdline(int pid, char **cmdline)
{
	ON_TRUE_RETURN_VAL(pid < 0, -1);
	ON_NULL_RETURN_VAL(cmdline, -1);

	char buf[64];
	int read, read_total = 0;
	char *cmd = NULL;

	snprintf(buf, sizeof(buf), PROC_PID_CMDLINE_PATH, pid);

	FILE *cmdline_fp = fopen(buf, "r");
	if (!cmdline_fp) {
		ERR("failed to open %s", buf);
		return -1;
	}

	while ((read = fread(buf, 1, sizeof(buf), cmdline_fp)) != 0) {
		char *tmp = realloc(cmd, read_total + read + 1);
		if (!tmp) {
			fclose(cmdline_fp);
			free(cmd);
			return -1;
		}
		cmd = tmp;
		memcpy(cmd + read_total, buf, read);
		read_total += read;
	}

	if (read_total == 0) {
		fclose(cmdline_fp);
		*cmdline = NULL;
		return 0;
	}

	// clear string from end-of-string characters
	for (int i = 0; i < read_total; ++i) {
		if (cmd[i] == '\0')
			cmd[i] = ' ';
	}
	cmd[read_total] = '\0';

	fclose(cmdline_fp);
	*cmdline = cmd;
	return 0;
}