expandm.c revision 1.2 1 /* $NetBSD: expandm.c,v 1.2 2019/01/12 19:08:24 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2018 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Christos Zoulas.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31 #include <sys/cdefs.h>
32 __RCSID("$NetBSD: expandm.c,v 1.2 2019/01/12 19:08:24 christos Exp $");
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <errno.h>
38
39 #include "expandm.h"
40
41 char * __attribute__((__format_arg__(1)))
42 expandm(const char *fmt, const char *sf, char **rbuf)
43 {
44 const char *e = strerror(errno);
45 char *buf, *m, *nbuf;
46 const char *ptr;
47
48 for (ptr = fmt, buf = NULL; (m = strstr(ptr, "%m")) != NULL;
49 ptr = m + 2)
50 {
51 size_t cnt = 0;
52 for (char *p = m; p >= ptr && *p == '%'; p--)
53 cnt++;
54 if (asprintf(&nbuf, "%s%.*s%s", buf ? buf : "",
55 (int)(m - ptr), ptr, (cnt & 1) ? e : "%%m") == -1)
56 goto out;
57 free(buf);
58 buf = nbuf;
59 }
60
61 if (asprintf(&nbuf, "%s%s%s", buf ? buf : "", ptr, sf ? sf : "") == -1)
62 goto out;
63
64 free(buf);
65 if (rbuf)
66 *rbuf = buf;
67 return nbuf;
68 out:
69 free(buf);
70 if (rbuf)
71 *rbuf = NULL;
72 return __UNCONST(fmt);
73 }
74
75 #ifdef TEST
76 int
77 main(int argc, char *argv[])
78 {
79 errno = ERANGE;
80 printf("%s\n", expandm(argv[1], "", NULL));
81 return 0;
82 }
83 #endif
84