Fix: Possible memory leak when multiple config files are loaded
[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
20#define _GNU_SOURCE
35f90c40 21#include <assert.h>
81b86775
DG
22#include <ctype.h>
23#include <fcntl.h>
24#include <limits.h>
25#include <stdlib.h>
26#include <string.h>
2d851108 27#include <sys/stat.h>
0c7bcad5 28#include <sys/types.h>
2d851108 29#include <unistd.h>
fe4477ee 30#include <inttypes.h>
6c71277b 31#include <grp.h>
fb198a11 32#include <pwd.h>
81b86775
DG
33
34#include <common/common.h>
fe4477ee 35#include <common/runas.h>
81b86775
DG
36
37#include "utils.h"
feb0f3e5 38#include "defaults.h"
81b86775 39
5154230f
RB
40/*
41 * Return a partial realpath(3) of the path even if the full path does not
42 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
43 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
44 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
45 * point directory does not exist.
46 * In case resolved_path is NULL, the string returned was allocated in the
47 * function and thus need to be freed by the caller. The size argument allows
48 * to specify the size of the resolved_path argument if given, or the size to
49 * allocate.
50 */
51LTTNG_HIDDEN
52char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
53{
54 char *cut_path, *try_path = NULL, *try_path_prev = NULL;
55 const char *next, *prev, *end;
56
57 /* Safety net */
58 if (path == NULL) {
59 goto error;
60 }
61
62 /*
63 * Identify the end of the path, we don't want to treat the
64 * last char if it is a '/', we will just keep it on the side
65 * to be added at the end, and return a value coherent with
66 * the path given as argument
67 */
68 end = path + strlen(path);
69 if (*(end-1) == '/') {
70 end--;
71 }
72
73 /* Initiate the values of the pointers before looping */
74 next = path;
75 prev = next;
76 /* Only to ensure try_path is not NULL to enter the while */
77 try_path = (char *)next;
78
79 /* Resolve the canonical path of the first part of the path */
80 while (try_path != NULL && next != end) {
81 /*
82 * If there is not any '/' left, we want to try with
83 * the full path
84 */
85 next = strpbrk(next + 1, "/");
86 if (next == NULL) {
87 next = end;
88 }
89
90 /* Cut the part we will be trying to resolve */
91 cut_path = strndup(path, next - path);
92
93 /* Try to resolve this part */
94 try_path = realpath((char *)cut_path, NULL);
95 if (try_path == NULL) {
96 /*
97 * There was an error, we just want to be assured it
98 * is linked to an unexistent directory, if it's another
99 * reason, we spawn an error
100 */
101 switch (errno) {
102 case ENOENT:
103 /* Ignore the error */
104 break;
105 default:
106 PERROR("realpath (partial_realpath)");
107 goto error;
108 break;
109 }
110 } else {
111 /* Save the place we are before trying the next step */
112 free(try_path_prev);
113 try_path_prev = try_path;
114 prev = next;
115 }
116
117 /* Free the allocated memory */
118 free(cut_path);
119 };
120
121 /* Allocate memory for the resolved path if necessary */
122 if (resolved_path == NULL) {
123 resolved_path = zmalloc(size);
124 if (resolved_path == NULL) {
125 PERROR("zmalloc resolved path");
126 goto error;
127 }
128 }
129
130 /*
131 * If we were able to solve at least partially the path, we can concatenate
132 * what worked and what didn't work
133 */
134 if (try_path_prev != NULL) {
135 /* If we risk to concatenate two '/', we remove one of them */
136 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
137 try_path_prev[strlen(try_path_prev) - 1] = '\0';
138 }
139
140 /*
141 * Duplicate the memory used by prev in case resolved_path and
142 * path are pointers for the same memory space
143 */
144 cut_path = strdup(prev);
145
146 /* Concatenate the strings */
147 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
148
149 /* Free the allocated memory */
150 free(cut_path);
151 free(try_path_prev);
152 /*
153 * Else, we just copy the path in our resolved_path to
154 * return it as is
155 */
156 } else {
157 strncpy(resolved_path, path, size);
158 }
159
160 /* Then we return the 'partially' resolved path */
161 return resolved_path;
162
163error:
164 free(resolved_path);
165 return NULL;
166}
167
81b86775 168/*
3d229795
RB
169 * Make a full resolution of the given path even if it doesn't exist.
170 * This function uses the utils_partial_realpath function to resolve
171 * symlinks and relatives paths at the start of the string, and
172 * implements functionnalities to resolve the './' and '../' strings
173 * in the middle of a path. This function is only necessary because
174 * realpath(3) does not accept to resolve unexistent paths.
175 * The returned string was allocated in the function, it is thus of
176 * the responsibility of the caller to free this memory.
81b86775 177 */
90e535ef 178LTTNG_HIDDEN
81b86775
DG
179char *utils_expand_path(const char *path)
180{
3d229795 181 char *next, *previous, *slash, *start_path, *absolute_path = NULL;
5de083f4
RB
182 char *last_token;
183 int is_dot, is_dotdot;
81b86775
DG
184
185 /* Safety net */
186 if (path == NULL) {
187 goto error;
188 }
189
3d229795
RB
190 /* Allocate memory for the absolute_path */
191 absolute_path = zmalloc(PATH_MAX);
192 if (absolute_path == NULL) {
81b86775
DG
193 PERROR("zmalloc expand path");
194 goto error;
195 }
196
3d229795
RB
197 /*
198 * If the path is not already absolute nor explicitly relative,
199 * consider we're in the current directory
200 */
201 if (*path != '/' && strncmp(path, "./", 2) != 0 &&
202 strncmp(path, "../", 3) != 0) {
203 snprintf(absolute_path, PATH_MAX, "./%s", path);
2dcd84b7 204 /* Else, we just copy the path */
116f95d9 205 } else {
3d229795
RB
206 strncpy(absolute_path, path, PATH_MAX);
207 }
116f95d9 208
3d229795
RB
209 /* Resolve partially our path */
210 absolute_path = utils_partial_realpath(absolute_path,
211 absolute_path, PATH_MAX);
116f95d9 212
3d229795
RB
213 /* As long as we find '/./' in the working_path string */
214 while ((next = strstr(absolute_path, "/./"))) {
116f95d9 215
3d229795
RB
216 /* We prepare the start_path not containing it */
217 start_path = strndup(absolute_path, next - absolute_path);
116f95d9 218
3d229795
RB
219 /* And we concatenate it with the part after this string */
220 snprintf(absolute_path, PATH_MAX, "%s%s", start_path, next + 2);
116f95d9 221
3d229795
RB
222 free(start_path);
223 }
116f95d9 224
3d229795
RB
225 /* As long as we find '/../' in the working_path string */
226 while ((next = strstr(absolute_path, "/../"))) {
227 /* We find the last level of directory */
228 previous = absolute_path;
229 while ((slash = strpbrk(previous, "/")) && slash != next) {
230 previous = slash + 1;
81b86775 231 }
81b86775 232
3d229795
RB
233 /* Then we prepare the start_path not containing it */
234 start_path = strndup(absolute_path, previous - absolute_path);
235
236 /* And we concatenate it with the part after the '/../' */
237 snprintf(absolute_path, PATH_MAX, "%s%s", start_path, next + 4);
238
239 /* We can free the memory used for the start path*/
240 free(start_path);
241
242 /* Then we verify for symlinks using partial_realpath */
243 absolute_path = utils_partial_realpath(absolute_path,
244 absolute_path, PATH_MAX);
116f95d9 245 }
81b86775 246
5de083f4
RB
247 /* Identify the last token */
248 last_token = strrchr(absolute_path, '/');
249
250 /* Verify that this token is not a relative path */
251 is_dotdot = (strcmp(last_token, "/..") == 0);
252 is_dot = (strcmp(last_token, "/.") == 0);
253
254 /* If it is, take action */
255 if (is_dot || is_dotdot) {
256 /* For both, remove this token */
257 *last_token = '\0';
258
259 /* If it was a reference to parent directory, go back one more time */
260 if (is_dotdot) {
261 last_token = strrchr(absolute_path, '/');
262
263 /* If there was only one level left, we keep the first '/' */
264 if (last_token == absolute_path) {
265 last_token++;
266 }
267
268 *last_token = '\0';
269 }
270 }
271
3d229795 272 return absolute_path;
81b86775
DG
273
274error:
3d229795 275 free(absolute_path);
81b86775
DG
276 return NULL;
277}
278
279/*
280 * Create a pipe in dst.
281 */
90e535ef 282LTTNG_HIDDEN
81b86775
DG
283int utils_create_pipe(int *dst)
284{
285 int ret;
286
287 if (dst == NULL) {
288 return -1;
289 }
290
291 ret = pipe(dst);
292 if (ret < 0) {
293 PERROR("create pipe");
294 }
295
296 return ret;
297}
298
299/*
300 * Create pipe and set CLOEXEC flag to both fd.
301 *
302 * Make sure the pipe opened by this function are closed at some point. Use
303 * utils_close_pipe().
304 */
90e535ef 305LTTNG_HIDDEN
81b86775
DG
306int utils_create_pipe_cloexec(int *dst)
307{
308 int ret, i;
309
310 if (dst == NULL) {
311 return -1;
312 }
313
314 ret = utils_create_pipe(dst);
315 if (ret < 0) {
316 goto error;
317 }
318
319 for (i = 0; i < 2; i++) {
320 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
321 if (ret < 0) {
322 PERROR("fcntl pipe cloexec");
323 goto error;
324 }
325 }
326
327error:
328 return ret;
329}
330
094f381c
MD
331/*
332 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
333 *
334 * Make sure the pipe opened by this function are closed at some point. Use
335 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
336 * support OSes other than Linux 2.6.23+.
337 */
338LTTNG_HIDDEN
339int utils_create_pipe_cloexec_nonblock(int *dst)
340{
341 int ret, i;
342
343 if (dst == NULL) {
344 return -1;
345 }
346
347 ret = utils_create_pipe(dst);
348 if (ret < 0) {
349 goto error;
350 }
351
352 for (i = 0; i < 2; i++) {
353 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
354 if (ret < 0) {
355 PERROR("fcntl pipe cloexec");
356 goto error;
357 }
358 /*
359 * Note: we override any flag that could have been
360 * previously set on the fd.
361 */
362 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
363 if (ret < 0) {
364 PERROR("fcntl pipe nonblock");
365 goto error;
366 }
367 }
368
369error:
370 return ret;
371}
372
81b86775
DG
373/*
374 * Close both read and write side of the pipe.
375 */
90e535ef 376LTTNG_HIDDEN
81b86775
DG
377void utils_close_pipe(int *src)
378{
379 int i, ret;
380
381 if (src == NULL) {
382 return;
383 }
384
385 for (i = 0; i < 2; i++) {
386 /* Safety check */
387 if (src[i] < 0) {
388 continue;
389 }
390
391 ret = close(src[i]);
392 if (ret) {
393 PERROR("close pipe");
394 }
395 }
396}
a4b92340
DG
397
398/*
399 * Create a new string using two strings range.
400 */
90e535ef 401LTTNG_HIDDEN
a4b92340
DG
402char *utils_strdupdelim(const char *begin, const char *end)
403{
404 char *str;
405
406 str = zmalloc(end - begin + 1);
407 if (str == NULL) {
408 PERROR("zmalloc strdupdelim");
409 goto error;
410 }
411
412 memcpy(str, begin, end - begin);
413 str[end - begin] = '\0';
414
415error:
416 return str;
417}
b662582b
DG
418
419/*
420 * Set CLOEXEC flag to the give file descriptor.
421 */
90e535ef 422LTTNG_HIDDEN
b662582b
DG
423int utils_set_fd_cloexec(int fd)
424{
425 int ret;
426
427 if (fd < 0) {
428 ret = -EINVAL;
429 goto end;
430 }
431
432 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
433 if (ret < 0) {
434 PERROR("fcntl cloexec");
435 ret = -errno;
436 }
437
438end:
439 return ret;
440}
35f90c40
DG
441
442/*
443 * Create pid file to the given path and filename.
444 */
90e535ef 445LTTNG_HIDDEN
35f90c40
DG
446int utils_create_pid_file(pid_t pid, const char *filepath)
447{
448 int ret;
449 FILE *fp;
450
451 assert(filepath);
452
453 fp = fopen(filepath, "w");
454 if (fp == NULL) {
455 PERROR("open pid file %s", filepath);
456 ret = -1;
457 goto error;
458 }
459
460 ret = fprintf(fp, "%d\n", pid);
461 if (ret < 0) {
462 PERROR("fprintf pid file");
463 }
464
465 fclose(fp);
466 DBG("Pid %d written in file %s", pid, filepath);
467error:
468 return ret;
469}
2d851108
DG
470
471/*
472 * Recursively create directory using the given path and mode.
473 *
474 * On success, return 0 else a negative error code.
475 */
90e535ef 476LTTNG_HIDDEN
2d851108
DG
477int utils_mkdir_recursive(const char *path, mode_t mode)
478{
479 char *p, tmp[PATH_MAX];
2d851108
DG
480 size_t len;
481 int ret;
482
483 assert(path);
484
485 ret = snprintf(tmp, sizeof(tmp), "%s", path);
486 if (ret < 0) {
487 PERROR("snprintf mkdir");
488 goto error;
489 }
490
491 len = ret;
492 if (tmp[len - 1] == '/') {
493 tmp[len - 1] = 0;
494 }
495
496 for (p = tmp + 1; *p; p++) {
497 if (*p == '/') {
498 *p = 0;
499 if (tmp[strlen(tmp) - 1] == '.' &&
500 tmp[strlen(tmp) - 2] == '.' &&
501 tmp[strlen(tmp) - 3] == '/') {
502 ERR("Using '/../' is not permitted in the trace path (%s)",
503 tmp);
504 ret = -1;
505 goto error;
506 }
0c7bcad5 507 ret = mkdir(tmp, mode);
2d851108 508 if (ret < 0) {
0c7bcad5
MD
509 if (errno != EEXIST) {
510 PERROR("mkdir recursive");
511 ret = -errno;
512 goto error;
2d851108
DG
513 }
514 }
515 *p = '/';
516 }
517 }
518
519 ret = mkdir(tmp, mode);
520 if (ret < 0) {
521 if (errno != EEXIST) {
522 PERROR("mkdir recursive last piece");
523 ret = -errno;
524 } else {
525 ret = 0;
526 }
527 }
528
529error:
530 return ret;
531}
fe4477ee
JD
532
533/*
534 * Create the stream tracefile on disk.
535 *
536 * Return 0 on success or else a negative value.
537 */
bc182241 538LTTNG_HIDDEN
07b86b52 539int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
309167d2 540 uint64_t count, int uid, int gid, char *suffix)
fe4477ee 541{
be96a7d1 542 int ret, out_fd, flags, mode;
309167d2
JD
543 char full_path[PATH_MAX], *path_name_suffix = NULL, *path;
544 char *extra = NULL;
fe4477ee
JD
545
546 assert(path_name);
547 assert(file_name);
548
549 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
550 path_name, file_name);
551 if (ret < 0) {
552 PERROR("snprintf create output file");
553 goto error;
554 }
555
309167d2
JD
556 /* Setup extra string if suffix or/and a count is needed. */
557 if (size > 0 && suffix) {
558 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
559 } else if (size > 0) {
560 ret = asprintf(&extra, "_%" PRIu64, count);
561 } else if (suffix) {
562 ret = asprintf(&extra, "%s", suffix);
563 }
564 if (ret < 0) {
565 PERROR("Allocating extra string to name");
566 goto error;
567 }
568
fe4477ee
JD
569 /*
570 * If we split the trace in multiple files, we have to add the count at the
571 * end of the tracefile name
572 */
309167d2
JD
573 if (extra) {
574 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
fe4477ee 575 if (ret < 0) {
309167d2
JD
576 PERROR("Allocating path name with extra string");
577 goto error_free_suffix;
fe4477ee 578 }
309167d2 579 path = path_name_suffix;
fe4477ee
JD
580 } else {
581 path = full_path;
582 }
583
be96a7d1 584 flags = O_WRONLY | O_CREAT | O_TRUNC;
0f907de1 585 /* Open with 660 mode */
be96a7d1
DG
586 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
587
588 if (uid < 0 || gid < 0) {
589 out_fd = open(path, flags, mode);
590 } else {
591 out_fd = run_as_open(path, flags, mode, uid, gid);
592 }
fe4477ee
JD
593 if (out_fd < 0) {
594 PERROR("open stream path %s", path);
595 goto error_open;
596 }
597 ret = out_fd;
598
599error_open:
309167d2
JD
600 free(path_name_suffix);
601error_free_suffix:
602 free(extra);
fe4477ee
JD
603error:
604 return ret;
605}
606
607/*
608 * Change the output tracefile according to the given size and count The
609 * new_count pointer is set during this operation.
610 *
611 * From the consumer, the stream lock MUST be held before calling this function
612 * because we are modifying the stream status.
613 *
614 * Return 0 on success or else a negative value.
615 */
bc182241 616LTTNG_HIDDEN
fe4477ee 617int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
309167d2
JD
618 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
619 int *stream_fd)
fe4477ee
JD
620{
621 int ret;
622
309167d2
JD
623 assert(new_count);
624 assert(stream_fd);
625
fe4477ee
JD
626 ret = close(out_fd);
627 if (ret < 0) {
628 PERROR("Closing tracefile");
629 goto error;
630 }
631
632 if (count > 0) {
633 *new_count = (*new_count + 1) % count;
634 } else {
635 (*new_count)++;
636 }
637
309167d2
JD
638 ret = utils_create_stream_file(path_name, file_name, size, *new_count,
639 uid, gid, 0);
640 if (ret < 0) {
641 goto error;
642 }
643 *stream_fd = ret;
644
645 /* Success. */
646 ret = 0;
647
fe4477ee
JD
648error:
649 return ret;
650}
70d0b120 651
70d0b120
SM
652
653/**
654 * Parse a string that represents a size in human readable format. It
5983a922 655 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
656 *
657 * The suffix multiply the integer by:
658 * 'k': 1024
659 * 'M': 1024^2
660 * 'G': 1024^3
661 *
662 * @param str The string to parse.
5983a922 663 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 664 * resulting size.
70d0b120
SM
665 *
666 * @return 0 on success, -1 on failure.
667 */
00a52467 668LTTNG_HIDDEN
5983a922 669int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 670{
70d0b120 671 int ret;
5983a922 672 uint64_t base_size;
70d0b120 673 long shift = 0;
5983a922
SM
674 const char *str_end;
675 char *num_end;
70d0b120
SM
676
677 if (!str) {
5983a922 678 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
679 ret = -1;
680 goto end;
681 }
682
5983a922
SM
683 /* strtoull will accept a negative number, but we don't want to. */
684 if (strchr(str, '-') != NULL) {
685 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 686 ret = -1;
5983a922 687 goto end;
70d0b120
SM
688 }
689
5983a922
SM
690 /* str_end will point to the \0 */
691 str_end = str + strlen(str);
70d0b120 692 errno = 0;
5983a922 693 base_size = strtoull(str, &num_end, 0);
70d0b120 694 if (errno != 0) {
5983a922 695 PERROR("utils_parse_size_suffix strtoull");
70d0b120 696 ret = -1;
5983a922
SM
697 goto end;
698 }
699
700 if (num_end == str) {
701 /* strtoull parsed nothing, not good. */
702 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
703 ret = -1;
704 goto end;
705 }
706
707 /* Check if a prefix is present. */
708 switch (*num_end) {
709 case 'G':
710 shift = GIBI_LOG2;
711 num_end++;
712 break;
713 case 'M': /* */
714 shift = MEBI_LOG2;
715 num_end++;
716 break;
717 case 'K':
718 case 'k':
719 shift = KIBI_LOG2;
720 num_end++;
721 break;
722 case '\0':
723 break;
724 default:
725 DBG("utils_parse_size_suffix: invalid suffix.");
726 ret = -1;
727 goto end;
728 }
729
730 /* Check for garbage after the valid input. */
731 if (num_end != str_end) {
732 DBG("utils_parse_size_suffix: Garbage after size string.");
733 ret = -1;
734 goto end;
70d0b120
SM
735 }
736
737 *size = base_size << shift;
738
739 /* Check for overflow */
740 if ((*size >> shift) != base_size) {
5983a922 741 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 742 ret = -1;
5983a922 743 goto end;
70d0b120
SM
744 }
745
746 ret = 0;
70d0b120
SM
747end:
748 return ret;
749}
cfa9a5a2
DG
750
751/*
752 * fls: returns the position of the most significant bit.
753 * Returns 0 if no bit is set, else returns the position of the most
754 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
755 */
756#if defined(__i386) || defined(__x86_64)
757static inline unsigned int fls_u32(uint32_t x)
758{
759 int r;
760
761 asm("bsrl %1,%0\n\t"
762 "jnz 1f\n\t"
763 "movl $-1,%0\n\t"
764 "1:\n\t"
765 : "=r" (r) : "rm" (x));
766 return r + 1;
767}
768#define HAS_FLS_U32
769#endif
770
771#ifndef HAS_FLS_U32
772static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
773{
774 unsigned int r = 32;
775
776 if (!x) {
777 return 0;
778 }
779 if (!(x & 0xFFFF0000U)) {
780 x <<= 16;
781 r -= 16;
782 }
783 if (!(x & 0xFF000000U)) {
784 x <<= 8;
785 r -= 8;
786 }
787 if (!(x & 0xF0000000U)) {
788 x <<= 4;
789 r -= 4;
790 }
791 if (!(x & 0xC0000000U)) {
792 x <<= 2;
793 r -= 2;
794 }
795 if (!(x & 0x80000000U)) {
796 x <<= 1;
797 r -= 1;
798 }
799 return r;
800}
801#endif
802
803/*
804 * Return the minimum order for which x <= (1UL << order).
805 * Return -1 if x is 0.
806 */
807LTTNG_HIDDEN
808int utils_get_count_order_u32(uint32_t x)
809{
810 if (!x) {
811 return -1;
812 }
813
814 return fls_u32(x - 1);
815}
feb0f3e5
AM
816
817/**
818 * Obtain the value of LTTNG_HOME environment variable, if exists.
819 * Otherwise returns the value of HOME.
820 */
00a52467 821LTTNG_HIDDEN
feb0f3e5
AM
822char *utils_get_home_dir(void)
823{
824 char *val = NULL;
04135dbd
DG
825 struct passwd *pwd;
826
feb0f3e5
AM
827 val = getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
828 if (val != NULL) {
04135dbd
DG
829 goto end;
830 }
831 val = getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
832 if (val != NULL) {
833 goto end;
feb0f3e5 834 }
04135dbd
DG
835
836 /* Fallback on the password file entry. */
837 pwd = getpwuid(getuid());
838 if (!pwd) {
839 goto end;
840 }
841 val = pwd->pw_dir;
842
843 DBG3("Home directory is '%s'", val);
844
845end:
846 return val;
feb0f3e5 847}
26fe5938 848
fb198a11
JG
849/**
850 * Get user's home directory. Dynamically allocated, must be freed
851 * by the caller.
852 */
853LTTNG_HIDDEN
854char *utils_get_user_home_dir(uid_t uid)
855{
856 struct passwd pwd;
857 struct passwd *result;
858 char *home_dir = NULL;
859 char *buf = NULL;
860 long buflen;
861 int ret;
862
863 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
864 if (buflen == -1) {
865 goto end;
866 }
867retry:
868 buf = zmalloc(buflen);
869 if (!buf) {
870 goto end;
871 }
872
873 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
874 if (ret || !result) {
875 if (ret == ERANGE) {
876 free(buf);
877 buflen *= 2;
878 goto retry;
879 }
880 goto end;
881 }
882
883 home_dir = strdup(pwd.pw_dir);
884end:
885 free(buf);
886 return home_dir;
887}
888
fbb9748b
JG
889/*
890 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
891 * Otherwise returns an empty string.
892 */
893LTTNG_HIDDEN
894char *utils_get_kmod_probes_list(void)
895{
896 return getenv(DEFAULT_LTTNG_KMOD_PROBES);
897}
898
26fe5938
DG
899/*
900 * With the given format, fill dst with the time of len maximum siz.
901 *
902 * Return amount of bytes set in the buffer or else 0 on error.
903 */
904LTTNG_HIDDEN
905size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
906{
907 size_t ret;
908 time_t rawtime;
909 struct tm *timeinfo;
910
911 assert(format);
912 assert(dst);
913
914 /* Get date and time for session path */
915 time(&rawtime);
916 timeinfo = localtime(&rawtime);
917 ret = strftime(dst, len, format, timeinfo);
918 if (ret == 0) {
68e6efdd 919 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
920 dst, len);
921 }
922
923 return ret;
924}
6c71277b
MD
925
926/*
927 * Return the group ID matching name, else 0 if it cannot be found.
928 */
929LTTNG_HIDDEN
930gid_t utils_get_group_id(const char *name)
931{
932 struct group *grp;
933
934 grp = getgrnam(name);
935 if (!grp) {
936 static volatile int warn_once;
937
938 if (!warn_once) {
939 WARN("No tracing group detected");
940 warn_once = 1;
941 }
942 return 0;
943 }
944 return grp->gr_gid;
945}
8db0dc00
JG
946
947/*
948 * Return a newly allocated option string. This string is to be used as the
949 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
950 * of elements in the long_options array. Returns NULL if the string's
951 * allocation fails.
952 */
953LTTNG_HIDDEN
954char *utils_generate_optstring(const struct option *long_options,
955 size_t opt_count)
956{
957 int i;
958 size_t string_len = opt_count, str_pos = 0;
959 char *optstring;
960
961 /*
962 * Compute the necessary string length. One letter per option, two when an
963 * argument is necessary, and a trailing NULL.
964 */
965 for (i = 0; i < opt_count; i++) {
966 string_len += long_options[i].has_arg ? 1 : 0;
967 }
968
969 optstring = zmalloc(string_len);
970 if (!optstring) {
971 goto end;
972 }
973
974 for (i = 0; i < opt_count; i++) {
975 if (!long_options[i].name) {
976 /* Got to the trailing NULL element */
977 break;
978 }
979
980 optstring[str_pos++] = (char)long_options[i].val;
981 if (long_options[i].has_arg) {
982 optstring[str_pos++] = ':';
983 }
984 }
985
986end:
987 return optstring;
988}
This page took 0.0807 seconds and 5 git commands to generate.