xref: /freebsd/contrib/bmake/str.c (revision 767173cec2b2041e1f847bc8896092f9c1481242)
1 /*	$NetBSD: str.c,v 1.42 2020/05/06 02:30:10 christos 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.42 2020/05/06 02:30:10 christos 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.42 2020/05/06 02:30:10 christos 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.
133  *
134  * returns --
135  *	Pointer to the array of pointers to the words.
136  *      Memory containing the actual words in *store_words_buf.
137  *		Both of these must be free'd by the caller.
138  *      Number of words in *store_words_len.
139  */
140 char **
141 brk_string(const char *str, int *store_words_len, Boolean expand,
142 	char **store_words_buf)
143 {
144 	char inquote;
145 	const char *str_p;
146 	size_t str_len;
147     	char **words;
148 	int words_len;
149 	int words_cap = 50;
150 	char *words_buf, *word_start, *word_end;
151 
152 	/* skip leading space chars. */
153 	for (; *str == ' ' || *str == '\t'; ++str)
154 		continue;
155 
156 	/* words_buf holds the words, separated by '\0'. */
157 	str_len = strlen(str);
158 	words_buf = bmake_malloc(strlen(str) + 1);
159 
160 	words_cap = MAX((str_len / 5), 50);
161 	words = bmake_malloc((words_cap + 1) * sizeof(char *));
162 
163 	/*
164 	 * copy the string; at the same time, parse backslashes,
165 	 * quotes and build the word list.
166 	 */
167 	words_len = 0;
168 	inquote = '\0';
169 	word_start = word_end = words_buf;
170 	for (str_p = str;; ++str_p) {
171 		char ch = *str_p;
172 		switch(ch) {
173 		case '"':
174 		case '\'':
175 			if (inquote) {
176 				if (inquote == ch)
177 					inquote = '\0';
178 				else
179 					break;
180 			}
181 			else {
182 				inquote = (char) ch;
183 				/* Don't miss "" or '' */
184 				if (word_start == NULL && str_p[1] == inquote) {
185 					if (!expand) {
186 						word_start = word_end;
187 						*word_end++ = ch;
188 					} else
189 						word_start = word_end + 1;
190 					str_p++;
191 					inquote = '\0';
192 					break;
193 				}
194 			}
195 			if (!expand) {
196 				if (word_start == NULL)
197 					word_start = word_end;
198 				*word_end++ = ch;
199 			}
200 			continue;
201 		case ' ':
202 		case '\t':
203 		case '\n':
204 			if (inquote)
205 				break;
206 			if (word_start == NULL)
207 				continue;
208 			/* FALLTHROUGH */
209 		case '\0':
210 			/*
211 			 * end of a token -- make sure there's enough words
212 			 * space and save off a pointer.
213 			 */
214 			if (word_start == NULL)
215 			    goto done;
216 
217 			*word_end++ = '\0';
218 			if (words_len == words_cap) {
219 				words_cap *= 2;		/* ramp up fast */
220 				words = (char **)bmake_realloc(words,
221 				    (words_cap + 1) * sizeof(char *));
222 			}
223 			words[words_len++] = word_start;
224 			word_start = NULL;
225 			if (ch == '\n' || ch == '\0') {
226 				if (expand && inquote) {
227 					free(words);
228 					free(words_buf);
229 					*store_words_buf = NULL;
230 					return NULL;
231 				}
232 				goto done;
233 			}
234 			continue;
235 		case '\\':
236 			if (!expand) {
237 				if (word_start == NULL)
238 					word_start = word_end;
239 				*word_end++ = '\\';
240 				/* catch '\' at end of line */
241 				if (str_p[1] == '\0')
242 					continue;
243 				ch = *++str_p;
244 				break;
245 			}
246 
247 			switch (ch = *++str_p) {
248 			case '\0':
249 			case '\n':
250 				/* hmmm; fix it up as best we can */
251 				ch = '\\';
252 				--str_p;
253 				break;
254 			case 'b':
255 				ch = '\b';
256 				break;
257 			case 'f':
258 				ch = '\f';
259 				break;
260 			case 'n':
261 				ch = '\n';
262 				break;
263 			case 'r':
264 				ch = '\r';
265 				break;
266 			case 't':
267 				ch = '\t';
268 				break;
269 			}
270 			break;
271 		}
272 		if (word_start == NULL)
273 			word_start = word_end;
274 		*word_end++ = ch;
275 	}
276 done:	words[words_len] = NULL;
277 	*store_words_len = words_len;
278 	*store_words_buf = words_buf;
279 	return words;
280 }
281 
282 /*
283  * Str_FindSubstring -- See if a string contains a particular substring.
284  *
285  * Input:
286  *	string		String to search.
287  *	substring	Substring to find in string.
288  *
289  * Results: If string contains substring, the return value is the location of
290  * the first matching instance of substring in string.  If string doesn't
291  * contain substring, the return value is NULL.  Matching is done on an exact
292  * character-for-character basis with no wildcards or special characters.
293  *
294  * Side effects: None.
295  */
296 char *
297 Str_FindSubstring(const char *string, const char *substring)
298 {
299 	const char *a, *b;
300 
301 	/*
302 	 * First scan quickly through the two strings looking for a single-
303 	 * character match.  When it's found, then compare the rest of the
304 	 * substring.
305 	 */
306 
307 	for (b = substring; *string != 0; string += 1) {
308 		if (*string != *b)
309 			continue;
310 		a = string;
311 		for (;;) {
312 			if (*b == 0)
313 				return UNCONST(string);
314 			if (*a++ != *b++)
315 				break;
316 		}
317 		b = substring;
318 	}
319 	return NULL;
320 }
321 
322 /*
323  * Str_Match --
324  *
325  * See if a particular string matches a particular pattern.
326  *
327  * Results: Non-zero is returned if string matches pattern, 0 otherwise. The
328  * matching operation permits the following special characters in the
329  * pattern: *?\[] (see the man page for details on what these mean).
330  *
331  * XXX this function does not detect or report malformed patterns.
332  *
333  * Side effects: None.
334  */
335 int
336 Str_Match(const char *string, const char *pattern)
337 {
338 	char c2;
339 
340 	for (;;) {
341 		/*
342 		 * See if we're at the end of both the pattern and the
343 		 * string. If, we succeeded.  If we're at the end of the
344 		 * pattern but not at the end of the string, we failed.
345 		 */
346 		if (*pattern == 0)
347 			return(!*string);
348 		if (*string == 0 && *pattern != '*')
349 			return(0);
350 		/*
351 		 * Check for a "*" as the next pattern character.  It matches
352 		 * any substring.  We handle this by calling ourselves
353 		 * recursively for each postfix of string, until either we
354 		 * match or we reach the end of the string.
355 		 */
356 		if (*pattern == '*') {
357 			pattern += 1;
358 			if (*pattern == 0)
359 				return(1);
360 			while (*string != 0) {
361 				if (Str_Match(string, pattern))
362 					return(1);
363 				++string;
364 			}
365 			return(0);
366 		}
367 		/*
368 		 * Check for a "?" as the next pattern character.  It matches
369 		 * any single character.
370 		 */
371 		if (*pattern == '?')
372 			goto thisCharOK;
373 		/*
374 		 * Check for a "[" as the next pattern character.  It is
375 		 * followed by a list of characters that are acceptable, or
376 		 * by a range (two characters separated by "-").
377 		 */
378 		if (*pattern == '[') {
379 			int nomatch;
380 
381 			++pattern;
382 			if (*pattern == '^') {
383 				++pattern;
384 				nomatch = 1;
385 			} else
386 				nomatch = 0;
387 			for (;;) {
388 				if ((*pattern == ']') || (*pattern == 0)) {
389 					if (nomatch)
390 						break;
391 					return(0);
392 				}
393 				if (*pattern == *string)
394 					break;
395 				if (pattern[1] == '-') {
396 					c2 = pattern[2];
397 					if (c2 == 0)
398 						return(nomatch);
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 			if (nomatch && (*pattern != ']') && (*pattern != 0))
410 				return 0;
411 			while ((*pattern != ']') && (*pattern != 0))
412 				++pattern;
413 			if (*pattern == 0)
414 				--pattern;
415 			goto thisCharOK;
416 		}
417 		/*
418 		 * If the next pattern character is '/', just strip off the
419 		 * '/' so we do exact matching on the character that follows.
420 		 */
421 		if (*pattern == '\\') {
422 			++pattern;
423 			if (*pattern == 0)
424 				return(0);
425 		}
426 		/*
427 		 * There's no special character.  Just make sure that the
428 		 * next characters of each string match.
429 		 */
430 		if (*pattern != *string)
431 			return(0);
432 thisCharOK:	++pattern;
433 		++string;
434 	}
435 }
436 
437 
438 /*-
439  *-----------------------------------------------------------------------
440  * Str_SYSVMatch --
441  *	Check word against pattern for a match (% is wild),
442  *
443  * Input:
444  *	word		Word to examine
445  *	pattern		Pattern to examine against
446  *	len		Number of characters to substitute
447  *
448  * Results:
449  *	Returns the beginning position of a match or null. The number
450  *	of characters matched is returned in len.
451  *
452  * Side Effects:
453  *	None
454  *
455  *-----------------------------------------------------------------------
456  */
457 char *
458 Str_SYSVMatch(const char *word, const char *pattern, size_t *len,
459     Boolean *hasPercent)
460 {
461     const char *p = pattern;
462     const char *w = word;
463     const char *m;
464 
465     *hasPercent = FALSE;
466     if (*p == '\0') {
467 	/* Null pattern is the whole string */
468 	*len = strlen(w);
469 	return UNCONST(w);
470     }
471 
472     if ((m = strchr(p, '%')) != NULL) {
473 	*hasPercent = TRUE;
474 	if (*w == '\0') {
475 		/* empty word does not match pattern */
476 		return NULL;
477 	}
478 	/* check that the prefix matches */
479 	for (; p != m && *w && *w == *p; w++, p++)
480 	     continue;
481 
482 	if (p != m)
483 	    return NULL;	/* No match */
484 
485 	if (*++p == '\0') {
486 	    /* No more pattern, return the rest of the string */
487 	    *len = strlen(w);
488 	    return UNCONST(w);
489 	}
490     }
491 
492     m = w;
493 
494     /* Find a matching tail */
495     do
496 	if (strcmp(p, w) == 0) {
497 	    *len = w - m;
498 	    return UNCONST(m);
499 	}
500     while (*w++ != '\0');
501 
502     return NULL;
503 }
504 
505 
506 /*-
507  *-----------------------------------------------------------------------
508  * Str_SYSVSubst --
509  *	Substitute '%' on the pattern with len characters from src.
510  *	If the pattern does not contain a '%' prepend len characters
511  *	from src.
512  *
513  * Results:
514  *	None
515  *
516  * Side Effects:
517  *	Places result on buf
518  *
519  *-----------------------------------------------------------------------
520  */
521 void
522 Str_SYSVSubst(Buffer *buf, char *pat, char *src, size_t len,
523     Boolean lhsHasPercent)
524 {
525     char *m;
526 
527     if ((m = strchr(pat, '%')) != NULL && lhsHasPercent) {
528 	/* Copy the prefix */
529 	Buf_AddBytes(buf, m - pat, pat);
530 	/* skip the % */
531 	pat = m + 1;
532     }
533     if (m != NULL || !lhsHasPercent) {
534 	/* Copy the pattern */
535 	Buf_AddBytes(buf, len, src);
536     }
537 
538     /* append the rest */
539     Buf_AddBytes(buf, strlen(pat), pat);
540 }
541