1 /*
2 ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $
3 ** Standard library for string operations and pattern-matching
4 ** See Copyright Notice in lua.h
5 */
6 
7 #include <ctype.h>
8 #include <stddef.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 
13 #define lstrlib_c
14 #define LUA_LIB
15 
16 #include "lua.h"
17 
18 #include "lauxlib.h"
19 #include "lualib.h"
20 
21 /*
22 ** maximum number of captures that a pattern can do during
23 ** pattern-matching. This limit is arbitrary.
24 */
25 #if !defined(LUA_MAXCAPTURES)
26 #define LUA_MAXCAPTURES 32
27 #endif
28 
29 /* macro to `unsign' a character */
30 #define uchar(c) ((unsigned char)(c))
31 
str_len(lua_State * L)32 static int str_len(lua_State *L)
33 {
34 	size_t l;
35 	luaL_checklstring(L, 1, &l);
36 	lua_pushinteger(L, (lua_Integer)l);
37 	return 1;
38 }
39 
40 /* translate a relative string position: negative means back from end */
posrelat(ptrdiff_t pos,size_t len)41 static size_t posrelat(ptrdiff_t pos, size_t len)
42 {
43 	if (pos >= 0)
44 		return (size_t)pos;
45 	else if (0u - (size_t)pos > len)
46 		return 0;
47 	else
48 		return len - ((size_t)-pos) + 1;
49 }
50 
str_sub(lua_State * L)51 static int str_sub(lua_State *L)
52 {
53 	size_t l;
54 	const char *s = luaL_checklstring(L, 1, &l);
55 	size_t start = posrelat(luaL_checkinteger(L, 2), l);
56 	size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
57 	if (start < 1) start = 1;
58 	if (end > l) end = l;
59 	if (start <= end)
60 		lua_pushlstring(L, s + start - 1, end - start + 1);
61 	else
62 		lua_pushliteral(L, "");
63 	return 1;
64 }
65 
str_reverse(lua_State * L)66 static int str_reverse(lua_State *L)
67 {
68 	size_t l, i;
69 	luaL_Buffer b;
70 	const char *s = luaL_checklstring(L, 1, &l);
71 	char *p = luaL_buffinitsize(L, &b, l);
72 	for (i = 0; i < l; i++)
73 		p[i] = s[l - i - 1];
74 	luaL_pushresultsize(&b, l);
75 	return 1;
76 }
77 
str_lower(lua_State * L)78 static int str_lower(lua_State *L)
79 {
80 	size_t l;
81 	size_t i;
82 	luaL_Buffer b;
83 	const char *s = luaL_checklstring(L, 1, &l);
84 	char *p = luaL_buffinitsize(L, &b, l);
85 	for (i = 0; i < l; i++)
86 		p[i] = tolower(uchar(s[i]));
87 	luaL_pushresultsize(&b, l);
88 	return 1;
89 }
90 
str_upper(lua_State * L)91 static int str_upper(lua_State *L)
92 {
93 	size_t l;
94 	size_t i;
95 	luaL_Buffer b;
96 	const char *s = luaL_checklstring(L, 1, &l);
97 	char *p = luaL_buffinitsize(L, &b, l);
98 	for (i = 0; i < l; i++)
99 		p[i] = toupper(uchar(s[i]));
100 	luaL_pushresultsize(&b, l);
101 	return 1;
102 }
103 
104 /* reasonable limit to avoid arithmetic overflow */
105 #define MAXSIZE ((~(size_t)0) >> 1)
106 
str_rep(lua_State * L)107 static int str_rep(lua_State *L)
108 {
109 	size_t l, lsep;
110 	const char *s = luaL_checklstring(L, 1, &l);
111 	int n = luaL_checkint(L, 2);
112 	const char *sep = luaL_optlstring(L, 3, "", &lsep);
113 	if (n <= 0)
114 		lua_pushliteral(L, "");
115 	else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
116 		return luaL_error(L, "resulting string too large");
117 	else
118 	{
119 		size_t totallen = n * l + (n - 1) * lsep;
120 		luaL_Buffer b;
121 		char *p = luaL_buffinitsize(L, &b, totallen);
122 		while (n-- > 1)
123 		{ /* first n-1 copies (followed by separator) */
124 			memcpy(p, s, l * sizeof(char));
125 			p += l;
126 			if (lsep > 0)
127 			{ /* avoid empty 'memcpy' (may be expensive) */
128 				memcpy(p, sep, lsep * sizeof(char));
129 				p += lsep;
130 			}
131 		}
132 		memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
133 		luaL_pushresultsize(&b, totallen);
134 	}
135 	return 1;
136 }
137 
str_byte(lua_State * L)138 static int str_byte(lua_State *L)
139 {
140 	size_t l;
141 	const char *s = luaL_checklstring(L, 1, &l);
142 	size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
143 	size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
144 	int n, i;
145 	if (posi < 1) posi = 1;
146 	if (pose > l) pose = l;
147 	if (posi > pose) return 0; /* empty interval; return no values */
148 	n = (int)(pose - posi + 1);
149 	if (posi + n <= pose) /* (size_t -> int) overflow? */
150 		return luaL_error(L, "string slice too long");
151 	luaL_checkstack(L, n, "string slice too long");
152 	for (i = 0; i < n; i++)
153 		lua_pushinteger(L, uchar(s[posi + i - 1]));
154 	return n;
155 }
156 
str_char(lua_State * L)157 static int str_char(lua_State *L)
158 {
159 	int n = lua_gettop(L); /* number of arguments */
160 	int i;
161 	luaL_Buffer b;
162 	char *p = luaL_buffinitsize(L, &b, n);
163 	for (i = 1; i <= n; i++)
164 	{
165 		int c = luaL_checkint(L, i);
166 		luaL_argcheck(L, uchar(c) == c, i, "value out of range");
167 		p[i - 1] = uchar(c);
168 	}
169 	luaL_pushresultsize(&b, n);
170 	return 1;
171 }
172 
writer(lua_State * L,const void * b,size_t size,void * B)173 static int writer(lua_State *L, const void *b, size_t size, void *B)
174 {
175 	(void)L;
176 	luaL_addlstring((luaL_Buffer *)B, (const char *)b, size);
177 	return 0;
178 }
179 
str_dump(lua_State * L)180 static int str_dump(lua_State *L)
181 {
182 	luaL_Buffer b;
183 	luaL_checktype(L, 1, LUA_TFUNCTION);
184 	lua_settop(L, 1);
185 	luaL_buffinit(L, &b);
186 	if (lua_dump(L, writer, &b) != 0)
187 		return luaL_error(L, "unable to dump given function");
188 	luaL_pushresult(&b);
189 	return 1;
190 }
191 
192 /*
193 ** {======================================================
194 ** PATTERN MATCHING
195 ** =======================================================
196 */
197 
198 #define CAP_UNFINISHED (-1)
199 #define CAP_POSITION (-2)
200 
201 typedef struct MatchState
202 {
203 	int matchdepth;       /* control for recursive depth (to avoid C stack overflow) */
204 	const char *src_init; /* init of source string */
205 	const char *src_end;  /* end ('\0') of source string */
206 	const char *p_end;    /* end ('\0') of pattern */
207 	lua_State *L;
208 	int level; /* total number of captures (finished or unfinished) */
209 	struct
210 	{
211 		const char *init;
212 		ptrdiff_t len;
213 	} capture[LUA_MAXCAPTURES];
214 } MatchState;
215 
216 /* recursive function */
217 static const char *match(MatchState *ms, const char *s, const char *p);
218 
219 /* maximum recursion depth for 'match' */
220 #if !defined(MAXCCALLS)
221 #define MAXCCALLS 200
222 #endif
223 
224 #define L_ESC '%'
225 #define SPECIALS "^$*+?.([%-"
226 
check_capture(MatchState * ms,int l)227 static int check_capture(MatchState *ms, int l)
228 {
229 	l -= '1';
230 	if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
231 		return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
232 	return l;
233 }
234 
capture_to_close(MatchState * ms)235 static int capture_to_close(MatchState *ms)
236 {
237 	int level = ms->level;
238 	for (level--; level >= 0; level--)
239 		if (ms->capture[level].len == CAP_UNFINISHED) return level;
240 	return luaL_error(ms->L, "invalid pattern capture");
241 }
242 
classend(MatchState * ms,const char * p)243 static const char *classend(MatchState *ms, const char *p)
244 {
245 	switch (*p++)
246 	{
247 		case L_ESC:
248 		{
249 			if (p == ms->p_end)
250 				luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
251 			return p + 1;
252 		}
253 		case '[':
254 		{
255 			if (*p == '^') p++;
256 			do
257 			{ /* look for a `]' */
258 				if (p == ms->p_end)
259 					luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
260 				if (*(p++) == L_ESC && p < ms->p_end)
261 					p++; /* skip escapes (e.g. `%]') */
262 			} while (*p != ']');
263 			return p + 1;
264 		}
265 		default:
266 		{
267 			return p;
268 		}
269 	}
270 }
271 
match_class(int c,int cl)272 static int match_class(int c, int cl)
273 {
274 	int res;
275 	switch (tolower(cl))
276 	{
277 		case 'a':
278 			res = isalpha(c);
279 			break;
280 		case 'c':
281 			res = iscntrl(c);
282 			break;
283 		case 'd':
284 			res = isdigit(c);
285 			break;
286 		case 'g':
287 			res = isgraph(c);
288 			break;
289 		case 'l':
290 			res = islower(c);
291 			break;
292 		case 'p':
293 			res = ispunct(c);
294 			break;
295 		case 's':
296 			res = isspace(c);
297 			break;
298 		case 'u':
299 			res = isupper(c);
300 			break;
301 		case 'w':
302 			res = isalnum(c);
303 			break;
304 		case 'x':
305 			res = isxdigit(c);
306 			break;
307 		case 'z':
308 			res = (c == 0);
309 			break; /* deprecated option */
310 		default:
311 			return (cl == c);
312 	}
313 	return (islower(cl) ? res : !res);
314 }
315 
matchbracketclass(int c,const char * p,const char * ec)316 static int matchbracketclass(int c, const char *p, const char *ec)
317 {
318 	int sig = 1;
319 	if (*(p + 1) == '^')
320 	{
321 		sig = 0;
322 		p++; /* skip the `^' */
323 	}
324 	while (++p < ec)
325 	{
326 		if (*p == L_ESC)
327 		{
328 			p++;
329 			if (match_class(c, uchar(*p)))
330 				return sig;
331 		}
332 		else if ((*(p + 1) == '-') && (p + 2 < ec))
333 		{
334 			p += 2;
335 			if (uchar(*(p - 2)) <= c && c <= uchar(*p))
336 				return sig;
337 		}
338 		else if (uchar(*p) == c)
339 			return sig;
340 	}
341 	return !sig;
342 }
343 
singlematch(MatchState * ms,const char * s,const char * p,const char * ep)344 static int singlematch(MatchState *ms, const char *s, const char *p,
345 					   const char *ep)
346 {
347 	if (s >= ms->src_end)
348 		return 0;
349 	else
350 	{
351 		int c = uchar(*s);
352 		switch (*p)
353 		{
354 			case '.':
355 				return 1; /* matches any char */
356 			case L_ESC:
357 				return match_class(c, uchar(*(p + 1)));
358 			case '[':
359 				return matchbracketclass(c, p, ep - 1);
360 			default:
361 				return (uchar(*p) == c);
362 		}
363 	}
364 }
365 
matchbalance(MatchState * ms,const char * s,const char * p)366 static const char *matchbalance(MatchState *ms, const char *s,
367 								const char *p)
368 {
369 	if (p >= ms->p_end - 1)
370 		luaL_error(ms->L,
371 				   "malformed pattern "
372 				   "(missing arguments to " LUA_QL("%%b") ")");
373 	if (*s != *p)
374 		return NULL;
375 	else
376 	{
377 		int b = *p;
378 		int e = *(p + 1);
379 		int cont = 1;
380 		while (++s < ms->src_end)
381 		{
382 			if (*s == e)
383 			{
384 				if (--cont == 0) return s + 1;
385 			}
386 			else if (*s == b)
387 				cont++;
388 		}
389 	}
390 	return NULL; /* string ends out of balance */
391 }
392 
max_expand(MatchState * ms,const char * s,const char * p,const char * ep)393 static const char *max_expand(MatchState *ms, const char *s,
394 							  const char *p, const char *ep)
395 {
396 	ptrdiff_t i = 0; /* counts maximum expand for item */
397 	while (singlematch(ms, s + i, p, ep))
398 		i++;
399 	/* keeps trying to match with the maximum repetitions */
400 	while (i >= 0)
401 	{
402 		const char *res = match(ms, (s + i), ep + 1);
403 		if (res) return res;
404 		i--; /* else didn't match; reduce 1 repetition to try again */
405 	}
406 	return NULL;
407 }
408 
min_expand(MatchState * ms,const char * s,const char * p,const char * ep)409 static const char *min_expand(MatchState *ms, const char *s,
410 							  const char *p, const char *ep)
411 {
412 	for (;;)
413 	{
414 		const char *res = match(ms, s, ep + 1);
415 		if (res != NULL)
416 			return res;
417 		else if (singlematch(ms, s, p, ep))
418 			s++; /* try with one more repetition */
419 		else
420 			return NULL;
421 	}
422 }
423 
start_capture(MatchState * ms,const char * s,const char * p,int what)424 static const char *start_capture(MatchState *ms, const char *s,
425 								 const char *p, int what)
426 {
427 	const char *res;
428 	int level = ms->level;
429 	if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
430 	ms->capture[level].init = s;
431 	ms->capture[level].len = what;
432 	ms->level = level + 1;
433 	if ((res = match(ms, s, p)) == NULL) /* match failed? */
434 		ms->level--;                     /* undo capture */
435 	return res;
436 }
437 
end_capture(MatchState * ms,const char * s,const char * p)438 static const char *end_capture(MatchState *ms, const char *s,
439 							   const char *p)
440 {
441 	int l = capture_to_close(ms);
442 	const char *res;
443 	ms->capture[l].len = s - ms->capture[l].init; /* close capture */
444 	if ((res = match(ms, s, p)) == NULL)          /* match failed? */
445 		ms->capture[l].len = CAP_UNFINISHED;      /* undo capture */
446 	return res;
447 }
448 
match_capture(MatchState * ms,const char * s,int l)449 static const char *match_capture(MatchState *ms, const char *s, int l)
450 {
451 	size_t len;
452 	l = check_capture(ms, l);
453 	len = ms->capture[l].len;
454 	if ((size_t)(ms->src_end - s) >= len &&
455 		memcmp(ms->capture[l].init, s, len) == 0)
456 		return s + len;
457 	else
458 		return NULL;
459 }
460 
match(MatchState * ms,const char * s,const char * p)461 static const char *match(MatchState *ms, const char *s, const char *p)
462 {
463 	if (ms->matchdepth-- == 0)
464 		luaL_error(ms->L, "pattern too complex");
465 init: /* using goto's to optimize tail recursion */
466 	if (p != ms->p_end)
467 	{ /* end of pattern? */
468 		switch (*p)
469 		{
470 			case '(':
471 			{                        /* start capture */
472 				if (*(p + 1) == ')') /* position capture? */
473 					s = start_capture(ms, s, p + 2, CAP_POSITION);
474 				else
475 					s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
476 				break;
477 			}
478 			case ')':
479 			{ /* end capture */
480 				s = end_capture(ms, s, p + 1);
481 				break;
482 			}
483 			case '$':
484 			{
485 				if ((p + 1) != ms->p_end)          /* is the `$' the last char in pattern? */
486 					goto dflt;                     /* no; go to default */
487 				s = (s == ms->src_end) ? s : NULL; /* check end of string */
488 				break;
489 			}
490 			case L_ESC:
491 			{ /* escaped sequences not in the format class[*+?-]? */
492 				switch (*(p + 1))
493 				{
494 					case 'b':
495 					{ /* balanced string? */
496 						s = matchbalance(ms, s, p + 2);
497 						if (s != NULL)
498 						{
499 							p += 4;
500 							goto init; /* return match(ms, s, p + 4); */
501 						}              /* else fail (s == NULL) */
502 						break;
503 					}
504 					case 'f':
505 					{ /* frontier? */
506 						const char *ep;
507 						char previous;
508 						p += 2;
509 						if (*p != '[')
510 							luaL_error(ms->L, "missing " LUA_QL("[") " after " LUA_QL("%%f") " in pattern");
511 						ep = classend(ms, p); /* points to what is next */
512 						previous = (s == ms->src_init) ? '\0' : *(s - 1);
513 						if (!matchbracketclass(uchar(previous), p, ep - 1) &&
514 							matchbracketclass(uchar(*s), p, ep - 1))
515 						{
516 							p = ep;
517 							goto init; /* return match(ms, s, ep); */
518 						}
519 						s = NULL; /* match failed */
520 						break;
521 					}
522 					case '0':
523 					case '1':
524 					case '2':
525 					case '3':
526 					case '4':
527 					case '5':
528 					case '6':
529 					case '7':
530 					case '8':
531 					case '9':
532 					{ /* capture results (%0-%9)? */
533 						s = match_capture(ms, s, uchar(*(p + 1)));
534 						if (s != NULL)
535 						{
536 							p += 2;
537 							goto init; /* return match(ms, s, p + 2) */
538 						}
539 						break;
540 					}
541 					default:
542 						goto dflt;
543 				}
544 				break;
545 			}
546 			default:
547 			dflt:
548 			{                                     /* pattern class plus optional suffix */
549 				const char *ep = classend(ms, p); /* points to optional suffix */
550 				/* does not match at least once? */
551 				if (!singlematch(ms, s, p, ep))
552 				{
553 					if (*ep == '*' || *ep == '?' || *ep == '-')
554 					{ /* accept empty? */
555 						p = ep + 1;
556 						goto init; /* return match(ms, s, ep + 1); */
557 					}
558 					else          /* '+' or no suffix */
559 						s = NULL; /* fail */
560 				}
561 				else
562 				{ /* matched once */
563 					switch (*ep)
564 					{ /* handle optional suffix */
565 						case '?':
566 						{ /* optional */
567 							const char *res;
568 							if ((res = match(ms, s + 1, ep + 1)) != NULL)
569 								s = res;
570 							else
571 							{
572 								p = ep + 1;
573 								goto init; /* else return match(ms, s, ep + 1); */
574 							}
575 							break;
576 						}
577 						case '+': /* 1 or more repetitions */
578 							s++;  /* 1 match already done */
579 								  /* go through */
580 						case '*': /* 0 or more repetitions */
581 							s = max_expand(ms, s, p, ep);
582 							break;
583 						case '-': /* 0 or more repetitions (minimum) */
584 							s = min_expand(ms, s, p, ep);
585 							break;
586 						default: /* no suffix */
587 							s++;
588 							p = ep;
589 							goto init; /* return match(ms, s + 1, ep); */
590 					}
591 				}
592 				break;
593 			}
594 		}
595 	}
596 	ms->matchdepth++;
597 	return s;
598 }
599 
lmemfind(const char * s1,size_t l1,const char * s2,size_t l2)600 static const char *lmemfind(const char *s1, size_t l1,
601 							const char *s2, size_t l2)
602 {
603 	if (l2 == 0)
604 		return s1; /* empty strings are everywhere */
605 	else if (l2 > l1)
606 		return NULL; /* avoids a negative `l1' */
607 	else
608 	{
609 		const char *init; /* to search for a `*s2' inside `s1' */
610 		l2--;             /* 1st char will be checked by `memchr' */
611 		l1 = l1 - l2;     /* `s2' cannot be found after that */
612 		while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL)
613 		{
614 			init++; /* 1st char is already checked */
615 			if (memcmp(init, s2 + 1, l2) == 0)
616 				return init - 1;
617 			else
618 			{ /* correct `l1' and `s1' to try again */
619 				l1 -= init - s1;
620 				s1 = init;
621 			}
622 		}
623 		return NULL; /* not found */
624 	}
625 }
626 
push_onecapture(MatchState * ms,int i,const char * s,const char * e)627 static void push_onecapture(MatchState *ms, int i, const char *s,
628 							const char *e)
629 {
630 	if (i >= ms->level)
631 	{
632 		if (i == 0)                           /* ms->level == 0, too */
633 			lua_pushlstring(ms->L, s, e - s); /* add whole match */
634 		else
635 			luaL_error(ms->L, "invalid capture index");
636 	}
637 	else
638 	{
639 		ptrdiff_t l = ms->capture[i].len;
640 		if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
641 		if (l == CAP_POSITION)
642 			lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
643 		else
644 			lua_pushlstring(ms->L, ms->capture[i].init, l);
645 	}
646 }
647 
push_captures(MatchState * ms,const char * s,const char * e)648 static int push_captures(MatchState *ms, const char *s, const char *e)
649 {
650 	int i;
651 	int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
652 	luaL_checkstack(ms->L, nlevels, "too many captures");
653 	for (i = 0; i < nlevels; i++)
654 		push_onecapture(ms, i, s, e);
655 	return nlevels; /* number of strings pushed */
656 }
657 
658 /* check whether pattern has no special characters */
nospecials(const char * p,size_t l)659 static int nospecials(const char *p, size_t l)
660 {
661 	size_t upto = 0;
662 	do
663 	{
664 		if (strpbrk(p + upto, SPECIALS))
665 			return 0;                 /* pattern has a special character */
666 		upto += strlen(p + upto) + 1; /* may have more after \0 */
667 	} while (upto <= l);
668 	return 1; /* no special chars found */
669 }
670 
str_find_aux(lua_State * L,int find)671 static int str_find_aux(lua_State *L, int find)
672 {
673 	size_t ls, lp;
674 	const char *s = luaL_checklstring(L, 1, &ls);
675 	const char *p = luaL_checklstring(L, 2, &lp);
676 	size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
677 	if (init < 1)
678 		init = 1;
679 	else if (init > ls + 1)
680 	{                   /* start after string's end? */
681 		lua_pushnil(L); /* cannot find anything */
682 		return 1;
683 	}
684 	/* explicit request or no special characters? */
685 	if (find && (lua_toboolean(L, 4) || nospecials(p, lp)))
686 	{
687 		/* do a plain search */
688 		const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
689 		if (s2)
690 		{
691 			lua_pushinteger(L, s2 - s + 1);
692 			lua_pushinteger(L, s2 - s + lp);
693 			return 2;
694 		}
695 	}
696 	else
697 	{
698 		MatchState ms;
699 		const char *s1 = s + init - 1;
700 		int anchor = (*p == '^');
701 		if (anchor)
702 		{
703 			p++;
704 			lp--; /* skip anchor character */
705 		}
706 		ms.L = L;
707 		ms.matchdepth = MAXCCALLS;
708 		ms.src_init = s;
709 		ms.src_end = s + ls;
710 		ms.p_end = p + lp;
711 		do
712 		{
713 			const char *res;
714 			ms.level = 0;
715 			lua_assert(ms.matchdepth == MAXCCALLS);
716 			if ((res = match(&ms, s1, p)) != NULL)
717 			{
718 				if (find)
719 				{
720 					lua_pushinteger(L, s1 - s + 1); /* start */
721 					lua_pushinteger(L, res - s);    /* end */
722 					return push_captures(&ms, NULL, 0) + 2;
723 				}
724 				else
725 					return push_captures(&ms, s1, res);
726 			}
727 		} while (s1++ < ms.src_end && !anchor);
728 	}
729 	lua_pushnil(L); /* not found */
730 	return 1;
731 }
732 
str_find(lua_State * L)733 static int str_find(lua_State *L)
734 {
735 	return str_find_aux(L, 1);
736 }
737 
str_match(lua_State * L)738 static int str_match(lua_State *L)
739 {
740 	return str_find_aux(L, 0);
741 }
742 
gmatch_aux(lua_State * L)743 static int gmatch_aux(lua_State *L)
744 {
745 	MatchState ms;
746 	size_t ls, lp;
747 	const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
748 	const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
749 	const char *src;
750 	ms.L = L;
751 	ms.matchdepth = MAXCCALLS;
752 	ms.src_init = s;
753 	ms.src_end = s + ls;
754 	ms.p_end = p + lp;
755 	for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
756 		 src <= ms.src_end;
757 		 src++)
758 	{
759 		const char *e;
760 		ms.level = 0;
761 		lua_assert(ms.matchdepth == MAXCCALLS);
762 		if ((e = match(&ms, src, p)) != NULL)
763 		{
764 			lua_Integer newstart = e - s;
765 			if (e == src) newstart++; /* empty match? go at least one position */
766 			lua_pushinteger(L, newstart);
767 			lua_replace(L, lua_upvalueindex(3));
768 			return push_captures(&ms, src, e);
769 		}
770 	}
771 	return 0; /* not found */
772 }
773 
gmatch(lua_State * L)774 static int gmatch(lua_State *L)
775 {
776 	luaL_checkstring(L, 1);
777 	luaL_checkstring(L, 2);
778 	lua_settop(L, 2);
779 	lua_pushinteger(L, 0);
780 	lua_pushcclosure(L, gmatch_aux, 3);
781 	return 1;
782 }
783 
add_s(MatchState * ms,luaL_Buffer * b,const char * s,const char * e)784 static void add_s(MatchState *ms, luaL_Buffer *b, const char *s,
785 				  const char *e)
786 {
787 	size_t l, i;
788 	const char *news = lua_tolstring(ms->L, 3, &l);
789 	for (i = 0; i < l; i++)
790 	{
791 		if (news[i] != L_ESC)
792 			luaL_addchar(b, news[i]);
793 		else
794 		{
795 			i++; /* skip ESC */
796 			if (!isdigit(uchar(news[i])))
797 			{
798 				if (news[i] != L_ESC)
799 					luaL_error(ms->L, "invalid use of " LUA_QL("%c") " in replacement string", L_ESC);
800 				luaL_addchar(b, news[i]);
801 			}
802 			else if (news[i] == '0')
803 				luaL_addlstring(b, s, e - s);
804 			else
805 			{
806 				push_onecapture(ms, news[i] - '1', s, e);
807 				luaL_addvalue(b); /* add capture to accumulated result */
808 			}
809 		}
810 	}
811 }
812 
add_value(MatchState * ms,luaL_Buffer * b,const char * s,const char * e,int tr)813 static void add_value(MatchState *ms, luaL_Buffer *b, const char *s,
814 					  const char *e, int tr)
815 {
816 	lua_State *L = ms->L;
817 	switch (tr)
818 	{
819 		case LUA_TFUNCTION:
820 		{
821 			int n;
822 			lua_pushvalue(L, 3);
823 			n = push_captures(ms, s, e);
824 			lua_call(L, n, 1);
825 			break;
826 		}
827 		case LUA_TTABLE:
828 		{
829 			push_onecapture(ms, 0, s, e);
830 			lua_gettable(L, 3);
831 			break;
832 		}
833 		default:
834 		{ /* LUA_TNUMBER or LUA_TSTRING */
835 			add_s(ms, b, s, e);
836 			return;
837 		}
838 	}
839 	if (!lua_toboolean(L, -1))
840 	{ /* nil or false? */
841 		lua_pop(L, 1);
842 		lua_pushlstring(L, s, e - s); /* keep original text */
843 	}
844 	else if (!lua_isstring(L, -1))
845 		luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
846 	luaL_addvalue(b); /* add result to accumulator */
847 }
848 
str_gsub(lua_State * L)849 static int str_gsub(lua_State *L)
850 {
851 	size_t srcl, lp;
852 	const char *src = luaL_checklstring(L, 1, &srcl);
853 	const char *p = luaL_checklstring(L, 2, &lp);
854 	int tr = lua_type(L, 3);
855 	size_t max_s = luaL_optinteger(L, 4, srcl + 1);
856 	int anchor = (*p == '^');
857 	size_t n = 0;
858 	MatchState ms;
859 	luaL_Buffer b;
860 	luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
861 				  "string/function/table expected");
862 	luaL_buffinit(L, &b);
863 	if (anchor)
864 	{
865 		p++;
866 		lp--; /* skip anchor character */
867 	}
868 	ms.L = L;
869 	ms.matchdepth = MAXCCALLS;
870 	ms.src_init = src;
871 	ms.src_end = src + srcl;
872 	ms.p_end = p + lp;
873 	while (n < max_s)
874 	{
875 		const char *e;
876 		ms.level = 0;
877 		lua_assert(ms.matchdepth == MAXCCALLS);
878 		e = match(&ms, src, p);
879 		if (e)
880 		{
881 			n++;
882 			add_value(&ms, &b, src, e, tr);
883 		}
884 		if (e && e > src) /* non empty match? */
885 			src = e;      /* skip it */
886 		else if (src < ms.src_end)
887 			luaL_addchar(&b, *src++);
888 		else
889 			break;
890 		if (anchor) break;
891 	}
892 	luaL_addlstring(&b, src, ms.src_end - src);
893 	luaL_pushresult(&b);
894 	lua_pushinteger(L, n); /* number of substitutions */
895 	return 2;
896 }
897 
898 /* }====================================================== */
899 
900 /*
901 ** {======================================================
902 ** STRING FORMAT
903 ** =======================================================
904 */
905 
906 /*
907 ** LUA_INTFRMLEN is the length modifier for integer conversions in
908 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
909 ** the previous length
910 */
911 #if !defined(LUA_INTFRMLEN) /* { */
912 #if defined(LUA_USE_LONGLONG)
913 
914 #define LUA_INTFRMLEN "ll"
915 #define LUA_INTFRM_T long long
916 
917 #else
918 
919 #define LUA_INTFRMLEN "l"
920 #define LUA_INTFRM_T long
921 
922 #endif
923 #endif /* } */
924 
925 /*
926 ** LUA_FLTFRMLEN is the length modifier for float conversions in
927 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
928 ** the previous length
929 */
930 #if !defined(LUA_FLTFRMLEN)
931 
932 #define LUA_FLTFRMLEN ""
933 #define LUA_FLTFRM_T double
934 
935 #endif
936 
937 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
938 #define MAX_ITEM 512
939 /* valid flags in a format specification */
940 #define FLAGS "-+ #0"
941 /*
942 ** maximum size of each format specification (such as '%-099.99d')
943 ** (+10 accounts for %99.99x plus margin of error)
944 */
945 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
946 
addquoted(lua_State * L,luaL_Buffer * b,int arg)947 static void addquoted(lua_State *L, luaL_Buffer *b, int arg)
948 {
949 	size_t l;
950 	const char *s = luaL_checklstring(L, arg, &l);
951 	luaL_addchar(b, '"');
952 	while (l--)
953 	{
954 		if (*s == '"' || *s == '\\' || *s == '\n')
955 		{
956 			luaL_addchar(b, '\\');
957 			luaL_addchar(b, *s);
958 		}
959 		else if (*s == '\0' || iscntrl(uchar(*s)))
960 		{
961 			char buff[10];
962 			if (!isdigit(uchar(*(s + 1))))
963 				sprintf(buff, "\\%d", (int)uchar(*s));
964 			else
965 				sprintf(buff, "\\%03d", (int)uchar(*s));
966 			luaL_addstring(b, buff);
967 		}
968 		else
969 			luaL_addchar(b, *s);
970 		s++;
971 	}
972 	luaL_addchar(b, '"');
973 }
974 
scanformat(lua_State * L,const char * strfrmt,char * form)975 static const char *scanformat(lua_State *L, const char *strfrmt, char *form)
976 {
977 	const char *p = strfrmt;
978 	while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
979 	if ((size_t)(p - strfrmt) >= sizeof(FLAGS) / sizeof(char))
980 		luaL_error(L, "invalid format (repeated flags)");
981 	if (isdigit(uchar(*p))) p++; /* skip width */
982 	if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
983 	if (*p == '.')
984 	{
985 		p++;
986 		if (isdigit(uchar(*p))) p++; /* skip precision */
987 		if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
988 	}
989 	if (isdigit(uchar(*p)))
990 		luaL_error(L, "invalid format (width or precision too long)");
991 	*(form++) = '%';
992 	memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
993 	form += p - strfrmt + 1;
994 	*form = '\0';
995 	return p;
996 }
997 
998 /*
999 ** add length modifier into formats
1000 */
addlenmod(char * form,const char * lenmod)1001 static void addlenmod(char *form, const char *lenmod)
1002 {
1003 	size_t l = strlen(form);
1004 	size_t lm = strlen(lenmod);
1005 	char spec = form[l - 1];
1006 	strcpy(form + l - 1, lenmod);
1007 	form[l + lm - 1] = spec;
1008 	form[l + lm] = '\0';
1009 }
1010 
str_format(lua_State * L)1011 static int str_format(lua_State *L)
1012 {
1013 	int top = lua_gettop(L);
1014 	int arg = 1;
1015 	size_t sfl;
1016 	const char *strfrmt = luaL_checklstring(L, arg, &sfl);
1017 	const char *strfrmt_end = strfrmt + sfl;
1018 	luaL_Buffer b;
1019 	luaL_buffinit(L, &b);
1020 	while (strfrmt < strfrmt_end)
1021 	{
1022 		if (*strfrmt != L_ESC)
1023 			luaL_addchar(&b, *strfrmt++);
1024 		else if (*++strfrmt == L_ESC)
1025 			luaL_addchar(&b, *strfrmt++); /* %% */
1026 		else
1027 		{                                                 /* format item */
1028 			char form[MAX_FORMAT];                        /* to store the format (`%...') */
1029 			char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
1030 			int nb = 0;                                   /* number of bytes in added item */
1031 			if (++arg > top)
1032 				luaL_argerror(L, arg, "no value");
1033 			strfrmt = scanformat(L, strfrmt, form);
1034 			switch (*strfrmt++)
1035 			{
1036 				case 'c':
1037 				{
1038 					nb = sprintf(buff, form, luaL_checkint(L, arg));
1039 					break;
1040 				}
1041 				case 'd':
1042 				case 'i':
1043 				{
1044 					lua_Number n = luaL_checknumber(L, arg);
1045 					LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
1046 					lua_Number diff = n - (lua_Number)ni;
1047 					luaL_argcheck(L, -1 < diff && diff < 1, arg,
1048 								  "not a number in proper range");
1049 					addlenmod(form, LUA_INTFRMLEN);
1050 					nb = sprintf(buff, form, ni);
1051 					break;
1052 				}
1053 				case 'o':
1054 				case 'u':
1055 				case 'x':
1056 				case 'X':
1057 				{
1058 					lua_Number n = luaL_checknumber(L, arg);
1059 					unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
1060 					lua_Number diff = n - (lua_Number)ni;
1061 					luaL_argcheck(L, -1 < diff && diff < 1, arg,
1062 								  "not a non-negative number in proper range");
1063 					addlenmod(form, LUA_INTFRMLEN);
1064 					nb = sprintf(buff, form, ni);
1065 					break;
1066 				}
1067 				case 'e':
1068 				case 'E':
1069 				case 'f':
1070 #if defined(LUA_USE_AFORMAT)
1071 				case 'a':
1072 				case 'A':
1073 #endif
1074 				case 'g':
1075 				case 'G':
1076 				{
1077 					addlenmod(form, LUA_FLTFRMLEN);
1078 					nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
1079 					break;
1080 				}
1081 				case 'q':
1082 				{
1083 					addquoted(L, &b, arg);
1084 					break;
1085 				}
1086 				case 's':
1087 				{
1088 					size_t l;
1089 					const char *s = luaL_tolstring(L, arg, &l);
1090 					if (!strchr(form, '.') && l >= 100)
1091 					{
1092 						/* no precision and string is too long to be formatted;
1093                keep original string */
1094 						luaL_addvalue(&b);
1095 						break;
1096 					}
1097 					else
1098 					{
1099 						nb = sprintf(buff, form, s);
1100 						lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
1101 						break;
1102 					}
1103 				}
1104 				default:
1105 				{ /* also treat cases `pnLlh' */
1106 					return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " LUA_QL("format"), *(strfrmt - 1));
1107 				}
1108 			}
1109 			luaL_addsize(&b, nb);
1110 		}
1111 	}
1112 	luaL_pushresult(&b);
1113 	return 1;
1114 }
1115 
1116 /* }====================================================== */
1117 
1118 static const luaL_Reg strlib[] = {
1119 	{"byte", str_byte},
1120 	{"char", str_char},
1121 	{"dump", str_dump},
1122 	{"find", str_find},
1123 	{"format", str_format},
1124 	{"gmatch", gmatch},
1125 	{"gsub", str_gsub},
1126 	{"len", str_len},
1127 	{"lower", str_lower},
1128 	{"match", str_match},
1129 	{"rep", str_rep},
1130 	{"reverse", str_reverse},
1131 	{"sub", str_sub},
1132 	{"upper", str_upper},
1133 	{NULL, NULL}};
1134 
createmetatable(lua_State * L)1135 static void createmetatable(lua_State *L)
1136 {
1137 	lua_createtable(L, 0, 1);       /* table to be metatable for strings */
1138 	lua_pushliteral(L, "");         /* dummy string */
1139 	lua_pushvalue(L, -2);           /* copy table */
1140 	lua_setmetatable(L, -2);        /* set table as metatable for strings */
1141 	lua_pop(L, 1);                  /* pop dummy string */
1142 	lua_pushvalue(L, -2);           /* get string library */
1143 	lua_setfield(L, -2, "__index"); /* metatable.__index = string */
1144 	lua_pop(L, 1);                  /* pop metatable */
1145 }
1146 
1147 /*
1148 ** Open string library
1149 */
luaopen_string(lua_State * L)1150 LUAMOD_API int luaopen_string(lua_State *L)
1151 {
1152 	luaL_newlib(L, strlib);
1153 	createmetatable(L);
1154 	return 1;
1155 }
1156