xref: /openbsd-src/libexec/ld.so/path.c (revision c8dfd7a0734a8685a19a8e0884852e8c62e59623)
1 /*	$OpenBSD: path.c,v 1.1 2013/03/20 21:49:59 kurt Exp $	*/
2 
3 /*
4  * Copyright (c) 2013 Kurt Miller <kurt@intricatesoftware.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include "path.h"
22 #include "util.h"
23 
24 char **
25 _dl_split_path(const char *searchpath)
26 {
27 	int pos = 0;
28 	int count = 1;
29 	const char *pp, *p_begin;
30 	char **retval;
31 
32 	if (searchpath == NULL)
33 		return (NULL);
34 
35 	/* Count ':' or ';' in searchpath */
36 	pp = searchpath;
37 	while (*pp) {
38 		if (*pp == ':' || *pp == ';')
39 			count++;
40 		pp++;
41 	}
42 
43 	/* one more for NULL entry */
44 	count++;
45 
46 	retval = _dl_malloc(count * sizeof(retval));
47 
48 	if (retval == NULL)
49 		return (NULL);
50 
51 	pp = searchpath;
52 	while (pp) {
53 		p_begin = pp;
54 		while (*pp != '\0' && *pp != ':' && *pp != ';')
55 			pp++;
56 
57 		/* interpret "" as curdir "." */
58 		if (p_begin == pp) {
59 			retval[pos] = _dl_malloc(2);
60 			if (retval[pos] == NULL)
61 				goto badret;
62 
63 			_dl_bcopy(".", retval[pos++], 2);
64 		} else {
65 			retval[pos] = _dl_malloc(pp - p_begin + 1);
66 			if (retval[pos] == NULL)
67 				goto badret;
68 
69 			_dl_bcopy(p_begin, retval[pos], pp - p_begin);
70 			retval[pos++][pp - p_begin] = '\0';
71 		}
72 
73 		if (*pp)        /* Try curdir if ':' at end */
74 			pp++;
75 		else
76 			pp = NULL;
77 	}
78 
79 	return (retval);
80 
81 badret:
82 	_dl_free_path(retval);
83 	return (NULL);
84 }
85 
86 void
87 _dl_free_path(char **path)
88 {
89 	char **p = path;
90 
91 	if (path == NULL)
92 		return;
93 
94 	while (*p != NULL)
95 		_dl_free(*p++);
96 
97 	_dl_free(path);
98 }
99