xref: /netbsd/usr.bin/make/str.c (revision c4a72b64)
1 /*	$NetBSD: str.c,v 1.18 2002/06/15 18:24:57 wiz Exp $	*/
2 
3 /*-
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1989 by Berkeley Softworks
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Adam de Boor.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the University of
23  *	California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40 
41 #ifdef MAKE_BOOTSTRAP
42 static char rcsid[] = "$NetBSD: str.c,v 1.18 2002/06/15 18:24:57 wiz Exp $";
43 #else
44 #include <sys/cdefs.h>
45 #ifndef lint
46 #if 0
47 static char     sccsid[] = "@(#)str.c	5.8 (Berkeley) 6/1/90";
48 #else
49 __RCSID("$NetBSD: str.c,v 1.18 2002/06/15 18:24:57 wiz Exp $");
50 #endif
51 #endif				/* not lint */
52 #endif
53 
54 #include "make.h"
55 
56 /*-
57  * str_concat --
58  *	concatenate the two strings, inserting a space or slash between them,
59  *	freeing them if requested.
60  *
61  * returns --
62  *	the resulting string in allocated space.
63  */
64 char *
65 str_concat(char *s1, char *s2, int flags)
66 {
67 	int len1, len2;
68 	char *result;
69 
70 	/* get the length of both strings */
71 	len1 = strlen(s1);
72 	len2 = strlen(s2);
73 
74 	/* allocate length plus separator plus EOS */
75 	result = emalloc((u_int)(len1 + len2 + 2));
76 
77 	/* copy first string into place */
78 	memcpy(result, s1, len1);
79 
80 	/* add separator character */
81 	if (flags & STR_ADDSPACE) {
82 		result[len1] = ' ';
83 		++len1;
84 	} else if (flags & STR_ADDSLASH) {
85 		result[len1] = '/';
86 		++len1;
87 	}
88 
89 	/* copy second string plus EOS into place */
90 	memcpy(result + len1, s2, len2 + 1);
91 
92 	/* free original strings */
93 	if (flags & STR_DOFREE) {
94 		(void)free(s1);
95 		(void)free(s2);
96 	}
97 	return(result);
98 }
99 
100 /*-
101  * brk_string --
102  *	Fracture a string into an array of words (as delineated by tabs or
103  *	spaces) taking quotation marks into account.  Leading tabs/spaces
104  *	are ignored.
105  *
106  * returns --
107  *	Pointer to the array of pointers to the words.  To make life easier,
108  *	the first word is always the value of the .MAKE variable.
109  */
110 char **
111 brk_string(char *str, int *store_argc, Boolean expand, char **buffer)
112 {
113 	int argc, ch;
114 	char inquote, *p, *start, *t;
115 	int len;
116 	int argmax = 50, curlen = 0;
117     	char **argv = (char **)emalloc((argmax + 1) * sizeof(char *));
118 
119 	/* skip leading space chars. */
120 	for (; *str == ' ' || *str == '\t'; ++str)
121 		continue;
122 
123 	/* allocate room for a copy of the string */
124 	if ((len = strlen(str) + 1) > curlen)
125 		*buffer = emalloc(curlen = len);
126 
127 	/*
128 	 * copy the string; at the same time, parse backslashes,
129 	 * quotes and build the argument list.
130 	 */
131 	argc = 0;
132 	inquote = '\0';
133 	for (p = str, start = t = *buffer;; ++p) {
134 		switch(ch = *p) {
135 		case '"':
136 		case '\'':
137 			if (inquote) {
138 				if (inquote == ch)
139 					inquote = '\0';
140 				else
141 					break;
142 			}
143 			else {
144 				inquote = (char) ch;
145 				/* Don't miss "" or '' */
146 				if (start == NULL && p[1] == inquote) {
147 					start = t + 1;
148 					break;
149 				}
150 			}
151 			if (!expand) {
152 				if (!start)
153 					start = t;
154 				*t++ = ch;
155 			}
156 			continue;
157 		case ' ':
158 		case '\t':
159 		case '\n':
160 			if (inquote)
161 				break;
162 			if (!start)
163 				continue;
164 			/* FALLTHROUGH */
165 		case '\0':
166 			/*
167 			 * end of a token -- make sure there's enough argv
168 			 * space and save off a pointer.
169 			 */
170 			if (!start)
171 			    goto done;
172 
173 			*t++ = '\0';
174 			if (argc == argmax) {
175 				argmax *= 2;		/* ramp up fast */
176 				argv = (char **)erealloc(argv,
177 				    (argmax + 1) * sizeof(char *));
178 			}
179 			argv[argc++] = start;
180 			start = (char *)NULL;
181 			if (ch == '\n' || ch == '\0')
182 				goto done;
183 			continue;
184 		case '\\':
185 			if (!expand) {
186 				if (!start)
187 					start = t;
188 				*t++ = '\\';
189 				ch = *++p;
190 				break;
191 			}
192 
193 			switch (ch = *++p) {
194 			case '\0':
195 			case '\n':
196 				/* hmmm; fix it up as best we can */
197 				ch = '\\';
198 				--p;
199 				break;
200 			case 'b':
201 				ch = '\b';
202 				break;
203 			case 'f':
204 				ch = '\f';
205 				break;
206 			case 'n':
207 				ch = '\n';
208 				break;
209 			case 'r':
210 				ch = '\r';
211 				break;
212 			case 't':
213 				ch = '\t';
214 				break;
215 			}
216 			break;
217 		}
218 		if (!start)
219 			start = t;
220 		*t++ = (char) ch;
221 	}
222 done:	argv[argc] = (char *)NULL;
223 	*store_argc = argc;
224 	return(argv);
225 }
226 
227 /*
228  * Str_FindSubstring -- See if a string contains a particular substring.
229  *
230  * Input:
231  *	string		String to search.
232  *	substring	Substring to find in string.
233  *
234  * Results: If string contains substring, the return value is the location of
235  * the first matching instance of substring in string.  If string doesn't
236  * contain substring, the return value is NULL.  Matching is done on an exact
237  * character-for-character basis with no wildcards or special characters.
238  *
239  * Side effects: None.
240  */
241 char *
242 Str_FindSubstring(char *string, char *substring)
243 {
244 	char *a, *b;
245 
246 	/*
247 	 * First scan quickly through the two strings looking for a single-
248 	 * character match.  When it's found, then compare the rest of the
249 	 * substring.
250 	 */
251 
252 	for (b = substring; *string != 0; string += 1) {
253 		if (*string != *b)
254 			continue;
255 		a = string;
256 		for (;;) {
257 			if (*b == 0)
258 				return(string);
259 			if (*a++ != *b++)
260 				break;
261 		}
262 		b = substring;
263 	}
264 	return((char *) NULL);
265 }
266 
267 /*
268  * Str_Match --
269  *
270  * See if a particular string matches a particular pattern.
271  *
272  * Results: Non-zero is returned if string matches pattern, 0 otherwise. The
273  * matching operation permits the following special characters in the
274  * pattern: *?\[] (see the man page for details on what these mean).
275  *
276  * Side effects: None.
277  */
278 int
279 Str_Match(char *string, char *pattern)
280 {
281 	char c2;
282 
283 	for (;;) {
284 		/*
285 		 * See if we're at the end of both the pattern and the
286 		 * string. If, we succeeded.  If we're at the end of the
287 		 * pattern but not at the end of the string, we failed.
288 		 */
289 		if (*pattern == 0)
290 			return(!*string);
291 		if (*string == 0 && *pattern != '*')
292 			return(0);
293 		/*
294 		 * Check for a "*" as the next pattern character.  It matches
295 		 * any substring.  We handle this by calling ourselves
296 		 * recursively for each postfix of string, until either we
297 		 * match or we reach the end of the string.
298 		 */
299 		if (*pattern == '*') {
300 			pattern += 1;
301 			if (*pattern == 0)
302 				return(1);
303 			while (*string != 0) {
304 				if (Str_Match(string, pattern))
305 					return(1);
306 				++string;
307 			}
308 			return(0);
309 		}
310 		/*
311 		 * Check for a "?" as the next pattern character.  It matches
312 		 * any single character.
313 		 */
314 		if (*pattern == '?')
315 			goto thisCharOK;
316 		/*
317 		 * Check for a "[" as the next pattern character.  It is
318 		 * followed by a list of characters that are acceptable, or
319 		 * by a range (two characters separated by "-").
320 		 */
321 		if (*pattern == '[') {
322 			++pattern;
323 			for (;;) {
324 				if ((*pattern == ']') || (*pattern == 0))
325 					return(0);
326 				if (*pattern == *string)
327 					break;
328 				if (pattern[1] == '-') {
329 					c2 = pattern[2];
330 					if (c2 == 0)
331 						return(0);
332 					if ((*pattern <= *string) &&
333 					    (c2 >= *string))
334 						break;
335 					if ((*pattern >= *string) &&
336 					    (c2 <= *string))
337 						break;
338 					pattern += 2;
339 				}
340 				++pattern;
341 			}
342 			while ((*pattern != ']') && (*pattern != 0))
343 				++pattern;
344 			goto thisCharOK;
345 		}
346 		/*
347 		 * If the next pattern character is '/', just strip off the
348 		 * '/' so we do exact matching on the character that follows.
349 		 */
350 		if (*pattern == '\\') {
351 			++pattern;
352 			if (*pattern == 0)
353 				return(0);
354 		}
355 		/*
356 		 * There's no special character.  Just make sure that the
357 		 * next characters of each string match.
358 		 */
359 		if (*pattern != *string)
360 			return(0);
361 thisCharOK:	++pattern;
362 		++string;
363 	}
364 }
365 
366 
367 /*-
368  *-----------------------------------------------------------------------
369  * Str_SYSVMatch --
370  *	Check word against pattern for a match (% is wild),
371  *
372  * Input:
373  *	word		Word to examine
374  *	pattern		Pattern to examine against
375  *	len		Number of characters to substitute
376  *
377  * Results:
378  *	Returns the beginning position of a match or null. The number
379  *	of characters matched is returned in len.
380  *
381  * Side Effects:
382  *	None
383  *
384  *-----------------------------------------------------------------------
385  */
386 char *
387 Str_SYSVMatch(char *word, char *pattern, int *len)
388 {
389     char *p = pattern;
390     char *w = word;
391     char *m;
392 
393     if (*p == '\0') {
394 	/* Null pattern is the whole string */
395 	*len = strlen(w);
396 	return w;
397     }
398 
399     if ((m = strchr(p, '%')) != NULL) {
400 	/* check that the prefix matches */
401 	for (; p != m && *w && *w == *p; w++, p++)
402 	     continue;
403 
404 	if (p != m)
405 	    return NULL;	/* No match */
406 
407 	if (*++p == '\0') {
408 	    /* No more pattern, return the rest of the string */
409 	    *len = strlen(w);
410 	    return w;
411 	}
412     }
413 
414     m = w;
415 
416     /* Find a matching tail */
417     do
418 	if (strcmp(p, w) == 0) {
419 	    *len = w - m;
420 	    return m;
421 	}
422     while (*w++ != '\0');
423 
424     return NULL;
425 }
426 
427 
428 /*-
429  *-----------------------------------------------------------------------
430  * Str_SYSVSubst --
431  *	Substitute '%' on the pattern with len characters from src.
432  *	If the pattern does not contain a '%' prepend len characters
433  *	from src.
434  *
435  * Results:
436  *	None
437  *
438  * Side Effects:
439  *	Places result on buf
440  *
441  *-----------------------------------------------------------------------
442  */
443 void
444 Str_SYSVSubst(Buffer buf, char *pat, char *src, int len)
445 {
446     char *m;
447 
448     if ((m = strchr(pat, '%')) != NULL) {
449 	/* Copy the prefix */
450 	Buf_AddBytes(buf, m - pat, (Byte *) pat);
451 	/* skip the % */
452 	pat = m + 1;
453     }
454 
455     /* Copy the pattern */
456     Buf_AddBytes(buf, len, (Byte *) src);
457 
458     /* append the rest */
459     Buf_AddBytes(buf, strlen(pat), (Byte *) pat);
460 }
461