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