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