patch-7.107
[dragonfly.git] / usr.bin / make / str.c
1 /*-
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)str.c    5.8 (Berkeley) 6/1/90
39  * $FreeBSD: src/usr.bin/make/str.c,v 1.40 2005/02/07 07:54:23 harti Exp $
40  * $DragonFly: src/usr.bin/make/str.c,v 1.26 2005/03/04 23:49:42 okumoto Exp $
41  */
42
43 #include <ctype.h>
44 #include <stdlib.h>
45 #include <string.h>
46
47 #include "buf.h"
48 #include "globals.h"
49 #include "str.h"
50 #include "util.h"
51 #include "var.h"
52
53 static char **argv, *buffer;
54 static int argmax, curlen;
55
56 /*
57  * str_init --
58  *      Initialize the strings package
59  *
60  */
61 void
62 str_init(void)
63 {
64     char *p1;
65
66     argv = emalloc(((argmax = 50) + 1) * sizeof(char *));
67     argv[0] = Var_Value(".MAKE", VAR_GLOBAL, &p1);
68 }
69
70 /*-
71  * str_concat --
72  *      concatenate the two strings, inserting a space or slash between them.
73  *
74  * returns --
75  *      the resulting string in allocated space.
76  */
77 char *
78 str_concat(const char *s1, const char *s2, int flags)
79 {
80         int len1, len2;
81         char *result;
82
83         /* get the length of both strings */
84         len1 = strlen(s1);
85         len2 = strlen(s2);
86
87         /* allocate length plus separator plus EOS */
88         result = emalloc(len1 + len2 + 2);
89
90         /* copy first string into place */
91         memcpy(result, s1, len1);
92
93         /* add separator character */
94         if (flags & STR_ADDSPACE) {
95                 result[len1] = ' ';
96                 ++len1;
97         } else if (flags & STR_ADDSLASH) {
98                 result[len1] = '/';
99                 ++len1;
100         }
101
102         /* copy second string plus EOS into place */
103         memcpy(result + len1, s2, len2 + 1);
104
105         return (result);
106 }
107
108 /*-
109  * brk_string --
110  *      Fracture a string into an array of words (as delineated by tabs or
111  *      spaces) taking quotation marks into account.  Leading tabs/spaces
112  *      are ignored.
113  *
114  * returns --
115  *      Pointer to the array of pointers to the words.  To make life easier,
116  *      the first word is always the value of the .MAKE variable.
117  */
118 char **
119 brk_string(const char *str, int *store_argc, Boolean expand)
120 {
121         int argc, ch;
122         char inquote;
123         const char *p;
124         char *start, *t;
125         int len;
126
127         /* skip leading space chars. */
128         for (; *str == ' ' || *str == '\t'; ++str)
129                 continue;
130
131         /* allocate room for a copy of the string */
132         if ((len = strlen(str) + 1) > curlen) {
133                 if (buffer)
134                     free(buffer);
135                 buffer = emalloc(curlen = len);
136         }
137
138         /*
139          * copy the string; at the same time, parse backslashes,
140          * quotes and build the argument list.
141          */
142         argc = 1;
143         inquote = '\0';
144         for (p = str, start = t = buffer;; ++p) {
145                 switch(ch = *p) {
146                 case '"':
147                 case '\'':
148                         if (inquote) {
149                                 if (ch != inquote)
150                                         break;
151                                 inquote = '\0';
152                                 /* Don't miss "" or '' */
153                                 if (!start)
154                                         start = t;
155                         } else
156                                 inquote = (char)ch;
157                         if (expand)
158                                 continue;
159                         break;
160                 case ' ':
161                 case '\t':
162                 case '\n':
163                         if (inquote)
164                                 break;
165                         if (!start)
166                                 continue;
167                         /* FALLTHROUGH */
168                 case '\0':
169                         /*
170                          * end of a token -- make sure there's enough argv
171                          * space and save off a pointer.
172                          */
173                         if (!start)
174                             goto done;
175
176                         *t++ = '\0';
177                         if (argc == argmax) {
178                                 argmax *= 2;            /* ramp up fast */
179                                 argv = erealloc(argv,
180                                     (argmax + 1) * sizeof(char *));
181                         }
182                         argv[argc++] = start;
183                         start = NULL;
184                         if (ch == '\n' || ch == '\0')
185                                 goto done;
186                         continue;
187                 case '\\':
188                         if (!expand) {
189                                 if (!start)
190                                         start = t;
191                                 *t++ = '\\';
192                                 ch = *++p;
193                                 break;
194                         }
195
196                         switch (ch = *++p) {
197                         case '\0':
198                         case '\n':
199                                 /* hmmm; fix it up as best we can */
200                                 ch = '\\';
201                                 --p;
202                                 break;
203                         case 'b':
204                                 ch = '\b';
205                                 break;
206                         case 'f':
207                                 ch = '\f';
208                                 break;
209                         case 'n':
210                                 ch = '\n';
211                                 break;
212                         case 'r':
213                                 ch = '\r';
214                                 break;
215                         case 't':
216                                 ch = '\t';
217                                 break;
218                         default:
219                                 break;
220                         }
221                         break;
222                 default:
223                         break;
224                 }
225                 if (!start)
226                         start = t;
227                 *t++ = (char)ch;
228         }
229 done:   argv[argc] = NULL;
230         if (store_argc != NULL)
231                 *store_argc = argc;
232         return (argv);
233 }
234
235 /*
236  * Quote a string for appending it to MAKEFLAGS. According to Posix the
237  * kind of quoting here is implementation-defined. This quoting must ensure
238  * that the parsing of MAKEFLAGS's contents in a sub-shell yields the same
239  * options, option arguments and macro definitions as in the calling make.
240  * We simply quote all blanks, which according to Posix are space and tab
241  * in the POSIX locale. Don't use isblank because in that case makes with
242  * different locale settings could not communicate. We must also quote
243  * backslashes obviously.
244  */
245 char *
246 MAKEFLAGS_quote(const char *str)
247 {
248         char *ret, *q;
249         const char *p;
250
251         /* assume worst case - everything has to be quoted */
252         ret = emalloc(strlen(str) * 2 + 1);
253
254         p = str;
255         q = ret;
256         while (*p != '\0') {
257                 switch (*p) {
258
259                   case ' ':
260                   case '\t':
261                         *q++ = '\\';
262                         break;
263
264                   default:
265                         break;
266                 }
267                 *q++ = *p++;
268         }
269         *q++ = '\0';
270         return (ret);
271 }
272
273 char **
274 MAKEFLAGS_break(const char *str, int *pargc)
275 {
276         char *q, *start;
277         int len;
278
279         /* allocate room for a copy of the string */
280         if ((len = strlen(str) + 1) > curlen)
281                 buffer = erealloc(buffer, curlen = len);
282
283         start = NULL;
284         *pargc = 1;
285
286         for (q = buffer;;) {
287                 switch (*str) {
288                   case ' ':
289                   case '\t':
290                         /* word separator */
291                         if (start == NULL) {
292                                 /* not in a word */
293                                 str++;
294                                 continue;
295                         }
296                         /* FALLTHRU */
297                   case '\0':
298                         if (start == NULL)
299                                 goto done;
300
301                         /* finish word */
302                         *q++ = '\0';
303                         if (argmax == *pargc) {
304                                 argmax *= 2;
305                                 argv = erealloc(argv,
306                                     sizeof(*argv) * (argmax + 1));
307                         }
308                         argv[(*pargc)++] = start;
309                         start = NULL;
310
311                         if (*str++ == '\0')
312                                 goto done;
313                         continue;
314
315                   case '\\':
316                         if (str[1] == ' ' || str[1] == '\t')
317                                 /* was a quote */
318                                 str++;
319                         break;
320
321                   default:
322                         break;
323                 }
324                 if (start == NULL)
325                         /* start of new word */
326                         start = q;
327                 *q++ = *str++;
328         }
329   done:
330         argv[(*pargc)] = NULL;
331         return (argv);
332 }
333
334 /*
335  * Str_Match --
336  *
337  * See if a particular string matches a particular pattern.
338  *
339  * Results: Non-zero is returned if string matches pattern, 0 otherwise. The
340  * matching operation permits the following special characters in the
341  * pattern: *?\[] (see the man page for details on what these mean).
342  *
343  * Side effects: None.
344  */
345 int
346 Str_Match(const char *string, const char *pattern)
347 {
348         char c2;
349
350         for (;;) {
351                 /*
352                  * See if we're at the end of both the pattern and the
353                  * string. If, we succeeded.  If we're at the end of the
354                  * pattern but not at the end of the string, we failed.
355                  */
356                 if (*pattern == 0)
357                         return (!*string);
358                 if (*string == 0 && *pattern != '*')
359                         return (0);
360                 /*
361                  * Check for a "*" as the next pattern character.  It matches
362                  * any substring.  We handle this by calling ourselves
363                  * recursively for each postfix of string, until either we
364                  * match or we reach the end of the string.
365                  */
366                 if (*pattern == '*') {
367                         pattern += 1;
368                         if (*pattern == 0)
369                                 return (1);
370                         while (*string != 0) {
371                                 if (Str_Match(string, pattern))
372                                         return (1);
373                                 ++string;
374                         }
375                         return (0);
376                 }
377                 /*
378                  * Check for a "?" as the next pattern character.  It matches
379                  * any single character.
380                  */
381                 if (*pattern == '?')
382                         goto thisCharOK;
383                 /*
384                  * Check for a "[" as the next pattern character.  It is
385                  * followed by a list of characters that are acceptable, or
386                  * by a range (two characters separated by "-").
387                  */
388                 if (*pattern == '[') {
389                         ++pattern;
390                         for (;;) {
391                                 if ((*pattern == ']') || (*pattern == 0))
392                                         return (0);
393                                 if (*pattern == *string)
394                                         break;
395                                 if (pattern[1] == '-') {
396                                         c2 = pattern[2];
397                                         if (c2 == 0)
398                                                 return (0);
399                                         if ((*pattern <= *string) &&
400                                             (c2 >= *string))
401                                                 break;
402                                         if ((*pattern >= *string) &&
403                                             (c2 <= *string))
404                                                 break;
405                                         pattern += 2;
406                                 }
407                                 ++pattern;
408                         }
409                         while ((*pattern != ']') && (*pattern != 0))
410                                 ++pattern;
411                         goto thisCharOK;
412                 }
413                 /*
414                  * If the next pattern character is '/', just strip off the
415                  * '/' so we do exact matching on the character that follows.
416                  */
417                 if (*pattern == '\\') {
418                         ++pattern;
419                         if (*pattern == 0)
420                                 return (0);
421                 }
422                 /*
423                  * There's no special character.  Just make sure that the
424                  * next characters of each string match.
425                  */
426                 if (*pattern != *string)
427                         return (0);
428 thisCharOK:     ++pattern;
429                 ++string;
430         }
431 }
432
433
434 /*-
435  *-----------------------------------------------------------------------
436  * Str_SYSVMatch --
437  *      Check word against pattern for a match (% is wild),
438  *
439  * Results:
440  *      Returns the beginning position of a match or null. The number
441  *      of characters matched is returned in len.
442  *
443  * Side Effects:
444  *      None
445  *
446  *-----------------------------------------------------------------------
447  */
448 const char *
449 Str_SYSVMatch(const char *word, const char *pattern, int *len)
450 {
451     const char *p = pattern;
452     const char *w = word;
453     const char *m;
454
455     if (*w == '\0') {
456         /* Zero-length word cannot be matched against */
457         *len = 0;
458         return (NULL);
459     }
460
461     if (*p == '\0') {
462         /* Null pattern is the whole string */
463         *len = strlen(w);
464         return (w);
465     }
466
467     if ((m = strchr(p, '%')) != NULL) {
468         /* check that the prefix matches */
469         for (; p != m && *w && *w == *p; w++, p++)
470              continue;
471
472         if (p != m)
473             return (NULL);      /* No match */
474
475         if (*++p == '\0') {
476             /* No more pattern, return the rest of the string */
477             *len = strlen(w);
478             return (w);
479         }
480     }
481
482     m = w;
483
484     /* Find a matching tail */
485     do
486         if (strcmp(p, w) == 0) {
487             *len = w - m;
488             return (m);
489         }
490     while (*w++ != '\0');
491
492     return (NULL);
493 }
494
495
496 /*-
497  *-----------------------------------------------------------------------
498  * Str_SYSVSubst --
499  *      Substitute '%' on the pattern with len characters from src.
500  *      If the pattern does not contain a '%' prepend len characters
501  *      from src.
502  *
503  * Results:
504  *      None
505  *
506  * Side Effects:
507  *      Places result on buf
508  *
509  *-----------------------------------------------------------------------
510  */
511 void
512 Str_SYSVSubst(Buffer *buf, const char *pat, const char *src, int len)
513 {
514     const char *m;
515
516     if ((m = strchr(pat, '%')) != NULL) {
517         /* Copy the prefix */
518         Buf_AppendRange(buf, pat, m);
519         /* skip the % */
520         pat = m + 1;
521     }
522
523     /* Copy the pattern */
524     Buf_AddBytes(buf, len, (const Byte *)src);
525
526     /* append the rest */
527     Buf_Append(buf, pat);
528 }