path.c revision 1.2
1/* $OpenBSD: path.c,v 1.2 2014/06/21 08:00:23 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 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 retval[pos] = NULL; 80 return (retval); 81 82badret: 83 _dl_free_path(retval); 84 return (NULL); 85} 86 87void 88_dl_free_path(char **path) 89{ 90 char **p = path; 91 92 if (path == NULL) 93 return; 94 95 while (*p != NULL) 96 _dl_free(*p++); 97 98 _dl_free(path); 99} 100