path.c revision 1.3
1/* $OpenBSD: path.c,v 1.3 2014/07/10 09:03:01 otto 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 24char ** 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_reallocarray(NULL, count, sizeof(retval)); 47 if (retval == NULL) 48 return (NULL); 49 50 pp = searchpath; 51 while (pp) { 52 p_begin = pp; 53 while (*pp != '\0' && *pp != ':' && *pp != ';') 54 pp++; 55 56 /* interpret "" as curdir "." */ 57 if (p_begin == pp) { 58 retval[pos] = _dl_malloc(2); 59 if (retval[pos] == NULL) 60 goto badret; 61 62 _dl_bcopy(".", retval[pos++], 2); 63 } else { 64 retval[pos] = _dl_malloc(pp - p_begin + 1); 65 if (retval[pos] == NULL) 66 goto badret; 67 68 _dl_bcopy(p_begin, retval[pos], pp - p_begin); 69 retval[pos++][pp - p_begin] = '\0'; 70 } 71 72 if (*pp) /* Try curdir if ':' at end */ 73 pp++; 74 else 75 pp = NULL; 76 } 77 78 retval[pos] = NULL; 79 return (retval); 80 81badret: 82 _dl_free_path(retval); 83 return (NULL); 84} 85 86void 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