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