Branch data Line data Source code
1 : : #include "precizer.h"
2 : :
3 : : /**
4 : : * @brief Allocate a path string suitable for filesystem access
5 : : *
6 : : * @details When `path` is relative, the function prefixes it with
7 : : * `config->running_dir`. When `path` is already absolute, the function copies it
8 : : * as-is into a newly allocated buffer
9 : : *
10 : : * @param[out] absolute_path Pointer that receives the allocated path buffer
11 : : * @param[in] path Relative or absolute input path
12 : : * @param[in] path_size Length of `path` without the terminating null byte
13 : : * @return Return status code
14 : : */
15 : 16357 : Return path_absolute_from_relative(
16 : : char **absolute_path,
17 : : const char *path,
18 : : const size_t path_size)
19 : : {
20 : : /* Status returned by this function through provide()
21 : : Default value assumes successful completion */
22 : 16357 : Return status = SUCCESS;
23 : :
24 : 16357 : size_t len = 0;
25 : :
26 [ + - - + ]: 16357 : if(!absolute_path || !path)
27 : : {
28 : 0 : provide(FAILURE);
29 : : }
30 : :
31 : : // Allocate memory for the absolute path (base dir + '/' + relative path + null terminator)
32 [ + - + + ]: 16357 : if(path_size > 0 && path[0] == '/')
33 : : {
34 : : // The provided path is actually absolute!
35 : 2 : len = path_size + 1;
36 : 2 : *absolute_path = (char *)malloc(len);
37 : :
38 [ - + ]: 2 : if(*absolute_path == NULL)
39 : : {
40 : 0 : report("Memory allocation failed, requested size: %zu bytes",len);
41 : 0 : status = FAILURE;
42 : 0 : provide(status);
43 : : }
44 : :
45 : 2 : snprintf(*absolute_path,len,"%s",path);
46 : :
47 : : } else {
48 : : // The provided path is indeed relative!
49 : : // running_dir_size already counts the trailing '\0'; +1 adds space for '/' and the new terminator.
50 : 16355 : len = (size_t)config->running_dir_size + path_size + 1;
51 : 16355 : *absolute_path = (char *)malloc(len);
52 : :
53 [ - + ]: 16355 : if(*absolute_path == NULL)
54 : : {
55 : 0 : report("Memory allocation failed, requested size: %zu bytes",len);
56 : 0 : status = FAILURE;
57 : 0 : provide(status);
58 : : }
59 : :
60 : 16355 : snprintf(*absolute_path,len,"%s/%s",config->running_dir,path);
61 : : }
62 : :
63 : 16357 : provide(status);
64 : : }
|