path.c revision 1.6
1/* $OpenBSD: path.c,v 1.6 2015/05/22 13:48:25 jsg 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 "path.h" 21#include "util.h" 22 23char ** 24_dl_split_path(const char *searchpath) 25{ 26 int pos = 0; 27 int count = 1; 28 const char *pp, *p_begin; 29 char **retval; 30 31 if (searchpath == NULL) 32 return (NULL); 33 34 /* Count ':' or ';' in searchpath */ 35 pp = searchpath; 36 while (*pp) { 37 if (*pp == ':' || *pp == ';') 38 count++; 39 pp++; 40 } 41 42 /* one more for NULL entry */ 43 count++; 44 45 retval = _dl_reallocarray(NULL, count, sizeof(*retval)); 46 if (retval == NULL) 47 return (NULL); 48 49 pp = searchpath; 50 while (pp) { 51 p_begin = pp; 52 while (*pp != '\0' && *pp != ':' && *pp != ';') 53 pp++; 54 55 /* interpret "" as curdir "." */ 56 if (p_begin == pp) { 57 retval[pos] = _dl_malloc(2); 58 if (retval[pos] == NULL) 59 goto badret; 60 61 _dl_bcopy(".", retval[pos++], 2); 62 } else { 63 retval[pos] = _dl_malloc(pp - p_begin + 1); 64 if (retval[pos] == NULL) 65 goto badret; 66 67 _dl_bcopy(p_begin, retval[pos], pp - p_begin); 68 retval[pos++][pp - p_begin] = '\0'; 69 } 70 71 if (*pp) /* Try curdir if ':' at end */ 72 pp++; 73 else 74 pp = NULL; 75 } 76 77 retval[pos] = NULL; 78 return (retval); 79 80badret: 81 _dl_free_path(retval); 82 return (NULL); 83} 84 85void 86_dl_free_path(char **path) 87{ 88 char **p = path; 89 90 if (path == NULL) 91 return; 92 93 while (*p != NULL) 94 _dl_free(*p++); 95 96 _dl_free(path); 97} 98