xref: /netbsd-src/usr.bin/make/str.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /*	$NetBSD: str.c,v 1.60 2020/08/11 18:41:46 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.60 2020/08/11 18:41:46 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.60 2020/08/11 18:41:46 rillig Exp $");
80 #endif
81 #endif				/* not lint */
82 #endif
83 
84 #include "make.h"
85 
86 /* Return the concatenation of s1 and s2, freshly allocated. */
87 char *
88 str_concat2(const char *s1, const char *s2)
89 {
90 	size_t len1 = strlen(s1);
91 	size_t len2 = strlen(s2);
92 	char *result = bmake_malloc(len1 + len2 + 1);
93 	memcpy(result, s1, len1);
94 	memcpy(result + len1, s2, len2 + 1);
95 	return result;
96 }
97 
98 /* Return the concatenation of s1, s2 and s3, freshly allocated. */
99 char *
100 str_concat3(const char *s1, const char *s2, const char *s3)
101 {
102 	size_t len1 = strlen(s1);
103 	size_t len2 = strlen(s2);
104 	size_t len3 = strlen(s3);
105 	char *result = bmake_malloc(len1 + len2 + len3 + 1);
106 	memcpy(result, s1, len1);
107 	memcpy(result + len1, s2, len2);
108 	memcpy(result + len1 + len2, s3, len3 + 1);
109 	return result;
110 }
111 
112 /* Return the concatenation of s1, s2, s3 and s4, freshly allocated. */
113 char *
114 str_concat4(const char *s1, const char *s2, const char *s3, const char *s4)
115 {
116 	size_t len1 = strlen(s1);
117 	size_t len2 = strlen(s2);
118 	size_t len3 = strlen(s3);
119 	size_t len4 = strlen(s4);
120 	char *result = bmake_malloc(len1 + len2 + len3 + len4 + 1);
121 	memcpy(result, s1, len1);
122 	memcpy(result + len1, s2, len2);
123 	memcpy(result + len1 + len2, s3, len3);
124 	memcpy(result + len1 + len2 + len3, s4, len4 + 1);
125 	return result;
126 }
127 
128 /*-
129  * brk_string --
130  *	Fracture a string into an array of words (as delineated by tabs or
131  *	spaces) taking quotation marks into account.  Leading tabs/spaces
132  *	are ignored.
133  *
134  *	If expand is TRUE, quotes are removed and escape sequences
135  *	such as \r, \t, etc... are expanded. In this case, the return value
136  *	is NULL on parse errors.
137  *
138  * returns --
139  *	Pointer to the array of pointers to the words.
140  *	Memory containing the actual words in *out_words_buf.
141  *	Both of these must be free'd by the caller.
142  *	Number of words in *out_words_len.
143  */
144 char **
145 brk_string(const char *str, int *out_words_len, Boolean expand,
146 	   char **out_words_buf)
147 {
148 	size_t str_len;
149 	char *words_buf;
150 	int words_cap;
151 	char **words;
152 	int words_len;
153 	char inquote;
154 	char *word_start;
155 	char *word_end;
156 	const char *str_p;
157 
158 	/* skip leading space chars. */
159 	for (; *str == ' ' || *str == '\t'; ++str)
160 		continue;
161 
162 	/* words_buf holds the words, separated by '\0'. */
163 	str_len = strlen(str);
164 	words_buf = bmake_malloc(strlen(str) + 1);
165 
166 	words_cap = MAX((str_len / 5), 50);
167 	words = bmake_malloc((words_cap + 1) * sizeof(char *));
168 
169 	/*
170 	 * copy the string; at the same time, parse backslashes,
171 	 * quotes and build the word list.
172 	 */
173 	words_len = 0;
174 	inquote = '\0';
175 	word_start = words_buf;
176 	word_end = words_buf;
177 	for (str_p = str;; ++str_p) {
178 		char ch = *str_p;
179 		switch (ch) {
180 		case '"':
181 		case '\'':
182 			if (inquote) {
183 				if (inquote == ch)
184 					inquote = '\0';
185 				else
186 					break;
187 			} else {
188 				inquote = (char)ch;
189 				/* Don't miss "" or '' */
190 				if (word_start == NULL && str_p[1] == inquote) {
191 					if (!expand) {
192 						word_start = word_end;
193 						*word_end++ = ch;
194 					} else
195 						word_start = word_end + 1;
196 					str_p++;
197 					inquote = '\0';
198 					break;
199 				}
200 			}
201 			if (!expand) {
202 				if (word_start == NULL)
203 					word_start = word_end;
204 				*word_end++ = ch;
205 			}
206 			continue;
207 		case ' ':
208 		case '\t':
209 		case '\n':
210 			if (inquote)
211 				break;
212 			if (word_start == NULL)
213 				continue;
214 			/* FALLTHROUGH */
215 		case '\0':
216 			/*
217 			 * end of a token -- make sure there's enough words
218 			 * space and save off a pointer.
219 			 */
220 			if (word_start == NULL)
221 				goto done;
222 
223 			*word_end++ = '\0';
224 			if (words_len == words_cap) {
225 				size_t new_size;
226 				words_cap *= 2;		/* ramp up fast */
227 				new_size = (words_cap + 1) * sizeof(char *);
228 				words = bmake_realloc(words, new_size);
229 			}
230 			words[words_len++] = word_start;
231 			word_start = NULL;
232 			if (ch == '\n' || ch == '\0') {
233 				if (expand && inquote) {
234 					free(words);
235 					free(words_buf);
236 					*out_words_buf = NULL;
237 					return NULL;
238 				}
239 				goto done;
240 			}
241 			continue;
242 		case '\\':
243 			if (!expand) {
244 				if (word_start == NULL)
245 					word_start = word_end;
246 				*word_end++ = '\\';
247 				/* catch '\' at end of line */
248 				if (str_p[1] == '\0')
249 					continue;
250 				ch = *++str_p;
251 				break;
252 			}
253 
254 			switch (ch = *++str_p) {
255 			case '\0':
256 			case '\n':
257 				/* hmmm; fix it up as best we can */
258 				ch = '\\';
259 				--str_p;
260 				break;
261 			case 'b':
262 				ch = '\b';
263 				break;
264 			case 'f':
265 				ch = '\f';
266 				break;
267 			case 'n':
268 				ch = '\n';
269 				break;
270 			case 'r':
271 				ch = '\r';
272 				break;
273 			case 't':
274 				ch = '\t';
275 				break;
276 			}
277 			break;
278 		}
279 		if (word_start == NULL)
280 			word_start = word_end;
281 		*word_end++ = ch;
282 	}
283 done:
284 	words[words_len] = NULL;
285 	*out_words_len = words_len;
286 	*out_words_buf = words_buf;
287 	return words;
288 }
289 
290 /*
291  * Str_FindSubstring -- See if a string contains a particular substring.
292  *
293  * Input:
294  *	string		String to search.
295  *	substring	Substring to find in string.
296  *
297  * Results: If string contains substring, the return value is the location of
298  * the first matching instance of substring in string.  If string doesn't
299  * contain substring, the return value is NULL.  Matching is done on an exact
300  * character-for-character basis with no wildcards or special characters.
301  *
302  * Side effects: None.
303  */
304 char *
305 Str_FindSubstring(const char *string, const char *substring)
306 {
307 	const char *a, *b;
308 
309 	/*
310 	 * First scan quickly through the two strings looking for a single-
311 	 * character match.  When it's found, then compare the rest of the
312 	 * substring.
313 	 */
314 
315 	for (b = substring; *string != 0; string++) {
316 		if (*string != *b)
317 			continue;
318 		a = string;
319 		for (;;) {
320 			if (*b == 0)
321 				return UNCONST(string);
322 			if (*a++ != *b++)
323 				break;
324 		}
325 		b = substring;
326 	}
327 	return NULL;
328 }
329 
330 /*
331  * Str_Match -- Test if a string matches a pattern like "*.[ch]".
332  *
333  * XXX this function does not detect or report malformed patterns.
334  *
335  * Results:
336  *	Non-zero is returned if string matches the pattern, 0 otherwise. The
337  *	matching operation permits the following special characters in the
338  *	pattern: *?\[] (as in fnmatch(3)).
339  *
340  * Side effects: None.
341  */
342 Boolean
343 Str_Match(const char *str, const char *pat)
344 {
345 	for (;;) {
346 		/*
347 		 * See if we're at the end of both the pattern and the
348 		 * string. If, we succeeded.  If we're at the end of the
349 		 * pattern but not at the end of the string, we failed.
350 		 */
351 		if (*pat == 0)
352 			return *str == 0;
353 		if (*str == 0 && *pat != '*')
354 			return FALSE;
355 
356 		/*
357 		 * A '*' in the pattern matches any substring.  We handle this
358 		 * by calling ourselves for each suffix of the string.
359 		 */
360 		if (*pat == '*') {
361 			pat++;
362 			while (*pat == '*')
363 				pat++;
364 			if (*pat == 0)
365 				return TRUE;
366 			while (*str != 0) {
367 				if (Str_Match(str, pat))
368 					return TRUE;
369 				str++;
370 			}
371 			return FALSE;
372 		}
373 
374 		/* A '?' in the pattern matches any single character. */
375 		if (*pat == '?')
376 			goto thisCharOK;
377 
378 		/*
379 		 * A '[' in the pattern matches a character from a list.
380 		 * The '[' is followed by the list of acceptable characters,
381 		 * or by ranges (two characters separated by '-'). In these
382 		 * character lists, the backslash is an ordinary character.
383 		 */
384 		if (*pat == '[') {
385 			Boolean neg = pat[1] == '^';
386 			pat += 1 + neg;
387 
388 			for (;;) {
389 				if (*pat == ']' || *pat == 0) {
390 					if (neg)
391 						break;
392 					return FALSE;
393 				}
394 				if (*pat == *str)
395 					break;
396 				if (pat[1] == '-') {
397 					if (pat[2] == 0)
398 						return neg;
399 					if (*pat <= *str && pat[2] >= *str)
400 						break;
401 					if (*pat >= *str && pat[2] <= *str)
402 						break;
403 					pat += 2;
404 				}
405 				pat++;
406 			}
407 			if (neg && *pat != ']' && *pat != 0)
408 				return FALSE;
409 			while (*pat != ']' && *pat != 0)
410 				pat++;
411 			if (*pat == 0)
412 				pat--;
413 			goto thisCharOK;
414 		}
415 
416 		/*
417 		 * A backslash in the pattern matches the character following
418 		 * it exactly.
419 		 */
420 		if (*pat == '\\') {
421 			pat++;
422 			if (*pat == 0)
423 				return FALSE;
424 		}
425 
426 		if (*pat != *str)
427 			return FALSE;
428 
429 	thisCharOK:
430 		pat++;
431 		str++;
432 	}
433 }
434