Initial import of binutils 2.22 on the new vendor branch
[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.39 2005/08/05 22:42:12 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
52 /**
53  * Initialize the argument array object.  The array is initially
54  * eight positions, and will be expaned as necessary.  The first
55  * position is set to NULL since everything ignores it.  We allocate
56  * (size + 1) since we need space for the terminating NULL.  The
57  * buffer is set to NULL, since no common buffer is allocated yet.
58  */
59 void
60 ArgArray_Init(ArgArray *aa)
61 {
62
63         aa->size = 8;
64         aa->argv = emalloc((aa->size + 1) * sizeof(char *));
65         aa->argc = 0;
66         aa->argv[aa->argc++] = NULL;
67         aa->len = 0;
68         aa->buffer = NULL;
69 }
70
71 /**
72  * Cleanup the memory allocated for in the argument array object.
73  */
74 void
75 ArgArray_Done(ArgArray *aa)
76 {
77
78         if (aa->buffer == NULL) {
79                 int     i;
80                 /* args are individually allocated */
81                 for (i = 0; i < aa->argc; ++i) {
82                         if (aa->argv[i]) {
83                                 free(aa->argv[i]);
84                                 aa->argv[i] = NULL;
85                         }
86                 }
87         } else {
88                 /* args are part of a single allocation */
89                 free(aa->buffer);
90                 aa->buffer = NULL;
91         }
92         free(aa->argv);
93         aa->argv = NULL;
94         aa->argc = 0;
95         aa->size = 0;
96 }
97
98 /**
99  * Concatenate the two strings, possibily inserting a character between them.
100  *
101  * @returns
102  *      the resulting string in allocated space.
103  */
104 char *
105 str_concat(const char s1[], char c, const char s2[])
106 {
107         int len1, len2;
108         char *result;
109
110         /* get the length of both strings */
111         len1 = strlen(s1);
112         len2 = strlen(s2);
113
114         /* allocate length plus separator plus EOS */
115         result = emalloc(len1 + len2 + 2);
116
117         /* copy first string into place */
118         memcpy(result, s1, len1);
119
120         /* add separator character */
121         if (c != '\0') {
122                 result[len1] = c;
123                 ++len1;
124         }
125
126         /* copy second string plus EOS into place */
127         memcpy(result + len1, s2, len2 + 1);
128
129         return (result);
130 }
131
132 /**
133  * Fracture a string into an array of words (as delineated by tabs or
134  * spaces) taking quotation marks into account.  Leading tabs/spaces
135  * are ignored.
136  */
137 void
138 brk_string(ArgArray *aa, const char str[], bool expand)
139 {
140         char    inquote;
141         char    *start;
142         char    *arg;
143
144         /* skip leading space chars. */
145         for (; *str == ' ' || *str == '\t'; ++str)
146                 continue;
147
148         ArgArray_Init(aa);
149         aa->buffer = estrdup(str);
150
151         arg = aa->buffer;
152         start = arg;
153         inquote = '\0';
154
155         /*
156          * copy the string; at the same time, parse backslashes,
157          * quotes and build the argument list.
158          */
159         for (;;) {
160                 switch (str[0]) {
161                 case '"':
162                 case '\'':
163                         if (inquote == '\0') {
164                                 inquote = str[0];
165                                 if (expand)
166                                         break;
167                                 if (start == NULL)
168                                         start = arg;
169                         } else if (inquote == str[0]) {
170                                 inquote = '\0';
171                                 /* Don't miss "" or '' */
172                                 if (start == NULL)
173                                         start = arg;
174                                 if (expand)
175                                         break;
176                         } else {
177                                 /* other type of quote found */
178                                 if (start == NULL)
179                                         start = arg;
180                         }
181                         *arg++ = str[0];
182                         break;
183                 case ' ':
184                 case '\t':
185                 case '\n':
186                         if (inquote) {
187                                 if (start == NULL)
188                                         start = arg;
189                                 *arg++ = str[0];
190                                 break;
191                         }
192                         if (start == NULL)
193                                 break;
194                         /* FALLTHROUGH */
195                 case '\0':
196                         /*
197                          * end of a token -- make sure there's enough argv
198                          * space and save off a pointer.
199                          */
200                         if (aa->argc == aa->size) {
201                                 aa->size *= 2;          /* ramp up fast */
202                                 aa->argv = erealloc(aa->argv,
203                                     (aa->size + 1) * sizeof(char *));
204                         }
205
206                         *arg++ = '\0';
207                         if (start == NULL) {
208                                 aa->argv[aa->argc] = start;
209                                 return;
210                         }
211                         if (str[0] == '\n' || str[0] == '\0') {
212                                 aa->argv[aa->argc++] = start;
213                                 aa->argv[aa->argc] = NULL;
214                                 return;
215                         } else {
216                                 aa->argv[aa->argc++] = start;
217                                 start = NULL;
218                                 break;
219                         }
220                 case '\\':
221                         if (start == NULL)
222                                 start = arg;
223                         if (expand) {
224                                 switch (str[1]) {
225                                 case '\0':
226                                 case '\n':
227                                         /* hmmm; fix it up as best we can */
228                                         *arg++ = '\\';
229                                         break;
230                                 case 'b':
231                                         *arg++ = '\b';
232                                         ++str;
233                                         break;
234                                 case 'f':
235                                         *arg++ = '\f';
236                                         ++str;
237                                         break;
238                                 case 'n':
239                                         *arg++ = '\n';
240                                         ++str;
241                                         break;
242                                 case 'r':
243                                         *arg++ = '\r';
244                                         ++str;
245                                         break;
246                                 case 't':
247                                         *arg++ = '\t';
248                                         ++str;
249                                         break;
250                                 default:
251                                         *arg++ = str[1];
252                                         ++str;
253                                         break;
254                                 }
255                         } else {
256                                 *arg++ = str[0];
257                                 ++str;
258                                 *arg++ = str[0];
259                         }
260                         break;
261                 default:
262                         if (start == NULL)
263                                 start = arg;
264                         *arg++ = str[0];
265                         break;
266                 }
267                 ++str;
268         }
269 }
270
271 /*
272  * Quote a string for appending it to MAKEFLAGS. According to Posix the
273  * kind of quoting here is implementation-defined. This quoting must ensure
274  * that the parsing of MAKEFLAGS's contents in a sub-shell yields the same
275  * options, option arguments and macro definitions as in the calling make.
276  * We simply quote all blanks, which according to Posix are space and tab
277  * in the POSIX locale. Don't use isblank because in that case makes with
278  * different locale settings could not communicate. We must also quote
279  * backslashes obviously.
280  */
281 char *
282 MAKEFLAGS_quote(const char *str)
283 {
284         char *ret, *q;
285         const char *p;
286
287         /* assume worst case - everything has to be quoted */
288         ret = emalloc(strlen(str) * 2 + 1);
289
290         p = str;
291         q = ret;
292         while (*p != '\0') {
293                 switch (*p) {
294
295                   case ' ':
296                   case '\t':
297                         *q++ = '\\';
298                         break;
299
300                   default:
301                         break;
302                 }
303                 *q++ = *p++;
304         }
305         *q++ = '\0';
306         return (ret);
307 }
308
309 void
310 MAKEFLAGS_break(ArgArray *aa, const char str[])
311 {
312         char    *arg;
313         char    *start;
314
315         ArgArray_Init(aa);
316         aa->buffer = strdup(str);
317
318         arg = aa->buffer;
319         start = NULL;
320
321         for (;;) {
322                 switch (str[0]) {
323                 case ' ':
324                 case '\t':
325                         /* word separator */
326                         if (start == NULL) {
327                                 /* not in a word */
328                                 str++;
329                                 continue;
330                         }
331                         /* FALLTHRU */
332                 case '\0':
333                         if (aa->argc == aa->size) {
334                                 aa->size *= 2;
335                                 aa->argv = erealloc(aa->argv,
336                                     (aa->size + 1) * sizeof(char *));
337                         }
338
339                         *arg++ = '\0';
340                         if (start == NULL) {
341                                 aa->argv[aa->argc] = start;
342                                 return;
343                         }
344                         if (str[0] == '\0') {
345                                 aa->argv[aa->argc++] = start;
346                                 aa->argv[aa->argc] = NULL;
347                                 return;
348                         } else {
349                                 aa->argv[aa->argc++] = start;
350                                 start = NULL;
351                                 str++;
352                                 continue;
353                         }
354
355                 case '\\':
356                         if (str[1] == ' ' || str[1] == '\t')
357                                 str++;
358                         break;
359
360                 default:
361                         break;
362                 }
363                 if (start == NULL)
364                         start = arg;
365                 *arg++ = *str++;
366         }
367 }
368
369 /*
370  * Str_Match --
371  *
372  * See if a particular string matches a particular pattern.
373  *
374  * Results: Non-zero is returned if string matches pattern, 0 otherwise. The
375  * matching operation permits the following special characters in the
376  * pattern: *?\[] (see the man page for details on what these mean).
377  *
378  * Side effects: None.
379  */
380 int
381 Str_Match(const char *string, const char *pattern)
382 {
383         char c2;
384
385         for (;;) {
386                 /*
387                  * See if we're at the end of both the pattern and the
388                  * string. If, we succeeded.  If we're at the end of the
389                  * pattern but not at the end of the string, we failed.
390                  */
391                 if (*pattern == 0)
392                         return (!*string);
393                 if (*string == 0 && *pattern != '*')
394                         return (0);
395                 /*
396                  * Check for a "*" as the next pattern character.  It matches
397                  * any substring.  We handle this by calling ourselves
398                  * recursively for each postfix of string, until either we
399                  * match or we reach the end of the string.
400                  */
401                 if (*pattern == '*') {
402                         pattern += 1;
403                         if (*pattern == 0)
404                                 return (1);
405                         while (*string != 0) {
406                                 if (Str_Match(string, pattern))
407                                         return (1);
408                                 ++string;
409                         }
410                         return (0);
411                 }
412                 /*
413                  * Check for a "?" as the next pattern character.  It matches
414                  * any single character.
415                  */
416                 if (*pattern == '?')
417                         goto thisCharOK;
418                 /*
419                  * Check for a "[" as the next pattern character.  It is
420                  * followed by a list of characters that are acceptable, or
421                  * by a range (two characters separated by "-").
422                  */
423                 if (*pattern == '[') {
424                         ++pattern;
425                         for (;;) {
426                                 if ((*pattern == ']') || (*pattern == 0))
427                                         return (0);
428                                 if (*pattern == *string)
429                                         break;
430                                 if (pattern[1] == '-') {
431                                         c2 = pattern[2];
432                                         if (c2 == 0)
433                                                 return (0);
434                                         if ((*pattern <= *string) &&
435                                             (c2 >= *string))
436                                                 break;
437                                         if ((*pattern >= *string) &&
438                                             (c2 <= *string))
439                                                 break;
440                                         pattern += 2;
441                                 }
442                                 ++pattern;
443                         }
444                         while ((*pattern != ']') && (*pattern != 0))
445                                 ++pattern;
446                         goto thisCharOK;
447                 }
448                 /*
449                  * If the next pattern character is '/', just strip off the
450                  * '/' so we do exact matching on the character that follows.
451                  */
452                 if (*pattern == '\\') {
453                         ++pattern;
454                         if (*pattern == 0)
455                                 return (0);
456                 }
457                 /*
458                  * There's no special character.  Just make sure that the
459                  * next characters of each string match.
460                  */
461                 if (*pattern != *string)
462                         return (0);
463 thisCharOK:     ++pattern;
464                 ++string;
465         }
466 }
467
468
469 /**
470  * Str_SYSVMatch
471  *      Check word against pattern for a match (% is wild),
472  *
473  * Results:
474  *      Returns the beginning position of a match or null. The number
475  *      of characters matched is returned in len.
476  */
477 const char *
478 Str_SYSVMatch(const char *word, const char *pattern, int *len)
479 {
480         const char *m, *p, *w;
481
482         p = pattern;
483         w = word;
484
485         if (*w == '\0') {
486                 /* Zero-length word cannot be matched against */
487                 *len = 0;
488                 return (NULL);
489         }
490
491         if (*p == '\0') {
492                 /* Null pattern is the whole string */
493                 *len = strlen(w);
494                 return (w);
495         }
496
497         if ((m = strchr(p, '%')) != NULL) {
498                 /* check that the prefix matches */
499                 for (; p != m && *w && *w == *p; w++, p++)
500                         continue;
501
502                 if (p != m)
503                         return (NULL);  /* No match */
504
505                 if (*++p == '\0') {
506                         /* No more pattern, return the rest of the string */
507                         *len = strlen(w);
508                         return (w);
509                 }
510         }
511
512         m = w;
513
514         /* Find a matching tail */
515         do
516                 if (strcmp(p, w) == 0) {
517                         *len = w - m;
518                         return (m);
519                 }
520         while (*w++ != '\0');
521
522         return (NULL);
523 }
524
525
526 /**
527  * Str_SYSVSubst
528  *      Substitute '%' on the pattern with len characters from src.
529  *      If the pattern does not contain a '%' prepend len characters
530  *      from src.
531  *
532  * Side Effects:
533  *      Places result on buf
534  */
535 void
536 Str_SYSVSubst(Buffer *buf, const char *pat, const char *src, int len)
537 {
538         const char *m;
539
540         if ((m = strchr(pat, '%')) != NULL) {
541                 /* Copy the prefix */
542                 Buf_AppendRange(buf, pat, m);
543                 /* skip the % */
544                 pat = m + 1;
545         }
546
547         /* Copy the pattern */
548         Buf_AddBytes(buf, len, src);
549
550         /* append the rest */
551         Buf_Append(buf, pat);
552 }