1 /*- 2 * Copyright (c) 2003 Poul-Henning Kamp 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. The names of the authors may not be used to endorse or promote 14 * products derived from this software without specific prior written 15 * permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 * 29 * $FreeBSD$ 30 */ 31 32 #include <sys/types.h> 33 #include <sys/sysctl.h> 34 #include <errno.h> 35 #include <stdlib.h> 36 #include <string.h> 37 #include "libgeom.h" 38 39 /* 40 * Amount of extra space we allocate to try and anticipate the size of 41 * confxml. 42 */ 43 #define GEOM_GETXML_SLACK 4096 44 45 /* 46 * Number of times to retry in the face of the size of confxml exceeding 47 * that of our buffer. 48 */ 49 #define GEOM_GETXML_RETRIES 4 50 51 char * 52 geom_getxml(void) 53 { 54 char *p; 55 size_t l = 0; 56 int mib[3]; 57 size_t sizep; 58 int retries; 59 60 sizep = sizeof(mib) / sizeof(*mib); 61 if (sysctlnametomib("kern.geom.confxml", mib, &sizep) != 0) 62 return (NULL); 63 if (sysctl(mib, sizep, NULL, &l, NULL, 0) != 0) 64 return (NULL); 65 l += GEOM_GETXML_SLACK; 66 67 for (retries = 0; retries < GEOM_GETXML_RETRIES; retries++) { 68 p = malloc(l); 69 if (p == NULL) 70 return (NULL); 71 if (sysctl(mib, sizep, p, &l, NULL, 0) == 0) 72 return (reallocf(p, strlen(p) + 1)); 73 74 free(p); 75 76 if (errno != ENOMEM) 77 return (NULL); 78 79 /* 80 * Our buffer wasn't big enough. Make it bigger and 81 * try again. 82 */ 83 l *= 2; 84 } 85 86 return (NULL); 87 } 88