1 /*        $NetBSD: memalloc.c,v 1.40 2025/05/06 13:09:26 kre Exp $    */
2 
3 /*-
4  * Copyright (c) 1991, 1993
5  *        The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
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  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)memalloc.c  8.3 (Berkeley) 5/4/95";
39 #else
40 __RCSID("$NetBSD: memalloc.c,v 1.40 2025/05/06 13:09:26 kre Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <limits.h>
45 #include <stdarg.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 
49 #include "shell.h"
50 #include "output.h"
51 #include "memalloc.h"
52 #include "error.h"
53 #include "machdep.h"
54 #include "mystring.h"
55 
56 /*
57  * Like malloc, but returns an error when out of space.
58  */
59 
60 pointer
ckmalloc(size_t nbytes)61 ckmalloc(size_t nbytes)
62 {
63           pointer p;
64 
65           p = malloc(nbytes);
66           if (p == NULL)
67                     error("Out of space");
68           return p;
69 }
70 
71 
72 /*
73  * Same for realloc.
74  */
75 
76 pointer
ckrealloc(pointer p,int nbytes)77 ckrealloc(pointer p, int nbytes)
78 {
79           p = realloc(p, nbytes);
80           if (p == NULL)
81                     error("Out of space");
82           return p;
83 }
84 
85 
86 /*
87  * Make a copy of a string in safe storage.
88  */
89 
90 char *
savestr(const char * s)91 savestr(const char *s)
92 {
93           char *p;
94 
95           p = ckmalloc(strlen(s) + 1);
96           scopy(s, p);
97           return p;
98 }
99 
100 
101 /*
102  * Parse trees for commands are allocated in lifo order, so we use a stack
103  * to make this more efficient, and also to avoid all sorts of exception
104  * handling code to handle interrupts in the middle of a parse.
105  *
106  * The size 504 was chosen because the Ultrix malloc handles that size
107  * well.
108  */
109 
110 #define MINSIZE 504           /* minimum size of a block */
111 
112 struct stack_block {
113           struct stack_block *prev;
114           char space[MINSIZE];
115 };
116 
117 struct stack_block stackbase;
118 struct stack_block *stackp = &stackbase;
119 struct stackmark *markp;
120 char *stacknxt = stackbase.space;
121 int stacknleft = MINSIZE;
122 int sstrnleft;
123 int herefd = -1;
124 
125 pointer
stalloc(int nbytes)126 stalloc(int nbytes)
127 {
128           char *p;
129 
130           nbytes = SHELL_ALIGN(nbytes);
131           if (nbytes > stacknleft) {
132                     int blocksize;
133                     struct stack_block *sp;
134 
135                     blocksize = nbytes;
136                     if (blocksize < MINSIZE)
137                               blocksize = MINSIZE;
138                     INTOFF;
139                     sp = ckmalloc(sizeof(struct stack_block) - MINSIZE + blocksize);
140                     sp->prev = stackp;
141                     stacknxt = sp->space;
142                     stacknleft = blocksize;
143                     stackp = sp;
144                     INTON;
145           }
146           INTOFF;
147           p = stacknxt;
148           stacknxt += nbytes;
149           stacknleft -= nbytes;
150           INTON;
151           return p;
152 }
153 
154 
155 void
stunalloc(pointer p)156 stunalloc(pointer p)
157 {
158           if (p == NULL) {              /*DEBUG */
159                     write(2, "stunalloc\n", 10);
160                     abort();
161           }
162           stacknleft += stacknxt - (char *)p;
163           stacknxt = p;
164 }
165 
166 
167 /* save the current status of the sh stack */
168 void
setstackmark(struct stackmark * mark)169 setstackmark(struct stackmark *mark)
170 {
171           mark->stackp = stackp;
172           mark->stacknxt = stacknxt;
173           mark->stacknleft = stacknleft;
174           mark->sstrnleft = sstrnleft;
175           mark->marknext = markp;
176           markp = mark;
177 }
178 
179 /* reset the stack mark, and remove it from the list of marks */
180 void
popstackmark(struct stackmark * mark)181 popstackmark(struct stackmark *mark)
182 {
183           INTOFF;
184           markp = mark->marknext;                 /* delete mark from the list */
185           rststackmark(mark);           /* and reset stack */
186           INTON;
187 }
188 
189 /* reset the shell stack to its state recorded in the stack mark */
190 void
rststackmark(struct stackmark * mark)191 rststackmark(struct stackmark *mark)
192 {
193           struct stack_block *sp;
194 
195           INTOFF;
196           while (stackp != mark->stackp) {
197                     /* delete any recently allocated mem blocks */
198                     sp = stackp;
199                     stackp = sp->prev;
200                     ckfree(sp);
201           }
202           stacknxt = mark->stacknxt;
203           stacknleft = mark->stacknleft;
204           sstrnleft = mark->sstrnleft;
205           INTON;
206 }
207 
208 
209 /*
210  * When the parser reads in a string, it wants to stick the string on the
211  * stack and only adjust the stack pointer when it knows how big the
212  * string is.  Stackblock (defined in stack.h) returns a pointer to a block
213  * of space on top of the stack and stackblocklen returns the length of
214  * this block.  Growstackblock will grow this space by at least one byte,
215  * possibly moving it (like realloc).  Grabstackblock actually allocates the
216  * part of the block that has been used.
217  */
218 
219 void
growstackblock(void)220 growstackblock(void)
221 {
222           int newlen = SHELL_ALIGN(stacknleft * 2 + 100);
223 
224           INTOFF;
225           if (stacknxt == stackp->space && stackp != &stackbase) {
226                     struct stack_block *oldstackp;
227                     struct stackmark *xmark;
228                     struct stack_block *sp;
229 
230                     oldstackp = stackp;
231                     sp = stackp;
232                     stackp = sp->prev;
233                     sp = ckrealloc((pointer)sp,
234                         sizeof(struct stack_block) - MINSIZE + newlen);
235                     sp->prev = stackp;
236                     stackp = sp;
237                     stacknxt = sp->space;
238                     sstrnleft += newlen - stacknleft;
239                     stacknleft = newlen;
240 
241                     /*
242                      * Stack marks pointing to the start of the old block
243                      * must be relocated to point to the new block
244                      */
245                     xmark = markp;
246                     while (xmark != NULL && xmark->stackp == oldstackp) {
247                               xmark->stackp = stackp;
248                               xmark->stacknxt = stacknxt;
249                               xmark->sstrnleft += stacknleft - xmark->stacknleft;
250                               xmark->stacknleft = stacknleft;
251                               xmark = xmark->marknext;
252                     }
253           } else {
254                     char *oldspace = stacknxt;
255                     int oldlen = stacknleft;
256                     char *p = stalloc(newlen);
257 
258                     (void)memcpy(p, oldspace, oldlen);
259                     stacknxt = p;                           /* free the space */
260                     stacknleft += newlen;                   /* we just allocated */
261           }
262           INTON;
263 }
264 
265 void
grabstackblock(int len)266 grabstackblock(int len)
267 {
268           len = SHELL_ALIGN(len);
269           INTOFF;
270           stacknxt += len;
271           stacknleft -= len;
272           INTON;
273 }
274 
275 /*
276  * The following routines are somewhat easier to use than the above.
277  * The user declares a variable of type STACKSTR, which may be declared
278  * to be a register.  The macro STARTSTACKSTR initializes things.  Then
279  * the user uses the macro STPUTC to add characters to the string.  In
280  * effect, STPUTC(c, p) is the same as *p++ = c except that the stack is
281  * grown as necessary.  When the user is done, she can just leave the
282  * string there and refer to it using stackblock().  Or she can allocate
283  * the space for it using grabstackstr().  If it is necessary to allow
284  * someone else to use the stack temporarily and then continue to grow
285  * the string, the user should use grabstack to allocate the space, and
286  * then call ungrabstr(p) to return to the previous mode of operation.
287  *
288  * USTPUTC is like STPUTC except that it doesn't check for overflow.
289  * CHECKSTACKSPACE can be called before USTPUTC to ensure that there
290  * is space for at least one character.
291  */
292 
293 char *
growstackstr(void)294 growstackstr(void)
295 {
296           int len = stackblocksize();
297 
298           growstackblock();
299           sstrnleft = stackblocksize() - len - 1;
300           return stackblock() + len;
301 }
302 
303 /*
304  * Called from CHECKSTRSPACE.
305  */
306 
307 char *
makestrspace(void)308 makestrspace(void)
309 {
310           int len = stackblocksize() - sstrnleft;
311           growstackblock();
312           sstrnleft = stackblocksize() - len;
313           return stackblock() + len;
314 }
315 
316 /*
317  * Note that this only works to release stack space for reuse
318  * if nothing else has allocated space on the stack since the grabstackstr()
319  *
320  * "s" is the start of the area to be released, and "p" represents the end
321  * of the string we have stored beyond there and are now releasing.
322  * (ie: "p" should be the same as in the call to grabstackstr()).
323  *
324  * stunalloc(s) and ungrabstackstr(s, p) are almost interchangeable after
325  * a grabstackstr(), however the latter also returns string space so we
326  * can just continue with STPUTC() etc without needing a new STARTSTACKSTR(s)
327  */
328 void
ungrabstackstr(char * s,char * p)329 ungrabstackstr(char *s, char *p)
330 {
331 #ifdef DEBUG
332           if (s < stacknxt || stacknxt + stacknleft < s)
333                     abort();
334 #endif
335           stacknleft += stacknxt - s;
336           stacknxt = s;
337           sstrnleft = stacknleft - (p - s);
338 }
339 
340 /*
341  * Save the concat of a sequence of strings in stack space
342  *
343  * The first arg (if not NULL) is a pointer to where the final string
344  * length will be returned.
345  *
346  * Remaining args are pointers to strings - sufficient space to hold
347  * the concat of the strings is allocated on the stack, the strings
348  * are copied into that space, and a pointer to its start is returned.
349  * The arg list is terminated with STSTRC_END.
350  *
351  * Use stunalloc(string) (in proper sequence) to release the string
352  */
353 char *
ststrcat(size_t * lp,...)354 ststrcat(size_t *lp, ...)
355 {
356           va_list ap;
357           const char *arg;
358           size_t len, tlen = 0, alen[8];
359           char *str, *nxt;
360           unsigned int n;
361 
362           n = 0;
363           va_start(ap, lp);
364           arg = va_arg(ap, const char *);
365           while (arg != STSTRC_END) {
366                     len = strlen(arg);
367                     if (n < sizeof(alen)/sizeof(alen[0]))
368                               alen[n++] = len;
369                     tlen += len;
370                     arg = va_arg(ap, const char *);
371           }
372           va_end(ap);
373 
374           if (lp != NULL)
375                     *lp = tlen;
376 
377           if (tlen >= INT_MAX)
378                     error("ststrcat() over length botch");
379           str = (char *)stalloc((int)tlen + 1);   /* 1 for \0 */
380           str[tlen] = '\0';   /* in case of no args  */
381 
382           n = 0;
383           nxt = str;
384           va_start(ap, lp);
385           arg = va_arg(ap, const char *);
386           while (arg != STSTRC_END) {
387                     if (n < sizeof(alen)/sizeof(alen[0]))
388                               len = alen[n++];
389                     else
390                               len = strlen(arg);
391 
392                     scopy(arg, nxt);
393                     nxt += len;
394 
395                     arg = va_arg(ap, const char *);
396           }
397           va_end(ap);
398 
399           return str;
400 }
401