aboutsummaryrefslogtreecommitdiff
path: root/lib/fstree/get_path.c
blob: f464ade42ad2057d8b538fb3b10b3bf859481fe9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * get_path.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "config.h"

#include "fstree.h"
#include "util.h"

#include <string.h>
#include <stdlib.h>
#include <errno.h>

char *fstree_get_path(tree_node_t *node)
{
	tree_node_t *it;
	char *str, *ptr;
	size_t len = 0;

	if (node->parent == NULL)
		return strdup("/");

	for (it = node; it != NULL && it->parent != NULL; it = it->parent) {
		if (SZ_ADD_OV(len, strlen(it->name), &len) ||
		    SZ_ADD_OV(len, 1, &len))
			goto fail_ov;
	}

	if (SZ_ADD_OV(len, 1, &len))
		goto fail_ov;

	str = malloc(len);
	if (str == NULL)
		return NULL;

	ptr = str + len - 1;
	*ptr = '\0';

	for (it = node; it != NULL && it->parent != NULL; it = it->parent) {
		len = strlen(it->name);
		ptr -= len;

		memcpy(ptr, it->name, len);
		*(--ptr) = '/';
	}

	return str;
fail_ov:
	errno = EOVERFLOW;
	return NULL;
}