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