Fix: use utils_get_home_dir for anonymous trace chunk path
[lttng-tools.git] / src / common / utils.c
CommitLineData
81b86775
DG
1/*
2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
66495845 3 * Copyright (C) 2013 - Raphaël Beamonte <raphael.beamonte@gmail.com>
8db0dc00 4 * Copyright (C) 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
81b86775
DG
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License, version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * more details.
14 *
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
6c1c0768 20#define _LGPL_SOURCE
35f90c40 21#include <assert.h>
81b86775
DG
22#include <ctype.h>
23#include <fcntl.h>
24#include <limits.h>
25#include <stdlib.h>
2d851108 26#include <sys/stat.h>
0c7bcad5 27#include <sys/types.h>
2d851108 28#include <unistd.h>
fe4477ee 29#include <inttypes.h>
6c71277b 30#include <grp.h>
fb198a11 31#include <pwd.h>
c9cb3e7d 32#include <sys/file.h>
a98e236e 33#include <unistd.h>
81b86775
DG
34
35#include <common/common.h>
e3091d6a 36#include <common/readwrite.h>
fe4477ee 37#include <common/runas.h>
e8fa9fb0 38#include <common/compat/getenv.h>
f5436bfc 39#include <common/compat/string.h>
5a2451c9 40#include <common/compat/dirent.h>
a42089bd 41#include <common/compat/directory-handle.h>
6710e5aa 42#include <common/dynamic-buffer.h>
38bdfdca 43#include <common/string-utils/format.h>
d7c23421 44#include <lttng/constant.h>
81b86775
DG
45
46#include "utils.h"
feb0f3e5 47#include "defaults.h"
20a8da1f 48#include "time.h"
81b86775 49
e3091d6a
FD
50#define PROC_MEMINFO_PATH "/proc/meminfo"
51#define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
52#define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
53
54/* The length of the longest field of `/proc/meminfo`. */
55#define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
56
57#if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
58#define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
59#else
60#error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
61#endif
62
5154230f
RB
63/*
64 * Return a partial realpath(3) of the path even if the full path does not
65 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
66 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
67 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
68 * point directory does not exist.
69 * In case resolved_path is NULL, the string returned was allocated in the
70 * function and thus need to be freed by the caller. The size argument allows
71 * to specify the size of the resolved_path argument if given, or the size to
72 * allocate.
73 */
74LTTNG_HIDDEN
75char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
76{
9482daac 77 char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
5154230f
RB
78 const char *next, *prev, *end;
79
80 /* Safety net */
81 if (path == NULL) {
82 goto error;
83 }
84
85 /*
86 * Identify the end of the path, we don't want to treat the
87 * last char if it is a '/', we will just keep it on the side
88 * to be added at the end, and return a value coherent with
89 * the path given as argument
90 */
91 end = path + strlen(path);
92 if (*(end-1) == '/') {
93 end--;
94 }
95
96 /* Initiate the values of the pointers before looping */
97 next = path;
98 prev = next;
99 /* Only to ensure try_path is not NULL to enter the while */
100 try_path = (char *)next;
101
102 /* Resolve the canonical path of the first part of the path */
103 while (try_path != NULL && next != end) {
d7c23421
JG
104 char *try_path_buf = NULL;
105
5154230f
RB
106 /*
107 * If there is not any '/' left, we want to try with
108 * the full path
109 */
110 next = strpbrk(next + 1, "/");
111 if (next == NULL) {
112 next = end;
113 }
114
115 /* Cut the part we will be trying to resolve */
f5436bfc 116 cut_path = lttng_strndup(path, next - path);
d9dbcf5e 117 if (cut_path == NULL) {
f5436bfc 118 PERROR("lttng_strndup");
d9dbcf5e
MD
119 goto error;
120 }
5154230f 121
d7c23421
JG
122 try_path_buf = zmalloc(LTTNG_PATH_MAX);
123 if (!try_path_buf) {
124 PERROR("zmalloc");
125 goto error;
126 }
127
5154230f 128 /* Try to resolve this part */
f3472d9a 129 try_path = realpath((char *) cut_path, try_path_buf);
5154230f 130 if (try_path == NULL) {
d7c23421 131 free(try_path_buf);
5154230f
RB
132 /*
133 * There was an error, we just want to be assured it
134 * is linked to an unexistent directory, if it's another
135 * reason, we spawn an error
136 */
137 switch (errno) {
138 case ENOENT:
139 /* Ignore the error */
140 break;
141 default:
142 PERROR("realpath (partial_realpath)");
143 goto error;
144 break;
145 }
146 } else {
147 /* Save the place we are before trying the next step */
d7c23421 148 try_path_buf = NULL;
5154230f
RB
149 free(try_path_prev);
150 try_path_prev = try_path;
151 prev = next;
152 }
153
154 /* Free the allocated memory */
155 free(cut_path);
c14cc491 156 cut_path = NULL;
494a8e99 157 }
5154230f
RB
158
159 /* Allocate memory for the resolved path if necessary */
160 if (resolved_path == NULL) {
161 resolved_path = zmalloc(size);
162 if (resolved_path == NULL) {
163 PERROR("zmalloc resolved path");
164 goto error;
165 }
166 }
167
168 /*
169 * If we were able to solve at least partially the path, we can concatenate
170 * what worked and what didn't work
171 */
172 if (try_path_prev != NULL) {
173 /* If we risk to concatenate two '/', we remove one of them */
174 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
175 try_path_prev[strlen(try_path_prev) - 1] = '\0';
176 }
177
178 /*
179 * Duplicate the memory used by prev in case resolved_path and
180 * path are pointers for the same memory space
181 */
182 cut_path = strdup(prev);
d9dbcf5e
MD
183 if (cut_path == NULL) {
184 PERROR("strdup");
185 goto error;
186 }
5154230f
RB
187
188 /* Concatenate the strings */
189 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
190
191 /* Free the allocated memory */
192 free(cut_path);
193 free(try_path_prev);
494a8e99
JG
194 cut_path = NULL;
195 try_path_prev = NULL;
5154230f
RB
196 /*
197 * Else, we just copy the path in our resolved_path to
198 * return it as is
199 */
200 } else {
201 strncpy(resolved_path, path, size);
202 }
203
204 /* Then we return the 'partially' resolved path */
205 return resolved_path;
206
207error:
208 free(resolved_path);
9482daac 209 free(cut_path);
b86d5f3f 210 free(try_path);
32bd4678
MJ
211 if (try_path_prev != try_path) {
212 free(try_path_prev);
213 }
5154230f
RB
214 return NULL;
215}
216
4b223a67 217static
6740483e 218int expand_double_slashes_dot_and_dotdot(char *path)
4b223a67
FD
219{
220 size_t expanded_path_len, path_len;
221 const char *curr_char, *path_last_char, *next_slash, *prev_slash;
222
223 path_len = strlen(path);
224 path_last_char = &path[path_len];
225
226 if (path_len == 0) {
4b223a67
FD
227 goto error;
228 }
229
230 expanded_path_len = 0;
231
232 /* We iterate over the provided path to expand the "//", "../" and "./" */
233 for (curr_char = path; curr_char <= path_last_char; curr_char = next_slash + 1) {
234 /* Find the next forward slash. */
235 size_t curr_token_len;
236
237 if (curr_char == path_last_char) {
238 expanded_path_len++;
239 break;
240 }
241
242 next_slash = memchr(curr_char, '/', path_last_char - curr_char);
243 if (next_slash == NULL) {
244 /* Reached the end of the provided path. */
245 next_slash = path_last_char;
246 }
247
248 /* Compute how long is the previous token. */
249 curr_token_len = next_slash - curr_char;
250 switch(curr_token_len) {
251 case 0:
252 /*
253 * The pointer has not move meaning that curr_char is
254 * pointing to a slash. It that case there is no token
255 * to copy, so continue the iteration to find the next
256 * token
257 */
258 continue;
259 case 1:
260 /*
261 * The pointer moved 1 character. Check if that
262 * character is a dot ('.'), if it is: omit it, else
263 * copy the token to the normalized path.
264 */
265 if (curr_char[0] == '.') {
266 continue;
267 }
268 break;
269 case 2:
270 /*
271 * The pointer moved 2 characters. Check if these
272 * characters are double dots ('..'). If that is the
273 * case, we need to remove the last token of the
274 * normalized path.
275 */
276 if (curr_char[0] == '.' && curr_char[1] == '.') {
277 /*
278 * Find the previous path component by
279 * using the memrchr function to find the
280 * previous forward slash and substract that
281 * len to the resulting path.
282 */
283 prev_slash = lttng_memrchr(path, '/', expanded_path_len);
284 /*
285 * If prev_slash is NULL, we reached the
286 * beginning of the path. We can't go back any
287 * further.
288 */
289 if (prev_slash != NULL) {
290 expanded_path_len = prev_slash - path;
291 }
292 continue;
293 }
294 break;
295 default:
296 break;
297 }
298
299 /*
300 * Copy the current token which is neither a '.' nor a '..'.
301 */
302 path[expanded_path_len++] = '/';
303 memcpy(&path[expanded_path_len], curr_char, curr_token_len);
304 expanded_path_len += curr_token_len;
305 }
306
307 if (expanded_path_len == 0) {
308 path[expanded_path_len++] = '/';
309 }
310
311 path[expanded_path_len] = '\0';
6740483e 312 return 0;
4b223a67 313error:
6740483e 314 return -1;
4b223a67
FD
315}
316
81b86775 317/*
3d229795
RB
318 * Make a full resolution of the given path even if it doesn't exist.
319 * This function uses the utils_partial_realpath function to resolve
320 * symlinks and relatives paths at the start of the string, and
321 * implements functionnalities to resolve the './' and '../' strings
322 * in the middle of a path. This function is only necessary because
323 * realpath(3) does not accept to resolve unexistent paths.
324 * The returned string was allocated in the function, it is thus of
325 * the responsibility of the caller to free this memory.
81b86775 326 */
90e535ef 327LTTNG_HIDDEN
4b223a67 328char *_utils_expand_path(const char *path, bool keep_symlink)
81b86775 329{
857f0d94 330 int ret;
4b223a67 331 char *absolute_path = NULL;
5de083f4 332 char *last_token;
6740483e 333 bool is_dot, is_dotdot;
81b86775
DG
334
335 /* Safety net */
336 if (path == NULL) {
337 goto error;
338 }
339
3d229795 340 /* Allocate memory for the absolute_path */
857f0d94 341 absolute_path = zmalloc(LTTNG_PATH_MAX);
3d229795 342 if (absolute_path == NULL) {
81b86775
DG
343 PERROR("zmalloc expand path");
344 goto error;
345 }
346
4b223a67 347 if (path[0] == '/') {
857f0d94
JG
348 ret = lttng_strncpy(absolute_path, path, LTTNG_PATH_MAX);
349 if (ret) {
350 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX);
351 goto error;
352 }
4b223a67
FD
353 } else {
354 /*
355 * This is a relative path. We need to get the present working
356 * directory and start the path walk from there.
357 */
857f0d94 358 char current_working_dir[LTTNG_PATH_MAX];
4b223a67 359 char *cwd_ret;
857f0d94 360
4b223a67
FD
361 cwd_ret = getcwd(current_working_dir, sizeof(current_working_dir));
362 if (!cwd_ret) {
d9dbcf5e
MD
363 goto error;
364 }
4b223a67
FD
365 /*
366 * Get the number of character in the CWD and allocate an array
367 * to can hold it and the path provided by the caller.
368 */
857f0d94
JG
369 ret = snprintf(absolute_path, LTTNG_PATH_MAX, "%s/%s",
370 current_working_dir, path);
371 if (ret >= LTTNG_PATH_MAX) {
372 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
373 current_working_dir, path, LTTNG_PATH_MAX);
374 goto error;
375 }
3d229795 376 }
116f95d9 377
4b223a67
FD
378 if (keep_symlink) {
379 /* Resolve partially our path */
3d229795 380 absolute_path = utils_partial_realpath(absolute_path,
857f0d94 381 absolute_path, LTTNG_PATH_MAX);
116f95d9 382 }
81b86775 383
6740483e
JG
384 ret = expand_double_slashes_dot_and_dotdot(absolute_path);
385 if (ret) {
4b223a67
FD
386 goto error;
387 }
388
5de083f4
RB
389 /* Identify the last token */
390 last_token = strrchr(absolute_path, '/');
391
392 /* Verify that this token is not a relative path */
393 is_dotdot = (strcmp(last_token, "/..") == 0);
394 is_dot = (strcmp(last_token, "/.") == 0);
395
396 /* If it is, take action */
397 if (is_dot || is_dotdot) {
398 /* For both, remove this token */
399 *last_token = '\0';
400
401 /* If it was a reference to parent directory, go back one more time */
402 if (is_dotdot) {
403 last_token = strrchr(absolute_path, '/');
404
405 /* If there was only one level left, we keep the first '/' */
406 if (last_token == absolute_path) {
407 last_token++;
408 }
409
410 *last_token = '\0';
411 }
412 }
413
3d229795 414 return absolute_path;
81b86775
DG
415
416error:
3d229795 417 free(absolute_path);
81b86775
DG
418 return NULL;
419}
4b223a67
FD
420LTTNG_HIDDEN
421char *utils_expand_path(const char *path)
422{
423 return _utils_expand_path(path, true);
424}
81b86775 425
4b223a67
FD
426LTTNG_HIDDEN
427char *utils_expand_path_keep_symlink(const char *path)
428{
429 return _utils_expand_path(path, false);
430}
81b86775
DG
431/*
432 * Create a pipe in dst.
433 */
90e535ef 434LTTNG_HIDDEN
81b86775
DG
435int utils_create_pipe(int *dst)
436{
437 int ret;
438
439 if (dst == NULL) {
440 return -1;
441 }
442
443 ret = pipe(dst);
444 if (ret < 0) {
445 PERROR("create pipe");
446 }
447
448 return ret;
449}
450
451/*
452 * Create pipe and set CLOEXEC flag to both fd.
453 *
454 * Make sure the pipe opened by this function are closed at some point. Use
455 * utils_close_pipe().
456 */
90e535ef 457LTTNG_HIDDEN
81b86775
DG
458int utils_create_pipe_cloexec(int *dst)
459{
460 int ret, i;
461
462 if (dst == NULL) {
463 return -1;
464 }
465
466 ret = utils_create_pipe(dst);
467 if (ret < 0) {
468 goto error;
469 }
470
471 for (i = 0; i < 2; i++) {
472 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
473 if (ret < 0) {
474 PERROR("fcntl pipe cloexec");
475 goto error;
476 }
477 }
478
479error:
480 return ret;
481}
482
094f381c
MD
483/*
484 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
485 *
486 * Make sure the pipe opened by this function are closed at some point. Use
487 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
488 * support OSes other than Linux 2.6.23+.
489 */
490LTTNG_HIDDEN
491int utils_create_pipe_cloexec_nonblock(int *dst)
492{
493 int ret, i;
494
495 if (dst == NULL) {
496 return -1;
497 }
498
499 ret = utils_create_pipe(dst);
500 if (ret < 0) {
501 goto error;
502 }
503
504 for (i = 0; i < 2; i++) {
505 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
506 if (ret < 0) {
507 PERROR("fcntl pipe cloexec");
508 goto error;
509 }
510 /*
511 * Note: we override any flag that could have been
512 * previously set on the fd.
513 */
514 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
515 if (ret < 0) {
516 PERROR("fcntl pipe nonblock");
517 goto error;
518 }
519 }
520
521error:
522 return ret;
523}
524
81b86775
DG
525/*
526 * Close both read and write side of the pipe.
527 */
90e535ef 528LTTNG_HIDDEN
81b86775
DG
529void utils_close_pipe(int *src)
530{
531 int i, ret;
532
533 if (src == NULL) {
534 return;
535 }
536
537 for (i = 0; i < 2; i++) {
538 /* Safety check */
539 if (src[i] < 0) {
540 continue;
541 }
542
543 ret = close(src[i]);
544 if (ret) {
545 PERROR("close pipe");
546 }
547 }
548}
a4b92340
DG
549
550/*
551 * Create a new string using two strings range.
552 */
90e535ef 553LTTNG_HIDDEN
a4b92340
DG
554char *utils_strdupdelim(const char *begin, const char *end)
555{
556 char *str;
557
558 str = zmalloc(end - begin + 1);
559 if (str == NULL) {
560 PERROR("zmalloc strdupdelim");
561 goto error;
562 }
563
564 memcpy(str, begin, end - begin);
565 str[end - begin] = '\0';
566
567error:
568 return str;
569}
b662582b
DG
570
571/*
572 * Set CLOEXEC flag to the give file descriptor.
573 */
90e535ef 574LTTNG_HIDDEN
b662582b
DG
575int utils_set_fd_cloexec(int fd)
576{
577 int ret;
578
579 if (fd < 0) {
580 ret = -EINVAL;
581 goto end;
582 }
583
584 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
585 if (ret < 0) {
586 PERROR("fcntl cloexec");
587 ret = -errno;
588 }
589
590end:
591 return ret;
592}
35f90c40
DG
593
594/*
595 * Create pid file to the given path and filename.
596 */
90e535ef 597LTTNG_HIDDEN
35f90c40
DG
598int utils_create_pid_file(pid_t pid, const char *filepath)
599{
600 int ret;
601 FILE *fp;
602
603 assert(filepath);
604
605 fp = fopen(filepath, "w");
606 if (fp == NULL) {
607 PERROR("open pid file %s", filepath);
608 ret = -1;
609 goto error;
610 }
611
d1f721c5 612 ret = fprintf(fp, "%d\n", (int) pid);
35f90c40
DG
613 if (ret < 0) {
614 PERROR("fprintf pid file");
e205d79b 615 goto error;
35f90c40
DG
616 }
617
e205d79b
MD
618 if (fclose(fp)) {
619 PERROR("fclose");
620 }
d1f721c5 621 DBG("Pid %d written in file %s", (int) pid, filepath);
e205d79b 622 ret = 0;
35f90c40
DG
623error:
624 return ret;
625}
2d851108 626
c9cb3e7d
JG
627/*
628 * Create lock file to the given path and filename.
629 * Returns the associated file descriptor, -1 on error.
630 */
631LTTNG_HIDDEN
632int utils_create_lock_file(const char *filepath)
633{
634 int ret;
635 int fd;
77e7fddf 636 struct flock lock;
c9cb3e7d
JG
637
638 assert(filepath);
639
77e7fddf
MJ
640 memset(&lock, 0, sizeof(lock));
641 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
642 S_IRGRP | S_IWGRP);
c9cb3e7d
JG
643 if (fd < 0) {
644 PERROR("open lock file %s", filepath);
e6576ba2 645 fd = -1;
c9cb3e7d
JG
646 goto error;
647 }
648
649 /*
650 * Attempt to lock the file. If this fails, there is
651 * already a process using the same lock file running
652 * and we should exit.
653 */
77e7fddf
MJ
654 lock.l_whence = SEEK_SET;
655 lock.l_type = F_WRLCK;
656
657 ret = fcntl(fd, F_SETLK, &lock);
658 if (ret == -1) {
659 PERROR("fcntl lock file");
208ff148 660 ERR("Could not get lock file %s, another instance is running.",
c9cb3e7d 661 filepath);
ffb0b851
JG
662 if (close(fd)) {
663 PERROR("close lock file");
664 }
c9cb3e7d
JG
665 fd = ret;
666 goto error;
667 }
668
669error:
670 return fd;
671}
672
2d851108 673/*
d77dded2 674 * Create directory using the given path and mode.
2d851108
DG
675 *
676 * On success, return 0 else a negative error code.
677 */
90e535ef 678LTTNG_HIDDEN
d77dded2
JG
679int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
680{
681 int ret;
a42089bd 682 struct lttng_directory_handle handle;
6992f9f1 683 const struct lttng_credentials creds = {
a42089bd
JG
684 .uid = (uid_t) uid,
685 .gid = (gid_t) gid,
686 };
687
d44a713b
JG
688 ret = lttng_directory_handle_init(&handle, NULL);
689 if (ret) {
690 goto end;
691 }
a42089bd
JG
692 ret = lttng_directory_handle_create_subdirectory_as_user(
693 &handle, path, mode,
694 (uid >= 0 || gid >= 0) ? &creds : NULL);
695 lttng_directory_handle_fini(&handle);
d44a713b 696end:
2d851108
DG
697 return ret;
698}
fe4477ee 699
d77dded2
JG
700/*
701 * Recursively create directory using the given path and mode, under the
702 * provided uid and gid.
703 *
704 * On success, return 0 else a negative error code.
705 */
706LTTNG_HIDDEN
707int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
708{
709 int ret;
a42089bd 710 struct lttng_directory_handle handle;
6992f9f1 711 const struct lttng_credentials creds = {
a42089bd
JG
712 .uid = (uid_t) uid,
713 .gid = (gid_t) gid,
714 };
715
d44a713b
JG
716 ret = lttng_directory_handle_init(&handle, NULL);
717 if (ret) {
718 goto end;
719 }
a42089bd
JG
720 ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
721 &handle, path, mode,
722 (uid >= 0 || gid >= 0) ? &creds : NULL);
723 lttng_directory_handle_fini(&handle);
d44a713b 724end:
d77dded2
JG
725 return ret;
726}
727
fe4477ee 728/*
38bdfdca 729 * out_stream_path is the output parameter.
fe4477ee
JD
730 *
731 * Return 0 on success or else a negative value.
732 */
38bdfdca
JG
733LTTNG_HIDDEN
734int utils_stream_file_path(const char *path_name, const char *file_name,
735 uint64_t size, uint64_t count, const char *suffix,
736 char *out_stream_path, size_t stream_path_len)
fe4477ee 737{
7591bab1 738 int ret;
38bdfdca
JG
739 char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
740 const char *path_separator;
fe4477ee 741
38bdfdca
JG
742 if (path_name && path_name[strlen(path_name) - 1] == '/') {
743 path_separator = "";
744 } else {
745 path_separator = "/";
fe4477ee
JD
746 }
747
38bdfdca
JG
748 path_name = path_name ? : "";
749 suffix = suffix ? : "";
750 if (size > 0) {
751 ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
752 count);
753 assert(ret > 0 && ret < sizeof(count_str));
309167d2
JD
754 }
755
38bdfdca
JG
756 ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
757 path_name, path_separator, file_name, count_str,
758 suffix);
759 if (ret < 0 || ret >= stream_path_len) {
760 ERR("Truncation occurred while formatting stream path");
761 ret = -1;
fe4477ee 762 } else {
38bdfdca 763 ret = 0;
7591bab1 764 }
7591bab1
MD
765 return ret;
766}
767
768/*
769 * Create the stream file on disk.
770 *
771 * Return 0 on success or else a negative value.
772 */
773LTTNG_HIDDEN
774int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
775 uint64_t count, int uid, int gid, char *suffix)
776{
777 int ret, flags, mode;
38bdfdca 778 char path[LTTNG_PATH_MAX];
7591bab1 779
38bdfdca
JG
780 ret = utils_stream_file_path(path_name, file_name,
781 size, count, suffix, path, sizeof(path));
7591bab1
MD
782 if (ret < 0) {
783 goto error;
fe4477ee
JD
784 }
785
d3ecc550
JD
786 /*
787 * With the session rotation feature on the relay, we might need to seek
788 * and truncate a tracefile, so we need read and write access.
789 */
790 flags = O_RDWR | O_CREAT | O_TRUNC;
0f907de1 791 /* Open with 660 mode */
be96a7d1
DG
792 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
793
794 if (uid < 0 || gid < 0) {
7591bab1 795 ret = open(path, flags, mode);
be96a7d1 796 } else {
7591bab1 797 ret = run_as_open(path, flags, mode, uid, gid);
be96a7d1 798 }
7591bab1 799 if (ret < 0) {
fe4477ee 800 PERROR("open stream path %s", path);
fe4477ee 801 }
7591bab1
MD
802error:
803 return ret;
804}
fe4477ee 805
7591bab1
MD
806/*
807 * Unlink the stream tracefile from disk.
808 *
809 * Return 0 on success or else a negative value.
810 */
811LTTNG_HIDDEN
812int utils_unlink_stream_file(const char *path_name, char *file_name, uint64_t size,
813 uint64_t count, int uid, int gid, char *suffix)
814{
815 int ret;
38bdfdca 816 char path[LTTNG_PATH_MAX];
7591bab1 817
38bdfdca
JG
818 ret = utils_stream_file_path(path_name, file_name, size, count, suffix,
819 path, sizeof(path));
7591bab1
MD
820 if (ret < 0) {
821 goto error;
822 }
823 if (uid < 0 || gid < 0) {
824 ret = unlink(path);
825 } else {
826 ret = run_as_unlink(path, uid, gid);
7591bab1
MD
827 }
828 if (ret < 0) {
829 goto error;
830 }
fe4477ee 831error:
7591bab1 832 DBG("utils_unlink_stream_file %s returns %d", path, ret);
fe4477ee
JD
833 return ret;
834}
835
70d0b120
SM
836/**
837 * Parse a string that represents a size in human readable format. It
5983a922 838 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
839 *
840 * The suffix multiply the integer by:
841 * 'k': 1024
842 * 'M': 1024^2
843 * 'G': 1024^3
844 *
845 * @param str The string to parse.
5983a922 846 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 847 * resulting size.
70d0b120
SM
848 *
849 * @return 0 on success, -1 on failure.
850 */
00a52467 851LTTNG_HIDDEN
5983a922 852int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 853{
70d0b120 854 int ret;
5983a922 855 uint64_t base_size;
70d0b120 856 long shift = 0;
5983a922
SM
857 const char *str_end;
858 char *num_end;
70d0b120
SM
859
860 if (!str) {
5983a922 861 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
862 ret = -1;
863 goto end;
864 }
865
5983a922
SM
866 /* strtoull will accept a negative number, but we don't want to. */
867 if (strchr(str, '-') != NULL) {
868 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 869 ret = -1;
5983a922 870 goto end;
70d0b120
SM
871 }
872
5983a922
SM
873 /* str_end will point to the \0 */
874 str_end = str + strlen(str);
70d0b120 875 errno = 0;
5983a922 876 base_size = strtoull(str, &num_end, 0);
70d0b120 877 if (errno != 0) {
5983a922 878 PERROR("utils_parse_size_suffix strtoull");
70d0b120 879 ret = -1;
5983a922
SM
880 goto end;
881 }
882
883 if (num_end == str) {
884 /* strtoull parsed nothing, not good. */
885 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
886 ret = -1;
887 goto end;
888 }
889
890 /* Check if a prefix is present. */
891 switch (*num_end) {
892 case 'G':
893 shift = GIBI_LOG2;
894 num_end++;
895 break;
896 case 'M': /* */
897 shift = MEBI_LOG2;
898 num_end++;
899 break;
900 case 'K':
901 case 'k':
902 shift = KIBI_LOG2;
903 num_end++;
904 break;
905 case '\0':
906 break;
907 default:
908 DBG("utils_parse_size_suffix: invalid suffix.");
909 ret = -1;
910 goto end;
911 }
912
913 /* Check for garbage after the valid input. */
914 if (num_end != str_end) {
915 DBG("utils_parse_size_suffix: Garbage after size string.");
916 ret = -1;
917 goto end;
70d0b120
SM
918 }
919
920 *size = base_size << shift;
921
922 /* Check for overflow */
923 if ((*size >> shift) != base_size) {
5983a922 924 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 925 ret = -1;
5983a922 926 goto end;
70d0b120
SM
927 }
928
929 ret = 0;
70d0b120
SM
930end:
931 return ret;
932}
cfa9a5a2 933
7010c033
SM
934/**
935 * Parse a string that represents a time in human readable format. It
c275dec9
JR
936 * supports decimal integers suffixed by:
937 * "us" for microsecond,
938 * "ms" for millisecond,
939 * "s" for second,
940 * "m" for minute,
941 * "h" for hour
7010c033
SM
942 *
943 * The suffix multiply the integer by:
c275dec9
JR
944 * "us" : 1
945 * "ms" : 1000
946 * "s" : 1000000
947 * "m" : 60000000
948 * "h" : 3600000000
7010c033
SM
949 *
950 * Note that unit-less numbers are assumed to be microseconds.
951 *
952 * @param str The string to parse, assumed to be NULL-terminated.
953 * @param time_us Pointer to a uint64_t that will be filled with the
954 * resulting time in microseconds.
955 *
956 * @return 0 on success, -1 on failure.
957 */
958LTTNG_HIDDEN
959int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
960{
961 int ret;
962 uint64_t base_time;
c275dec9 963 uint64_t multiplier = 1;
7010c033
SM
964 const char *str_end;
965 char *num_end;
966
967 if (!str) {
968 DBG("utils_parse_time_suffix: received a NULL string.");
969 ret = -1;
970 goto end;
971 }
972
973 /* strtoull will accept a negative number, but we don't want to. */
974 if (strchr(str, '-') != NULL) {
975 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
976 ret = -1;
977 goto end;
978 }
979
980 /* str_end will point to the \0 */
981 str_end = str + strlen(str);
982 errno = 0;
983 base_time = strtoull(str, &num_end, 10);
984 if (errno != 0) {
985 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
986 ret = -1;
987 goto end;
988 }
989
990 if (num_end == str) {
991 /* strtoull parsed nothing, not good. */
992 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
993 ret = -1;
994 goto end;
995 }
996
997 /* Check if a prefix is present. */
998 switch (*num_end) {
999 case 'u':
c275dec9
JR
1000 /*
1001 * Microsecond (us)
1002 *
1003 * Skip the "us" if the string matches the "us" suffix,
1004 * otherwise let the check for the end of the string handle
1005 * the error reporting.
1006 */
1007 if (*(num_end + 1) == 's') {
1008 num_end += 2;
1009 }
7010c033
SM
1010 break;
1011 case 'm':
c275dec9
JR
1012 if (*(num_end + 1) == 's') {
1013 /* Millisecond (ms) */
1014 multiplier = USEC_PER_MSEC;
1015 /* Skip the 's' */
1016 num_end++;
1017 } else {
1018 /* Minute (m) */
1019 multiplier = USEC_PER_MINUTE;
1020 }
1021 num_end++;
7010c033
SM
1022 break;
1023 case 's':
c275dec9
JR
1024 /* Second */
1025 multiplier = USEC_PER_SEC;
1026 num_end++;
1027 break;
1028 case 'h':
1029 /* Hour */
1030 multiplier = USEC_PER_HOURS;
7010c033
SM
1031 num_end++;
1032 break;
1033 case '\0':
1034 break;
1035 default:
1036 DBG("utils_parse_time_suffix: invalid suffix.");
1037 ret = -1;
1038 goto end;
1039 }
1040
1041 /* Check for garbage after the valid input. */
1042 if (num_end != str_end) {
1043 DBG("utils_parse_time_suffix: Garbage after time string.");
1044 ret = -1;
1045 goto end;
1046 }
1047
1048 *time_us = base_time * multiplier;
1049
1050 /* Check for overflow */
1051 if ((*time_us / multiplier) != base_time) {
1052 DBG("utils_parse_time_suffix: oops, overflow detected.");
1053 ret = -1;
1054 goto end;
1055 }
1056
1057 ret = 0;
1058end:
1059 return ret;
1060}
1061
cfa9a5a2
DG
1062/*
1063 * fls: returns the position of the most significant bit.
1064 * Returns 0 if no bit is set, else returns the position of the most
1065 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1066 */
1067#if defined(__i386) || defined(__x86_64)
1068static inline unsigned int fls_u32(uint32_t x)
1069{
1070 int r;
1071
1072 asm("bsrl %1,%0\n\t"
1073 "jnz 1f\n\t"
1074 "movl $-1,%0\n\t"
1075 "1:\n\t"
1076 : "=r" (r) : "rm" (x));
1077 return r + 1;
1078}
1079#define HAS_FLS_U32
1080#endif
1081
db5be0a3
JG
1082#if defined(__x86_64)
1083static inline
1084unsigned int fls_u64(uint64_t x)
1085{
1086 long r;
1087
1088 asm("bsrq %1,%0\n\t"
1089 "jnz 1f\n\t"
1090 "movq $-1,%0\n\t"
1091 "1:\n\t"
1092 : "=r" (r) : "rm" (x));
1093 return r + 1;
1094}
1095#define HAS_FLS_U64
1096#endif
1097
1098#ifndef HAS_FLS_U64
1099static __attribute__((unused))
1100unsigned int fls_u64(uint64_t x)
1101{
1102 unsigned int r = 64;
1103
1104 if (!x)
1105 return 0;
1106
1107 if (!(x & 0xFFFFFFFF00000000ULL)) {
1108 x <<= 32;
1109 r -= 32;
1110 }
1111 if (!(x & 0xFFFF000000000000ULL)) {
1112 x <<= 16;
1113 r -= 16;
1114 }
1115 if (!(x & 0xFF00000000000000ULL)) {
1116 x <<= 8;
1117 r -= 8;
1118 }
1119 if (!(x & 0xF000000000000000ULL)) {
1120 x <<= 4;
1121 r -= 4;
1122 }
1123 if (!(x & 0xC000000000000000ULL)) {
1124 x <<= 2;
1125 r -= 2;
1126 }
1127 if (!(x & 0x8000000000000000ULL)) {
1128 x <<= 1;
1129 r -= 1;
1130 }
1131 return r;
1132}
1133#endif
1134
cfa9a5a2
DG
1135#ifndef HAS_FLS_U32
1136static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1137{
1138 unsigned int r = 32;
1139
1140 if (!x) {
1141 return 0;
1142 }
1143 if (!(x & 0xFFFF0000U)) {
1144 x <<= 16;
1145 r -= 16;
1146 }
1147 if (!(x & 0xFF000000U)) {
1148 x <<= 8;
1149 r -= 8;
1150 }
1151 if (!(x & 0xF0000000U)) {
1152 x <<= 4;
1153 r -= 4;
1154 }
1155 if (!(x & 0xC0000000U)) {
1156 x <<= 2;
1157 r -= 2;
1158 }
1159 if (!(x & 0x80000000U)) {
1160 x <<= 1;
1161 r -= 1;
1162 }
1163 return r;
1164}
1165#endif
1166
1167/*
1168 * Return the minimum order for which x <= (1UL << order).
1169 * Return -1 if x is 0.
1170 */
1171LTTNG_HIDDEN
1172int utils_get_count_order_u32(uint32_t x)
1173{
1174 if (!x) {
1175 return -1;
1176 }
1177
1178 return fls_u32(x - 1);
1179}
feb0f3e5 1180
db5be0a3
JG
1181/*
1182 * Return the minimum order for which x <= (1UL << order).
1183 * Return -1 if x is 0.
1184 */
1185LTTNG_HIDDEN
1186int utils_get_count_order_u64(uint64_t x)
1187{
1188 if (!x) {
1189 return -1;
1190 }
1191
1192 return fls_u64(x - 1);
1193}
1194
feb0f3e5
AM
1195/**
1196 * Obtain the value of LTTNG_HOME environment variable, if exists.
1197 * Otherwise returns the value of HOME.
1198 */
00a52467 1199LTTNG_HIDDEN
feb0f3e5
AM
1200char *utils_get_home_dir(void)
1201{
1202 char *val = NULL;
04135dbd
DG
1203 struct passwd *pwd;
1204
e8fa9fb0 1205 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
feb0f3e5 1206 if (val != NULL) {
04135dbd
DG
1207 goto end;
1208 }
e8fa9fb0 1209 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
04135dbd
DG
1210 if (val != NULL) {
1211 goto end;
feb0f3e5 1212 }
04135dbd
DG
1213
1214 /* Fallback on the password file entry. */
1215 pwd = getpwuid(getuid());
1216 if (!pwd) {
1217 goto end;
1218 }
1219 val = pwd->pw_dir;
1220
1221 DBG3("Home directory is '%s'", val);
1222
1223end:
1224 return val;
feb0f3e5 1225}
26fe5938 1226
fb198a11
JG
1227/**
1228 * Get user's home directory. Dynamically allocated, must be freed
1229 * by the caller.
1230 */
1231LTTNG_HIDDEN
1232char *utils_get_user_home_dir(uid_t uid)
1233{
1234 struct passwd pwd;
1235 struct passwd *result;
1236 char *home_dir = NULL;
1237 char *buf = NULL;
1238 long buflen;
1239 int ret;
1240
1241 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1242 if (buflen == -1) {
1243 goto end;
1244 }
1245retry:
1246 buf = zmalloc(buflen);
1247 if (!buf) {
1248 goto end;
1249 }
1250
1251 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1252 if (ret || !result) {
1253 if (ret == ERANGE) {
1254 free(buf);
1255 buflen *= 2;
1256 goto retry;
1257 }
1258 goto end;
1259 }
1260
1261 home_dir = strdup(pwd.pw_dir);
1262end:
1263 free(buf);
1264 return home_dir;
1265}
1266
26fe5938
DG
1267/*
1268 * With the given format, fill dst with the time of len maximum siz.
1269 *
1270 * Return amount of bytes set in the buffer or else 0 on error.
1271 */
1272LTTNG_HIDDEN
1273size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1274{
1275 size_t ret;
1276 time_t rawtime;
1277 struct tm *timeinfo;
1278
1279 assert(format);
1280 assert(dst);
1281
1282 /* Get date and time for session path */
1283 time(&rawtime);
1284 timeinfo = localtime(&rawtime);
1285 ret = strftime(dst, len, format, timeinfo);
1286 if (ret == 0) {
68e6efdd 1287 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
1288 dst, len);
1289 }
1290
1291 return ret;
1292}
6c71277b
MD
1293
1294/*
6710e5aa
JR
1295 * Return 0 on success and set *gid to the group_ID matching the passed name.
1296 * Else -1 if it cannot be found or an error occurred.
6c71277b
MD
1297 */
1298LTTNG_HIDDEN
6710e5aa 1299int utils_get_group_id(const char *name, bool warn, gid_t *gid)
6c71277b 1300{
6710e5aa
JR
1301 static volatile int warn_once;
1302 int ret;
1303 long sys_len;
1304 size_t len;
1305 struct group grp;
1306 struct group *result;
1307 struct lttng_dynamic_buffer buffer;
1308
1309 /* Get the system limit, if it exists. */
1310 sys_len = sysconf(_SC_GETGR_R_SIZE_MAX);
1311 if (sys_len == -1) {
1312 len = 1024;
1313 } else {
1314 len = (size_t) sys_len;
1315 }
1316
1317 lttng_dynamic_buffer_init(&buffer);
1318 ret = lttng_dynamic_buffer_set_size(&buffer, len);
1319 if (ret) {
1320 ERR("Failed to allocate group info buffer");
1321 ret = -1;
1322 goto error;
1323 }
6c71277b 1324
6710e5aa
JR
1325 while ((ret = getgrnam_r(name, &grp, buffer.data, buffer.size, &result)) == ERANGE) {
1326 const size_t new_len = 2 * buffer.size;
6c71277b 1327
6710e5aa
JR
1328 /* Buffer is not big enough, increase its size. */
1329 if (new_len < buffer.size) {
1330 ERR("Group info buffer size overflow");
1331 ret = -1;
1332 goto error;
1333 }
1334
1335 ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
1336 if (ret) {
1337 ERR("Failed to grow group info buffer to %zu bytes",
1338 new_len);
1339 ret = -1;
1340 goto error;
6c71277b 1341 }
6c71277b 1342 }
6710e5aa
JR
1343 if (ret) {
1344 PERROR("Failed to get group file entry for group name \"%s\"",
1345 name);
1346 ret = -1;
1347 goto error;
1348 }
1349
1350 /* Group not found. */
1351 if (!result) {
1352 ret = -1;
1353 goto error;
1354 }
1355
1356 *gid = result->gr_gid;
1357 ret = 0;
1358
1359error:
1360 if (ret && warn && !warn_once) {
1361 WARN("No tracing group detected");
1362 warn_once = 1;
1363 }
1364 lttng_dynamic_buffer_reset(&buffer);
1365 return ret;
6c71277b 1366}
8db0dc00
JG
1367
1368/*
1369 * Return a newly allocated option string. This string is to be used as the
1370 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1371 * of elements in the long_options array. Returns NULL if the string's
1372 * allocation fails.
1373 */
1374LTTNG_HIDDEN
1375char *utils_generate_optstring(const struct option *long_options,
1376 size_t opt_count)
1377{
1378 int i;
1379 size_t string_len = opt_count, str_pos = 0;
1380 char *optstring;
1381
1382 /*
1383 * Compute the necessary string length. One letter per option, two when an
1384 * argument is necessary, and a trailing NULL.
1385 */
1386 for (i = 0; i < opt_count; i++) {
1387 string_len += long_options[i].has_arg ? 1 : 0;
1388 }
1389
1390 optstring = zmalloc(string_len);
1391 if (!optstring) {
1392 goto end;
1393 }
1394
1395 for (i = 0; i < opt_count; i++) {
1396 if (!long_options[i].name) {
1397 /* Got to the trailing NULL element */
1398 break;
1399 }
1400
a596dcb9
JG
1401 if (long_options[i].val != '\0') {
1402 optstring[str_pos++] = (char) long_options[i].val;
1403 if (long_options[i].has_arg) {
1404 optstring[str_pos++] = ':';
1405 }
8db0dc00
JG
1406 }
1407 }
1408
1409end:
1410 return optstring;
1411}
3d071855
MD
1412
1413/*
1414 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
9529ec1b 1415 * any file. Try to rmdir any empty directory within the hierarchy.
3d071855
MD
1416 */
1417LTTNG_HIDDEN
1418int utils_recursive_rmdir(const char *path)
1419{
fcde531a
JG
1420 int ret;
1421 struct lttng_directory_handle handle;
7a946beb 1422
fcde531a
JG
1423 ret = lttng_directory_handle_init(&handle, NULL);
1424 if (ret) {
1425 goto end;
3d071855 1426 }
fcde531a
JG
1427 ret = lttng_directory_handle_remove_subdirectory(&handle, path);
1428 lttng_directory_handle_fini(&handle);
3d071855 1429end:
3d071855
MD
1430 return ret;
1431}
93ec662e
JD
1432
1433LTTNG_HIDDEN
1434int utils_truncate_stream_file(int fd, off_t length)
1435{
1436 int ret;
a5df8828 1437 off_t lseek_ret;
93ec662e
JD
1438
1439 ret = ftruncate(fd, length);
1440 if (ret < 0) {
1441 PERROR("ftruncate");
1442 goto end;
1443 }
a5df8828
GL
1444 lseek_ret = lseek(fd, length, SEEK_SET);
1445 if (lseek_ret < 0) {
93ec662e 1446 PERROR("lseek");
a5df8828 1447 ret = -1;
93ec662e
JD
1448 goto end;
1449 }
93ec662e
JD
1450end:
1451 return ret;
1452}
4ba92f18
PP
1453
1454static const char *get_man_bin_path(void)
1455{
b7dce40d 1456 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
4ba92f18
PP
1457
1458 if (env_man_path) {
1459 return env_man_path;
1460 }
1461
1462 return DEFAULT_MAN_BIN_PATH;
1463}
1464
1465LTTNG_HIDDEN
4fc83d94
PP
1466int utils_show_help(int section, const char *page_name,
1467 const char *help_msg)
4ba92f18
PP
1468{
1469 char section_string[8];
1470 const char *man_bin_path = get_man_bin_path();
4fc83d94
PP
1471 int ret = 0;
1472
1473 if (help_msg) {
1474 printf("%s", help_msg);
1475 goto end;
1476 }
4ba92f18
PP
1477
1478 /* Section integer -> section string */
1479 ret = sprintf(section_string, "%d", section);
1480 assert(ret > 0 && ret < 8);
1481
1482 /*
1483 * Execute man pager.
1484 *
b07e7ef0 1485 * We provide -M to man here because LTTng-tools can
4ba92f18
PP
1486 * be installed outside /usr, in which case its man pages are
1487 * not located in the default /usr/share/man directory.
1488 */
b07e7ef0 1489 ret = execlp(man_bin_path, "man", "-M", MANPATH,
4ba92f18 1490 section_string, page_name, NULL);
4fc83d94
PP
1491
1492end:
4ba92f18
PP
1493 return ret;
1494}
e3091d6a
FD
1495
1496static
1497int read_proc_meminfo_field(const char *field, size_t *value)
1498{
1499 int ret;
1500 FILE *proc_meminfo;
1501 char name[PROC_MEMINFO_FIELD_MAX_NAME_LEN] = {};
1502
1503 proc_meminfo = fopen(PROC_MEMINFO_PATH, "r");
1504 if (!proc_meminfo) {
1505 PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
1506 ret = -1;
1507 goto fopen_error;
1508 }
1509
1510 /*
1511 * Read the contents of /proc/meminfo line by line to find the right
1512 * field.
1513 */
1514 while (!feof(proc_meminfo)) {
1515 unsigned long value_kb;
1516
1517 ret = fscanf(proc_meminfo,
1518 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n",
1519 name, &value_kb);
1520 if (ret == EOF) {
1521 /*
1522 * fscanf() returning EOF can indicate EOF or an error.
1523 */
1524 if (ferror(proc_meminfo)) {
1525 PERROR("Failed to parse " PROC_MEMINFO_PATH);
1526 }
1527 break;
1528 }
1529
1530 if (ret == 2 && strcmp(name, field) == 0) {
1531 /*
1532 * This number is displayed in kilo-bytes. Return the
1533 * number of bytes.
1534 */
1535 *value = ((size_t) value_kb) * 1024;
1536 ret = 0;
1537 goto found;
1538 }
1539 }
1540 /* Reached the end of the file without finding the right field. */
1541 ret = -1;
1542
1543found:
1544 fclose(proc_meminfo);
1545fopen_error:
1546 return ret;
1547}
1548
1549/*
1550 * Returns an estimate of the number of bytes of memory available based on the
1551 * the information in `/proc/meminfo`. The number returned by this function is
1552 * a best guess.
1553 */
1554LTTNG_HIDDEN
1555int utils_get_memory_available(size_t *value)
1556{
1557 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value);
1558}
1559
1560/*
1561 * Returns the total size of the memory on the system in bytes based on the
1562 * the information in `/proc/meminfo`.
1563 */
1564LTTNG_HIDDEN
1565int utils_get_memory_total(size_t *value)
1566{
1567 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value);
1568}
This page took 0.134801 seconds and 4 git commands to generate.