Home | History | Annotate | Line # | Download | only in make
str.c revision 1.56
      1 /*	$NetBSD: str.c,v 1.56 2020/08/09 10:24:02 rillig Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1988, 1989, 1990, 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  * 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. 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 /*-
     36  * Copyright (c) 1989 by Berkeley Softworks
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * Adam de Boor.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 #ifndef MAKE_NATIVE
     72 static char rcsid[] = "$NetBSD: str.c,v 1.56 2020/08/09 10:24:02 rillig Exp $";
     73 #else
     74 #include <sys/cdefs.h>
     75 #ifndef lint
     76 #if 0
     77 static char     sccsid[] = "@(#)str.c	5.8 (Berkeley) 6/1/90";
     78 #else
     79 __RCSID("$NetBSD: str.c,v 1.56 2020/08/09 10:24:02 rillig Exp $");
     80 #endif
     81 #endif				/* not lint */
     82 #endif
     83 
     84 #include "make.h"
     85 
     86 /*-
     87  * str_concat --
     88  *	concatenate the two strings, inserting a space or slash between them,
     89  *	freeing them if requested.
     90  *
     91  * returns --
     92  *	the resulting string in allocated space.
     93  */
     94 char *
     95 str_concat(const char *s1, const char *s2, int flags)
     96 {
     97 	int len1, len2;
     98 	char *result;
     99 
    100 	/* get the length of both strings */
    101 	len1 = strlen(s1);
    102 	len2 = strlen(s2);
    103 
    104 	/* allocate length plus separator plus EOS */
    105 	result = bmake_malloc((unsigned int)(len1 + len2 + 2));
    106 
    107 	/* copy first string into place */
    108 	memcpy(result, s1, len1);
    109 
    110 	/* add separator character */
    111 	if (flags & STR_ADDSPACE) {
    112 		result[len1] = ' ';
    113 		++len1;
    114 	} else if (flags & STR_ADDSLASH) {
    115 		result[len1] = '/';
    116 		++len1;
    117 	}
    118 
    119 	/* copy second string plus EOS into place */
    120 	memcpy(result + len1, s2, len2 + 1);
    121 
    122 	return result;
    123 }
    124 
    125 /*-
    126  * brk_string --
    127  *	Fracture a string into an array of words (as delineated by tabs or
    128  *	spaces) taking quotation marks into account.  Leading tabs/spaces
    129  *	are ignored.
    130  *
    131  *	If expand is TRUE, quotes are removed and escape sequences
    132  *	such as \r, \t, etc... are expanded. In this case, the return value
    133  *	is NULL on parse errors.
    134  *
    135  * returns --
    136  *	Pointer to the array of pointers to the words.
    137  *	Memory containing the actual words in *out_words_buf.
    138  *	Both of these must be free'd by the caller.
    139  *	Number of words in *out_words_len.
    140  */
    141 char **
    142 brk_string(const char *str, int *out_words_len, Boolean expand,
    143 	   char **out_words_buf)
    144 {
    145 	size_t str_len;
    146 	char *words_buf;
    147 	int words_cap;
    148 	char **words;
    149 	int words_len;
    150 	char inquote;
    151 	char *word_start;
    152 	char *word_end;
    153 	const char *str_p;
    154 
    155 	/* skip leading space chars. */
    156 	for (; *str == ' ' || *str == '\t'; ++str)
    157 		continue;
    158 
    159 	/* words_buf holds the words, separated by '\0'. */
    160 	str_len = strlen(str);
    161 	words_buf = bmake_malloc(strlen(str) + 1);
    162 
    163 	words_cap = MAX((str_len / 5), 50);
    164 	words = bmake_malloc((words_cap + 1) * sizeof(char *));
    165 
    166 	/*
    167 	 * copy the string; at the same time, parse backslashes,
    168 	 * quotes and build the word list.
    169 	 */
    170 	words_len = 0;
    171 	inquote = '\0';
    172 	word_start = words_buf;
    173 	word_end = words_buf;
    174 	for (str_p = str;; ++str_p) {
    175 		char ch = *str_p;
    176 		switch (ch) {
    177 		case '"':
    178 		case '\'':
    179 			if (inquote) {
    180 				if (inquote == ch)
    181 					inquote = '\0';
    182 				else
    183 					break;
    184 			} else {
    185 				inquote = (char)ch;
    186 				/* Don't miss "" or '' */
    187 				if (word_start == NULL && str_p[1] == inquote) {
    188 					if (!expand) {
    189 						word_start = word_end;
    190 						*word_end++ = ch;
    191 					} else
    192 						word_start = word_end + 1;
    193 					str_p++;
    194 					inquote = '\0';
    195 					break;
    196 				}
    197 			}
    198 			if (!expand) {
    199 				if (word_start == NULL)
    200 					word_start = word_end;
    201 				*word_end++ = ch;
    202 			}
    203 			continue;
    204 		case ' ':
    205 		case '\t':
    206 		case '\n':
    207 			if (inquote)
    208 				break;
    209 			if (word_start == NULL)
    210 				continue;
    211 			/* FALLTHROUGH */
    212 		case '\0':
    213 			/*
    214 			 * end of a token -- make sure there's enough words
    215 			 * space and save off a pointer.
    216 			 */
    217 			if (word_start == NULL)
    218 				goto done;
    219 
    220 			*word_end++ = '\0';
    221 			if (words_len == words_cap) {
    222 				size_t new_size;
    223 				words_cap *= 2;		/* ramp up fast */
    224 				new_size = (words_cap + 1) * sizeof(char *);
    225 				words = bmake_realloc(words, new_size);
    226 			}
    227 			words[words_len++] = word_start;
    228 			word_start = NULL;
    229 			if (ch == '\n' || ch == '\0') {
    230 				if (expand && inquote) {
    231 					free(words);
    232 					free(words_buf);
    233 					*out_words_buf = NULL;
    234 					return NULL;
    235 				}
    236 				goto done;
    237 			}
    238 			continue;
    239 		case '\\':
    240 			if (!expand) {
    241 				if (word_start == NULL)
    242 					word_start = word_end;
    243 				*word_end++ = '\\';
    244 				/* catch '\' at end of line */
    245 				if (str_p[1] == '\0')
    246 					continue;
    247 				ch = *++str_p;
    248 				break;
    249 			}
    250 
    251 			switch (ch = *++str_p) {
    252 			case '\0':
    253 			case '\n':
    254 				/* hmmm; fix it up as best we can */
    255 				ch = '\\';
    256 				--str_p;
    257 				break;
    258 			case 'b':
    259 				ch = '\b';
    260 				break;
    261 			case 'f':
    262 				ch = '\f';
    263 				break;
    264 			case 'n':
    265 				ch = '\n';
    266 				break;
    267 			case 'r':
    268 				ch = '\r';
    269 				break;
    270 			case 't':
    271 				ch = '\t';
    272 				break;
    273 			}
    274 			break;
    275 		}
    276 		if (word_start == NULL)
    277 			word_start = word_end;
    278 		*word_end++ = ch;
    279 	}
    280 done:
    281 	words[words_len] = NULL;
    282 	*out_words_len = words_len;
    283 	*out_words_buf = words_buf;
    284 	return words;
    285 }
    286 
    287 /*
    288  * Str_FindSubstring -- See if a string contains a particular substring.
    289  *
    290  * Input:
    291  *	string		String to search.
    292  *	substring	Substring to find in string.
    293  *
    294  * Results: If string contains substring, the return value is the location of
    295  * the first matching instance of substring in string.  If string doesn't
    296  * contain substring, the return value is NULL.  Matching is done on an exact
    297  * character-for-character basis with no wildcards or special characters.
    298  *
    299  * Side effects: None.
    300  */
    301 char *
    302 Str_FindSubstring(const char *string, const char *substring)
    303 {
    304 	const char *a, *b;
    305 
    306 	/*
    307 	 * First scan quickly through the two strings looking for a single-
    308 	 * character match.  When it's found, then compare the rest of the
    309 	 * substring.
    310 	 */
    311 
    312 	for (b = substring; *string != 0; string++) {
    313 		if (*string != *b)
    314 			continue;
    315 		a = string;
    316 		for (;;) {
    317 			if (*b == 0)
    318 				return UNCONST(string);
    319 			if (*a++ != *b++)
    320 				break;
    321 		}
    322 		b = substring;
    323 	}
    324 	return NULL;
    325 }
    326 
    327 /*
    328  * Str_Match -- Test if a string matches a pattern like "*.[ch]".
    329  *
    330  * XXX this function does not detect or report malformed patterns.
    331  *
    332  * Results:
    333  *	Non-zero is returned if string matches the pattern, 0 otherwise. The
    334  *	matching operation permits the following special characters in the
    335  *	pattern: *?\[] (as in fnmatch(3)).
    336  *
    337  * Side effects: None.
    338  */
    339 Boolean
    340 Str_Match(const char *str, const char *pat)
    341 {
    342 	for (;;) {
    343 		/*
    344 		 * See if we're at the end of both the pattern and the
    345 		 * string. If, we succeeded.  If we're at the end of the
    346 		 * pattern but not at the end of the string, we failed.
    347 		 */
    348 		if (*pat == 0)
    349 			return *str == 0;
    350 		if (*str == 0 && *pat != '*')
    351 			return FALSE;
    352 
    353 		/*
    354 		 * A '*' in the pattern matches any substring.  We handle this
    355 		 * by calling ourselves for each suffix of the string.
    356 		 */
    357 		if (*pat == '*') {
    358 			pat++;
    359 			while (*pat == '*')
    360 				pat++;
    361 			if (*pat == 0)
    362 				return TRUE;
    363 			while (*str != 0) {
    364 				if (Str_Match(str, pat))
    365 					return TRUE;
    366 				str++;
    367 			}
    368 			return FALSE;
    369 		}
    370 
    371 		/* A '?' in the pattern matches any single character. */
    372 		if (*pat == '?')
    373 			goto thisCharOK;
    374 
    375 		/*
    376 		 * A '[' in the pattern matches a character from a list.
    377 		 * The '[' is followed by the list of acceptable characters,
    378 		 * or by ranges (two characters separated by '-'). In these
    379 		 * character lists, the backslash is an ordinary character.
    380 		 */
    381 		if (*pat == '[') {
    382 			Boolean neg = pat[1] == '^';
    383 			pat += 1 + neg;
    384 
    385 			for (;;) {
    386 				if (*pat == ']' || *pat == 0) {
    387 					if (neg)
    388 						break;
    389 					return FALSE;
    390 				}
    391 				if (*pat == *str)
    392 					break;
    393 				if (pat[1] == '-') {
    394 					if (pat[2] == 0)
    395 						return neg;
    396 					if (*pat <= *str && pat[2] >= *str)
    397 						break;
    398 					if (*pat >= *str && pat[2] <= *str)
    399 						break;
    400 					pat += 2;
    401 				}
    402 				pat++;
    403 			}
    404 			if (neg && *pat != ']' && *pat != 0)
    405 				return FALSE;
    406 			while (*pat != ']' && *pat != 0)
    407 				pat++;
    408 			if (*pat == 0)
    409 				pat--;
    410 			goto thisCharOK;
    411 		}
    412 
    413 		/*
    414 		 * A backslash in the pattern matches the character following
    415 		 * it exactly.
    416 		 */
    417 		if (*pat == '\\') {
    418 			pat++;
    419 			if (*pat == 0)
    420 				return FALSE;
    421 		}
    422 
    423 		if (*pat != *str)
    424 			return FALSE;
    425 
    426 	thisCharOK:
    427 		pat++;
    428 		str++;
    429 	}
    430 }
    431