xref: /netbsd-src/external/mit/lua/dist/src/lstrlib.c (revision 212397c69a103ae7e5eafa8731ddfae671d2dee7)
1 /*	$NetBSD: lstrlib.c,v 1.11 2016/01/28 14:41:39 lneto Exp $	*/
2 
3 /*
4 ** Id: lstrlib.c,v 1.239 2015/11/25 16:28:17 roberto Exp
5 ** Standard library for string operations and pattern-matching
6 ** See Copyright Notice in lua.h
7 */
8 
9 #define lstrlib_c
10 #define LUA_LIB
11 
12 #include "lprefix.h"
13 
14 
15 #ifndef _KERNEL
16 #include <ctype.h>
17 #include <float.h>
18 #include <limits.h>
19 #include <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #endif /* _KERNEL */
24 
25 #include "lua.h"
26 
27 #include "lauxlib.h"
28 #include "lualib.h"
29 
30 
31 /*
32 ** maximum number of captures that a pattern can do during
33 ** pattern-matching. This limit is arbitrary.
34 */
35 #if !defined(LUA_MAXCAPTURES)
36 #define LUA_MAXCAPTURES		32
37 #endif
38 
39 
40 /* macro to 'unsign' a character */
41 #define uchar(c)	((unsigned char)(c))
42 
43 
44 /*
45 ** Some sizes are better limited to fit in 'int', but must also fit in
46 ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
47 */
48 #define MAX_SIZET	((size_t)(~(size_t)0))
49 
50 #define MAXSIZE  \
51 	(sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
52 
53 
54 
55 
56 static int str_len (lua_State *L) {
57   size_t l;
58   luaL_checklstring(L, 1, &l);
59   lua_pushinteger(L, (lua_Integer)l);
60   return 1;
61 }
62 
63 
64 /* translate a relative string position: negative means back from end */
65 static lua_Integer posrelat (lua_Integer pos, size_t len) {
66   if (pos >= 0) return pos;
67   else if (0u - (size_t)pos > len) return 0;
68   else return (lua_Integer)len + pos + 1;
69 }
70 
71 
72 static int str_sub (lua_State *L) {
73   size_t l;
74   const char *s = luaL_checklstring(L, 1, &l);
75   lua_Integer start = posrelat(luaL_checkinteger(L, 2), l);
76   lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l);
77   if (start < 1) start = 1;
78   if (end > (lua_Integer)l) end = l;
79   if (start <= end)
80     lua_pushlstring(L, s + start - 1, (size_t)(end - start) + 1);
81   else lua_pushliteral(L, "");
82   return 1;
83 }
84 
85 
86 static int str_reverse (lua_State *L) {
87   size_t l, i;
88   luaL_Buffer b;
89   const char *s = luaL_checklstring(L, 1, &l);
90   char *p = luaL_buffinitsize(L, &b, l);
91   for (i = 0; i < l; i++)
92     p[i] = s[l - i - 1];
93   luaL_pushresultsize(&b, l);
94   return 1;
95 }
96 
97 
98 static int str_lower (lua_State *L) {
99   size_t l;
100   size_t i;
101   luaL_Buffer b;
102   const char *s = luaL_checklstring(L, 1, &l);
103   char *p = luaL_buffinitsize(L, &b, l);
104   for (i=0; i<l; i++)
105     p[i] = tolower(uchar(s[i]));
106   luaL_pushresultsize(&b, l);
107   return 1;
108 }
109 
110 
111 static int str_upper (lua_State *L) {
112   size_t l;
113   size_t i;
114   luaL_Buffer b;
115   const char *s = luaL_checklstring(L, 1, &l);
116   char *p = luaL_buffinitsize(L, &b, l);
117   for (i=0; i<l; i++)
118     p[i] = toupper(uchar(s[i]));
119   luaL_pushresultsize(&b, l);
120   return 1;
121 }
122 
123 
124 static int str_rep (lua_State *L) {
125   size_t l, lsep;
126   const char *s = luaL_checklstring(L, 1, &l);
127   lua_Integer n = luaL_checkinteger(L, 2);
128   const char *sep = luaL_optlstring(L, 3, "", &lsep);
129   if (n <= 0) lua_pushliteral(L, "");
130   else if (l + lsep < l || l + lsep > MAXSIZE / n)  /* may overflow? */
131     return luaL_error(L, "resulting string too large");
132   else {
133     size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
134     luaL_Buffer b;
135     char *p = luaL_buffinitsize(L, &b, totallen);
136     while (n-- > 1) {  /* first n-1 copies (followed by separator) */
137       memcpy(p, s, l * sizeof(char)); p += l;
138       if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
139         memcpy(p, sep, lsep * sizeof(char));
140         p += lsep;
141       }
142     }
143     memcpy(p, s, l * sizeof(char));  /* last copy (not followed by separator) */
144     luaL_pushresultsize(&b, totallen);
145   }
146   return 1;
147 }
148 
149 
150 static int str_byte (lua_State *L) {
151   size_t l;
152   const char *s = luaL_checklstring(L, 1, &l);
153   lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l);
154   lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);
155   int n, i;
156   if (posi < 1) posi = 1;
157   if (pose > (lua_Integer)l) pose = l;
158   if (posi > pose) return 0;  /* empty interval; return no values */
159   if (pose - posi >= INT_MAX)  /* arithmetic overflow? */
160     return luaL_error(L, "string slice too long");
161   n = (int)(pose -  posi) + 1;
162   luaL_checkstack(L, n, "string slice too long");
163   for (i=0; i<n; i++)
164     lua_pushinteger(L, uchar(s[posi+i-1]));
165   return n;
166 }
167 
168 
169 static int str_char (lua_State *L) {
170   int n = lua_gettop(L);  /* number of arguments */
171   int i;
172   luaL_Buffer b;
173   char *p = luaL_buffinitsize(L, &b, n);
174   for (i=1; i<=n; i++) {
175     lua_Integer c = luaL_checkinteger(L, i);
176     luaL_argcheck(L, uchar(c) == c, i, "value out of range");
177     p[i - 1] = uchar(c);
178   }
179   luaL_pushresultsize(&b, n);
180   return 1;
181 }
182 
183 
184 static int writer (lua_State *L, const void *b, size_t size, void *B) {
185   (void)L;
186   luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
187   return 0;
188 }
189 
190 
191 static int str_dump (lua_State *L) {
192   luaL_Buffer b;
193   int strip = lua_toboolean(L, 2);
194   luaL_checktype(L, 1, LUA_TFUNCTION);
195   lua_settop(L, 1);
196   luaL_buffinit(L,&b);
197   if (lua_dump(L, writer, &b, strip) != 0)
198     return luaL_error(L, "unable to dump given function");
199   luaL_pushresult(&b);
200   return 1;
201 }
202 
203 
204 
205 /*
206 ** {======================================================
207 ** PATTERN MATCHING
208 ** =======================================================
209 */
210 
211 
212 #define CAP_UNFINISHED	(-1)
213 #define CAP_POSITION	(-2)
214 
215 
216 typedef struct MatchState {
217   const char *src_init;  /* init of source string */
218   const char *src_end;  /* end ('\0') of source string */
219   const char *p_end;  /* end ('\0') of pattern */
220   lua_State *L;
221   size_t nrep;  /* limit to avoid non-linear complexity */
222   int matchdepth;  /* control for recursive depth (to avoid C stack overflow) */
223   int level;  /* total number of captures (finished or unfinished) */
224   struct {
225     const char *init;
226     ptrdiff_t len;
227   } capture[LUA_MAXCAPTURES];
228 } MatchState;
229 
230 
231 /* recursive function */
232 static const char *match (MatchState *ms, const char *s, const char *p);
233 
234 
235 /* maximum recursion depth for 'match' */
236 #if !defined(MAXCCALLS)
237 #define MAXCCALLS	200
238 #endif
239 
240 
241 /*
242 ** parameters to control the maximum number of operators handled in
243 ** a match (to avoid non-linear complexity). The maximum will be:
244 ** (subject length) * A_REPS + B_REPS
245 */
246 #if !defined(A_REPS)
247 #define A_REPS		4
248 #define B_REPS		100000
249 #endif
250 
251 
252 #define L_ESC		'%'
253 #define SPECIALS	"^$*+?.([%-"
254 
255 
256 static int check_capture (MatchState *ms, int l) {
257   l -= '1';
258   if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
259     return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
260   return l;
261 }
262 
263 
264 static int capture_to_close (MatchState *ms) {
265   int level = ms->level;
266   for (level--; level>=0; level--)
267     if (ms->capture[level].len == CAP_UNFINISHED) return level;
268   return luaL_error(ms->L, "invalid pattern capture");
269 }
270 
271 
272 static const char *classend (MatchState *ms, const char *p) {
273   switch (*p++) {
274     case L_ESC: {
275       if (p == ms->p_end)
276         luaL_error(ms->L, "malformed pattern (ends with '%%')");
277       return p+1;
278     }
279     case '[': {
280       if (*p == '^') p++;
281       do {  /* look for a ']' */
282         if (p == ms->p_end)
283           luaL_error(ms->L, "malformed pattern (missing ']')");
284         if (*(p++) == L_ESC && p < ms->p_end)
285           p++;  /* skip escapes (e.g. '%]') */
286       } while (*p != ']');
287       return p+1;
288     }
289     default: {
290       return p;
291     }
292   }
293 }
294 
295 
296 static int match_class (int c, int cl) {
297   int res;
298   switch (tolower(cl)) {
299     case 'a' : res = isalpha(c); break;
300     case 'c' : res = iscntrl(c); break;
301     case 'd' : res = isdigit(c); break;
302     case 'g' : res = isgraph(c); break;
303     case 'l' : res = islower(c); break;
304     case 'p' : res = ispunct(c); break;
305     case 's' : res = isspace(c); break;
306     case 'u' : res = isupper(c); break;
307     case 'w' : res = isalnum(c); break;
308     case 'x' : res = isxdigit(c); break;
309     case 'z' : res = (c == 0); break;  /* deprecated option */
310     default: return (cl == c);
311   }
312   return (islower(cl) ? res : !res);
313 }
314 
315 
316 static int matchbracketclass (int c, const char *p, const char *ec) {
317   int sig = 1;
318   if (*(p+1) == '^') {
319     sig = 0;
320     p++;  /* skip the '^' */
321   }
322   while (++p < ec) {
323     if (*p == L_ESC) {
324       p++;
325       if (match_class(c, uchar(*p)))
326         return sig;
327     }
328     else if ((*(p+1) == '-') && (p+2 < ec)) {
329       p+=2;
330       if (uchar(*(p-2)) <= c && c <= uchar(*p))
331         return sig;
332     }
333     else if (uchar(*p) == c) return sig;
334   }
335   return !sig;
336 }
337 
338 
339 static int singlematch (MatchState *ms, const char *s, const char *p,
340                         const char *ep) {
341   if (s >= ms->src_end)
342     return 0;
343   else {
344     int c = uchar(*s);
345     switch (*p) {
346       case '.': return 1;  /* matches any char */
347       case L_ESC: return match_class(c, uchar(*(p+1)));
348       case '[': return matchbracketclass(c, p, ep-1);
349       default:  return (uchar(*p) == c);
350     }
351   }
352 }
353 
354 
355 static const char *matchbalance (MatchState *ms, const char *s,
356                                    const char *p) {
357   if (p >= ms->p_end - 1)
358     luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
359   if (*s != *p) return NULL;
360   else {
361     int b = *p;
362     int e = *(p+1);
363     int cont = 1;
364     while (++s < ms->src_end) {
365       if (*s == e) {
366         if (--cont == 0) return s+1;
367       }
368       else if (*s == b) cont++;
369     }
370   }
371   return NULL;  /* string ends out of balance */
372 }
373 
374 
375 static const char *max_expand (MatchState *ms, const char *s,
376                                  const char *p, const char *ep) {
377   ptrdiff_t i = 0;  /* counts maximum expand for item */
378   while (singlematch(ms, s + i, p, ep))
379     i++;
380   /* keeps trying to match with the maximum repetitions */
381   while (i>=0) {
382     const char *res = match(ms, (s+i), ep+1);
383     if (res) return res;
384     i--;  /* else didn't match; reduce 1 repetition to try again */
385   }
386   return NULL;
387 }
388 
389 
390 static const char *min_expand (MatchState *ms, const char *s,
391                                  const char *p, const char *ep) {
392   for (;;) {
393     const char *res = match(ms, s, ep+1);
394     if (res != NULL)
395       return res;
396     else if (singlematch(ms, s, p, ep))
397       s++;  /* try with one more repetition */
398     else return NULL;
399   }
400 }
401 
402 
403 static const char *start_capture (MatchState *ms, const char *s,
404                                     const char *p, int what) {
405   const char *res;
406   int level = ms->level;
407   if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
408   ms->capture[level].init = s;
409   ms->capture[level].len = what;
410   ms->level = level+1;
411   if ((res=match(ms, s, p)) == NULL)  /* match failed? */
412     ms->level--;  /* undo capture */
413   return res;
414 }
415 
416 
417 static const char *end_capture (MatchState *ms, const char *s,
418                                   const char *p) {
419   int l = capture_to_close(ms);
420   const char *res;
421   ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
422   if ((res = match(ms, s, p)) == NULL)  /* match failed? */
423     ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
424   return res;
425 }
426 
427 
428 static const char *match_capture (MatchState *ms, const char *s, int l) {
429   size_t len;
430   l = check_capture(ms, l);
431   len = ms->capture[l].len;
432   if ((size_t)(ms->src_end-s) >= len &&
433       memcmp(ms->capture[l].init, s, len) == 0)
434     return s+len;
435   else return NULL;
436 }
437 
438 
439 static const char *match (MatchState *ms, const char *s, const char *p) {
440   if (ms->matchdepth-- == 0)
441     luaL_error(ms->L, "pattern too complex");
442   init: /* using goto's to optimize tail recursion */
443   if (p != ms->p_end) {  /* end of pattern? */
444     switch (*p) {
445       case '(': {  /* start capture */
446         if (*(p + 1) == ')')  /* position capture? */
447           s = start_capture(ms, s, p + 2, CAP_POSITION);
448         else
449           s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
450         break;
451       }
452       case ')': {  /* end capture */
453         s = end_capture(ms, s, p + 1);
454         break;
455       }
456       case '$': {
457         if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
458           goto dflt;  /* no; go to default */
459         s = (s == ms->src_end) ? s : NULL;  /* check end of string */
460         break;
461       }
462       case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
463         switch (*(p + 1)) {
464           case 'b': {  /* balanced string? */
465             s = matchbalance(ms, s, p + 2);
466             if (s != NULL) {
467               p += 4; goto init;  /* return match(ms, s, p + 4); */
468             }  /* else fail (s == NULL) */
469             break;
470           }
471           case 'f': {  /* frontier? */
472             const char *ep; char previous;
473             p += 2;
474             if (*p != '[')
475               luaL_error(ms->L, "missing '[' after '%%f' in pattern");
476             ep = classend(ms, p);  /* points to what is next */
477             previous = (s == ms->src_init) ? '\0' : *(s - 1);
478             if (!matchbracketclass(uchar(previous), p, ep - 1) &&
479                matchbracketclass(uchar(*s), p, ep - 1)) {
480               p = ep; goto init;  /* return match(ms, s, ep); */
481             }
482             s = NULL;  /* match failed */
483             break;
484           }
485           case '0': case '1': case '2': case '3':
486           case '4': case '5': case '6': case '7':
487           case '8': case '9': {  /* capture results (%0-%9)? */
488             s = match_capture(ms, s, uchar(*(p + 1)));
489             if (s != NULL) {
490               p += 2; goto init;  /* return match(ms, s, p + 2) */
491             }
492             break;
493           }
494           default: goto dflt;
495         }
496         break;
497       }
498       default: dflt: {  /* pattern class plus optional suffix */
499         const char *ep = classend(ms, p);  /* points to optional suffix */
500         /* does not match at least once? */
501         if (!singlematch(ms, s, p, ep)) {
502           if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
503             p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
504           }
505           else  /* '+' or no suffix */
506             s = NULL;  /* fail */
507         }
508         else {  /* matched once */
509           if (ms->nrep-- == 0)
510             luaL_error(ms->L, "pattern too complex");
511           switch (*ep) {  /* handle optional suffix */
512             case '?': {  /* optional */
513               const char *res;
514               if ((res = match(ms, s + 1, ep + 1)) != NULL)
515                 s = res;
516               else {
517                 p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
518               }
519               break;
520             }
521             case '+':  /* 1 or more repetitions */
522               s++;  /* 1 match already done */
523               /* FALLTHROUGH */
524             case '*':  /* 0 or more repetitions */
525               s = max_expand(ms, s, p, ep);
526               break;
527             case '-':  /* 0 or more repetitions (minimum) */
528               s = min_expand(ms, s, p, ep);
529               break;
530             default:  /* no suffix */
531               s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
532           }
533         }
534         break;
535       }
536     }
537   }
538   ms->matchdepth++;
539   return s;
540 }
541 
542 
543 
544 static const char *lmemfind (const char *s1, size_t l1,
545                                const char *s2, size_t l2) {
546   if (l2 == 0) return s1;  /* empty strings are everywhere */
547   else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
548   else {
549     const char *init;  /* to search for a '*s2' inside 's1' */
550     l2--;  /* 1st char will be checked by 'memchr' */
551     l1 = l1-l2;  /* 's2' cannot be found after that */
552     while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
553       init++;   /* 1st char is already checked */
554       if (memcmp(init, s2+1, l2) == 0)
555         return init-1;
556       else {  /* correct 'l1' and 's1' to try again */
557         l1 -= init-s1;
558         s1 = init;
559       }
560     }
561     return NULL;  /* not found */
562   }
563 }
564 
565 
566 static void push_onecapture (MatchState *ms, int i, const char *s,
567                                                     const char *e) {
568   if (i >= ms->level) {
569     if (i == 0)  /* ms->level == 0, too */
570       lua_pushlstring(ms->L, s, e - s);  /* add whole match */
571     else
572       luaL_error(ms->L, "invalid capture index %%%d", i + 1);
573   }
574   else {
575     ptrdiff_t l = ms->capture[i].len;
576     if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
577     if (l == CAP_POSITION)
578       lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);
579     else
580       lua_pushlstring(ms->L, ms->capture[i].init, l);
581   }
582 }
583 
584 
585 static int push_captures (MatchState *ms, const char *s, const char *e) {
586   int i;
587   int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
588   luaL_checkstack(ms->L, nlevels, "too many captures");
589   for (i = 0; i < nlevels; i++)
590     push_onecapture(ms, i, s, e);
591   return nlevels;  /* number of strings pushed */
592 }
593 
594 
595 /* check whether pattern has no special characters */
596 static int nospecials (const char *p, size_t l) {
597   size_t upto = 0;
598   do {
599     if (strpbrk(p + upto, SPECIALS))
600       return 0;  /* pattern has a special character */
601     upto += strlen(p + upto) + 1;  /* may have more after \0 */
602   } while (upto <= l);
603   return 1;  /* no special chars found */
604 }
605 
606 
607 static void prepstate (MatchState *ms, lua_State *L,
608                        const char *s, size_t ls, const char *p, size_t lp) {
609   ms->L = L;
610   ms->matchdepth = MAXCCALLS;
611   ms->src_init = s;
612   ms->src_end = s + ls;
613   ms->p_end = p + lp;
614   if (ls < (MAX_SIZET - B_REPS) / A_REPS)
615     ms->nrep = A_REPS * ls + B_REPS;
616   else  /* overflow (very long subject) */
617     ms->nrep = MAX_SIZET;  /* no limit */
618 }
619 
620 
621 static void reprepstate (MatchState *ms) {
622   ms->level = 0;
623   lua_assert(ms->matchdepth == MAXCCALLS);
624 }
625 
626 
627 static int str_find_aux (lua_State *L, int find) {
628   size_t ls, lp;
629   const char *s = luaL_checklstring(L, 1, &ls);
630   const char *p = luaL_checklstring(L, 2, &lp);
631   lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls);
632   if (init < 1) init = 1;
633   else if (init > (lua_Integer)ls + 1) {  /* start after string's end? */
634     lua_pushnil(L);  /* cannot find anything */
635     return 1;
636   }
637   /* explicit request or no special characters? */
638   if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
639     /* do a plain search */
640     const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp);
641     if (s2) {
642       lua_pushinteger(L, (s2 - s) + 1);
643       lua_pushinteger(L, (s2 - s) + lp);
644       return 2;
645     }
646   }
647   else {
648     MatchState ms;
649     const char *s1 = s + init - 1;
650     int anchor = (*p == '^');
651     if (anchor) {
652       p++; lp--;  /* skip anchor character */
653     }
654     prepstate(&ms, L, s, ls, p, lp);
655     do {
656       const char *res;
657       reprepstate(&ms);
658       if ((res=match(&ms, s1, p)) != NULL) {
659         if (find) {
660           lua_pushinteger(L, (s1 - s) + 1);  /* start */
661           lua_pushinteger(L, res - s);   /* end */
662           return push_captures(&ms, NULL, 0) + 2;
663         }
664         else
665           return push_captures(&ms, s1, res);
666       }
667     } while (s1++ < ms.src_end && !anchor);
668   }
669   lua_pushnil(L);  /* not found */
670   return 1;
671 }
672 
673 
674 static int str_find (lua_State *L) {
675   return str_find_aux(L, 1);
676 }
677 
678 
679 static int str_match (lua_State *L) {
680   return str_find_aux(L, 0);
681 }
682 
683 
684 /* state for 'gmatch' */
685 typedef struct GMatchState {
686   const char *src;  /* current position */
687   const char *p;  /* pattern */
688   MatchState ms;  /* match state */
689 } GMatchState;
690 
691 
692 static int gmatch_aux (lua_State *L) {
693   GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
694   const char *src;
695   for (src = gm->src; src <= gm->ms.src_end; src++) {
696     const char *e;
697     reprepstate(&gm->ms);
698     if ((e = match(&gm->ms, src, gm->p)) != NULL) {
699       if (e == src)  /* empty match? */
700         gm->src =src + 1;  /* go at least one position */
701       else
702         gm->src = e;
703       return push_captures(&gm->ms, src, e);
704     }
705   }
706   return 0;  /* not found */
707 }
708 
709 
710 static int gmatch (lua_State *L) {
711   size_t ls, lp;
712   const char *s = luaL_checklstring(L, 1, &ls);
713   const char *p = luaL_checklstring(L, 2, &lp);
714   GMatchState *gm;
715   lua_settop(L, 2);  /* keep them on closure to avoid being collected */
716   gm = (GMatchState *)lua_newuserdata(L, sizeof(GMatchState));
717   prepstate(&gm->ms, L, s, ls, p, lp);
718   gm->src = s; gm->p = p;
719   lua_pushcclosure(L, gmatch_aux, 3);
720   return 1;
721 }
722 
723 
724 static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
725                                                    const char *e) {
726   size_t l, i;
727   lua_State *L = ms->L;
728   const char *news = lua_tolstring(L, 3, &l);
729   for (i = 0; i < l; i++) {
730     if (news[i] != L_ESC)
731       luaL_addchar(b, news[i]);
732     else {
733       i++;  /* skip ESC */
734       if (!isdigit(uchar(news[i]))) {
735         if (news[i] != L_ESC)
736           luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
737         luaL_addchar(b, news[i]);
738       }
739       else if (news[i] == '0')
740           luaL_addlstring(b, s, e - s);
741       else {
742         push_onecapture(ms, news[i] - '1', s, e);
743         luaL_tolstring(L, -1, NULL);  /* if number, convert it to string */
744         lua_remove(L, -2);  /* remove original value */
745         luaL_addvalue(b);  /* add capture to accumulated result */
746       }
747     }
748   }
749 }
750 
751 
752 static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
753                                        const char *e, int tr) {
754   lua_State *L = ms->L;
755   switch (tr) {
756     case LUA_TFUNCTION: {
757       int n;
758       lua_pushvalue(L, 3);
759       n = push_captures(ms, s, e);
760       lua_call(L, n, 1);
761       break;
762     }
763     case LUA_TTABLE: {
764       push_onecapture(ms, 0, s, e);
765       lua_gettable(L, 3);
766       break;
767     }
768     default: {  /* LUA_TNUMBER or LUA_TSTRING */
769       add_s(ms, b, s, e);
770       return;
771     }
772   }
773   if (!lua_toboolean(L, -1)) {  /* nil or false? */
774     lua_pop(L, 1);
775     lua_pushlstring(L, s, e - s);  /* keep original text */
776   }
777   else if (!lua_isstring(L, -1))
778     luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
779   luaL_addvalue(b);  /* add result to accumulator */
780 }
781 
782 
783 static int str_gsub (lua_State *L) {
784   size_t srcl, lp;
785   const char *src = luaL_checklstring(L, 1, &srcl);
786   const char *p = luaL_checklstring(L, 2, &lp);
787   int tr = lua_type(L, 3);
788   lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1);
789   int anchor = (*p == '^');
790   lua_Integer n = 0;
791   MatchState ms;
792   luaL_Buffer b;
793   luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
794                    tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
795                       "string/function/table expected");
796   luaL_buffinit(L, &b);
797   if (anchor) {
798     p++; lp--;  /* skip anchor character */
799   }
800   prepstate(&ms, L, src, srcl, p, lp);
801   while (n < max_s) {
802     const char *e;
803     reprepstate(&ms);
804     if ((e = match(&ms, src, p)) != NULL) {
805       n++;
806       add_value(&ms, &b, src, e, tr);
807     }
808     if (e && e>src) /* non empty match? */
809       src = e;  /* skip it */
810     else if (src < ms.src_end)
811       luaL_addchar(&b, *src++);
812     else break;
813     if (anchor) break;
814   }
815   luaL_addlstring(&b, src, ms.src_end-src);
816   luaL_pushresult(&b);
817   lua_pushinteger(L, n);  /* number of substitutions */
818   return 2;
819 }
820 
821 /* }====================================================== */
822 
823 
824 
825 /*
826 ** {======================================================
827 ** STRING FORMAT
828 ** =======================================================
829 */
830 
831 #if !defined(lua_number2strx)	/* { */
832 
833 /*
834 ** Hexadecimal floating-point formatter
835 */
836 
837 #include <locale.h>
838 #include <math.h>
839 
840 #define SIZELENMOD	(sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
841 
842 
843 /*
844 ** Number of bits that goes into the first digit. It can be any value
845 ** between 1 and 4; the following definition tries to align the number
846 ** to nibble boundaries by making what is left after that first digit a
847 ** multiple of 4.
848 */
849 #define L_NBFD		((l_mathlim(MANT_DIG) - 1)%4 + 1)
850 
851 
852 /*
853 ** Add integer part of 'x' to buffer and return new 'x'
854 */
855 static lua_Number adddigit (char *buff, int n, lua_Number x) {
856   lua_Number dd = l_mathop(floor)(x);  /* get integer part from 'x' */
857   int d = (int)dd;
858   buff[n] = (d < 10 ? d + '0' : d - 10 + 'a');  /* add to buffer */
859   return x - dd;  /* return what is left */
860 }
861 
862 
863 static int num2straux (char *buff, int sz, lua_Number x) {
864   if (x != x || x == HUGE_VAL || x == -HUGE_VAL)  /* inf or NaN? */
865     return l_sprintf(buff, sz, LUA_NUMBER_FMT, x);  /* equal to '%g' */
866   else if (x == 0) {  /* can be -0... */
867     /* create "0" or "-0" followed by exponent */
868     return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", x);
869   }
870   else {
871     int e;
872     lua_Number m = l_mathop(frexp)(x, &e);  /* 'x' fraction and exponent */
873     int n = 0;  /* character count */
874     if (m < 0) {  /* is number negative? */
875       buff[n++] = '-';  /* add signal */
876       m = -m;  /* make it positive */
877     }
878     buff[n++] = '0'; buff[n++] = 'x';  /* add "0x" */
879     m = adddigit(buff, n++, m * (1 << L_NBFD));  /* add first digit */
880     e -= L_NBFD;  /* this digit goes before the radix point */
881     if (m > 0) {  /* more digits? */
882       buff[n++] = lua_getlocaledecpoint();  /* add radix point */
883       do {  /* add as many digits as needed */
884         m = adddigit(buff, n++, m * 16);
885       } while (m > 0);
886     }
887     n += l_sprintf(buff + n, sz - n, "p%+d", e);  /* add exponent */
888     lua_assert(n < sz);
889     return n;
890   }
891 }
892 
893 
894 static int lua_number2strx (lua_State *L, char *buff, int sz,
895                             const char *fmt, lua_Number x) {
896   int n = num2straux(buff, sz, x);
897   if (fmt[SIZELENMOD] == 'A') {
898     int i;
899     for (i = 0; i < n; i++)
900       buff[i] = toupper(uchar(buff[i]));
901   }
902   else if (fmt[SIZELENMOD] != 'a')
903     luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
904   return n;
905 }
906 
907 #endif				/* } */
908 
909 
910 /*
911 ** Maximum size of each formatted item. This maximum size is produced
912 ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
913 ** and '\0') + number of decimal digits to represent maxfloat (which
914 ** is maximum exponent + 1). (99+3+1 then rounded to 120 for "extra
915 ** expenses", such as locale-dependent stuff)
916 */
917 #define MAX_ITEM        (120 + l_mathlim(MAX_10_EXP))
918 
919 
920 /* valid flags in a format specification */
921 #define FLAGS	"-+ #0"
922 
923 /*
924 ** maximum size of each format specification (such as "%-099.99d")
925 */
926 #define MAX_FORMAT	32
927 
928 
929 static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
930   size_t l;
931   const char *s = luaL_checklstring(L, arg, &l);
932   luaL_addchar(b, '"');
933   while (l--) {
934     if (*s == '"' || *s == '\\' || *s == '\n') {
935       luaL_addchar(b, '\\');
936       luaL_addchar(b, *s);
937     }
938     else if (*s == '\0' || iscntrl(uchar(*s))) {
939       char buff[10];
940       if (!isdigit(uchar(*(s+1))))
941         l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
942       else
943         l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
944       luaL_addstring(b, buff);
945     }
946     else
947       luaL_addchar(b, *s);
948     s++;
949   }
950   luaL_addchar(b, '"');
951 }
952 
953 static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
954   const char *p = strfrmt;
955   while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++;  /* skip flags */
956   if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
957     luaL_error(L, "invalid format (repeated flags)");
958   if (isdigit(uchar(*p))) p++;  /* skip width */
959   if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
960   if (*p == '.') {
961     p++;
962     if (isdigit(uchar(*p))) p++;  /* skip precision */
963     if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
964   }
965   if (isdigit(uchar(*p)))
966     luaL_error(L, "invalid format (width or precision too long)");
967   *(form++) = '%';
968   memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));
969   form += (p - strfrmt) + 1;
970   *form = '\0';
971   return p;
972 }
973 
974 
975 /*
976 ** add length modifier into formats
977 */
978 static void addlenmod (char *form, const char *lenmod) {
979   size_t l = strlen(form);
980   size_t lm = strlen(lenmod);
981   char spec = form[l - 1];
982   strcpy(form + l - 1, lenmod);
983   form[l + lm - 1] = spec;
984   form[l + lm] = '\0';
985 }
986 
987 
988 static int str_format (lua_State *L) {
989   int top = lua_gettop(L);
990   int arg = 1;
991   size_t sfl;
992   const char *strfrmt = luaL_checklstring(L, arg, &sfl);
993   const char *strfrmt_end = strfrmt+sfl;
994   luaL_Buffer b;
995   luaL_buffinit(L, &b);
996   while (strfrmt < strfrmt_end) {
997     if (*strfrmt != L_ESC)
998       luaL_addchar(&b, *strfrmt++);
999     else if (*++strfrmt == L_ESC)
1000       luaL_addchar(&b, *strfrmt++);  /* %% */
1001     else { /* format item */
1002       char form[MAX_FORMAT];  /* to store the format ('%...') */
1003       char *buff = luaL_prepbuffsize(&b, MAX_ITEM);  /* to put formatted item */
1004       int nb = 0;  /* number of bytes in added item */
1005       if (++arg > top)
1006         luaL_argerror(L, arg, "no value");
1007       strfrmt = scanformat(L, strfrmt, form);
1008       switch (*strfrmt++) {
1009         case 'c': {
1010           nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg));
1011           break;
1012         }
1013         case 'd': case 'i':
1014         case 'o': case 'u': case 'x': case 'X': {
1015           lua_Integer n = luaL_checkinteger(L, arg);
1016           addlenmod(form, LUA_INTEGER_FRMLEN);
1017           nb = l_sprintf(buff, MAX_ITEM, form, n);
1018           break;
1019         }
1020 #ifndef _KERNEL
1021         case 'a': case 'A':
1022           addlenmod(form, LUA_NUMBER_FRMLEN);
1023           nb = lua_number2strx(L, buff, MAX_ITEM, form,
1024                                   luaL_checknumber(L, arg));
1025           break;
1026         case 'e': case 'E': case 'f':
1027         case 'g': case 'G': {
1028           addlenmod(form, LUA_NUMBER_FRMLEN);
1029           nb = l_sprintf(buff, MAX_ITEM, form, luaL_checknumber(L, arg));
1030           break;
1031         }
1032 #endif /* _KERNEL */
1033         case 'q': {
1034           addquoted(L, &b, arg);
1035           break;
1036         }
1037         case 's': {
1038           size_t l;
1039           const char *s = luaL_tolstring(L, arg, &l);
1040           if (form[2] == '\0')  /* no modifiers? */
1041             luaL_addvalue(&b);  /* keep entire string */
1042           else {
1043             luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
1044             if (!strchr(form, '.') && l >= 100) {
1045               /* no precision and string is too long to be formatted */
1046               luaL_addvalue(&b);  /* keep entire string */
1047             }
1048             else {  /* format the string into 'buff' */
1049               nb = l_sprintf(buff, MAX_ITEM, form, s);
1050               lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
1051             }
1052           }
1053           break;
1054         }
1055         default: {  /* also treat cases 'pnLlh' */
1056           return luaL_error(L, "invalid option '%%%c' to 'format'",
1057                                *(strfrmt - 1));
1058         }
1059       }
1060       lua_assert(nb < MAX_ITEM);
1061       luaL_addsize(&b, nb);
1062     }
1063   }
1064   luaL_pushresult(&b);
1065   return 1;
1066 }
1067 
1068 /* }====================================================== */
1069 
1070 
1071 /*
1072 ** {======================================================
1073 ** PACK/UNPACK
1074 ** =======================================================
1075 */
1076 
1077 
1078 /* value used for padding */
1079 #if !defined(LUA_PACKPADBYTE)
1080 #define LUA_PACKPADBYTE		0x00
1081 #endif
1082 
1083 /* maximum size for the binary representation of an integer */
1084 #define MAXINTSIZE	16
1085 
1086 /* number of bits in a character */
1087 #define NB	CHAR_BIT
1088 
1089 /* mask for one character (NB 1's) */
1090 #define MC	((1 << NB) - 1)
1091 
1092 /* size of a lua_Integer */
1093 #define SZINT	((int)sizeof(lua_Integer))
1094 
1095 
1096 /* dummy union to get native endianness */
1097 static const union {
1098   int dummy;
1099   char little;  /* true iff machine is little endian */
1100 } nativeendian = {1};
1101 
1102 
1103 /* dummy structure to get native alignment requirements */
1104 struct cD {
1105   char c;
1106 #ifndef _KERNEL
1107   union { double d; void *p; lua_Integer i; lua_Number n; } u;
1108 #else /* _KERNEL */
1109   union { void *p; lua_Integer i; lua_Number n; } u;
1110 #endif /* _KERNEL */
1111 };
1112 
1113 #define MAXALIGN	(offsetof(struct cD, u))
1114 
1115 
1116 #ifndef _KERNEL
1117 /*
1118 ** Union for serializing floats
1119 */
1120 typedef union Ftypes {
1121   float f;
1122   double d;
1123   lua_Number n;
1124   char buff[5 * sizeof(lua_Number)];  /* enough for any float type */
1125 } Ftypes;
1126 #endif /* _KERNEL */
1127 
1128 
1129 /*
1130 ** information to pack/unpack stuff
1131 */
1132 typedef struct Header {
1133   lua_State *L;
1134   int islittle;
1135   int maxalign;
1136 } Header;
1137 
1138 
1139 /*
1140 ** options for pack/unpack
1141 */
1142 typedef enum KOption {
1143   Kint,		/* signed integers */
1144   Kuint,	/* unsigned integers */
1145 #ifndef _KERNEL
1146   Kfloat,	/* floating-point numbers */
1147 #endif /* _KERNEL */
1148   Kchar,	/* fixed-length strings */
1149   Kstring,	/* strings with prefixed length */
1150   Kzstr,	/* zero-terminated strings */
1151   Kpadding,	/* padding */
1152   Kpaddalign,	/* padding for alignment */
1153   Knop		/* no-op (configuration or spaces) */
1154 } KOption;
1155 
1156 
1157 /*
1158 ** Read an integer numeral from string 'fmt' or return 'df' if
1159 ** there is no numeral
1160 */
1161 static int digit (int c) { return '0' <= c && c <= '9'; }
1162 
1163 static int getnum (const char **fmt, int df) {
1164   if (!digit(**fmt))  /* no number? */
1165     return df;  /* return default value */
1166   else {
1167     int a = 0;
1168     do {
1169       a = a*10 + (*((*fmt)++) - '0');
1170     } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
1171     return a;
1172   }
1173 }
1174 
1175 
1176 /*
1177 ** Read an integer numeral and raises an error if it is larger
1178 ** than the maximum size for integers.
1179 */
1180 static int getnumlimit (Header *h, const char **fmt, int df) {
1181   int sz = getnum(fmt, df);
1182   if (sz > MAXINTSIZE || sz <= 0)
1183     luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
1184                      sz, MAXINTSIZE);
1185   return sz;
1186 }
1187 
1188 
1189 /*
1190 ** Initialize Header
1191 */
1192 static void initheader (lua_State *L, Header *h) {
1193   h->L = L;
1194   h->islittle = nativeendian.little;
1195   h->maxalign = 1;
1196 }
1197 
1198 
1199 /*
1200 ** Read and classify next option. 'size' is filled with option's size.
1201 */
1202 static KOption getoption (Header *h, const char **fmt, int *size) {
1203   int opt = *((*fmt)++);
1204   *size = 0;  /* default */
1205   switch (opt) {
1206     case 'b': *size = sizeof(char); return Kint;
1207     case 'B': *size = sizeof(char); return Kuint;
1208     case 'h': *size = sizeof(short); return Kint;
1209     case 'H': *size = sizeof(short); return Kuint;
1210     case 'l': *size = sizeof(long); return Kint;
1211     case 'L': *size = sizeof(long); return Kuint;
1212     case 'j': *size = sizeof(lua_Integer); return Kint;
1213     case 'J': *size = sizeof(lua_Integer); return Kuint;
1214     case 'T': *size = sizeof(size_t); return Kuint;
1215 #ifndef _KERNEL
1216     case 'f': *size = sizeof(float); return Kfloat;
1217     case 'd': *size = sizeof(double); return Kfloat;
1218     case 'n': *size = sizeof(lua_Number); return Kfloat;
1219 #else /* _KERNEL */
1220     case 'n': *size = sizeof(lua_Number); return Kint;
1221 #endif /* _KERNEL */
1222     case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1223     case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1224     case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1225     case 'c':
1226       *size = getnum(fmt, -1);
1227       if (*size == -1)
1228         luaL_error(h->L, "missing size for format option 'c'");
1229       return Kchar;
1230     case 'z': return Kzstr;
1231     case 'x': *size = 1; return Kpadding;
1232     case 'X': return Kpaddalign;
1233     case ' ': break;
1234     case '<': h->islittle = 1; break;
1235     case '>': h->islittle = 0; break;
1236     case '=': h->islittle = nativeendian.little; break;
1237     case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
1238     default: luaL_error(h->L, "invalid format option '%c'", opt);
1239   }
1240   return Knop;
1241 }
1242 
1243 
1244 /*
1245 ** Read, classify, and fill other details about the next option.
1246 ** 'psize' is filled with option's size, 'notoalign' with its
1247 ** alignment requirements.
1248 ** Local variable 'size' gets the size to be aligned. (Kpadal option
1249 ** always gets its full alignment, other options are limited by
1250 ** the maximum alignment ('maxalign'). Kchar option needs no alignment
1251 ** despite its size.
1252 */
1253 static KOption getdetails (Header *h, size_t totalsize,
1254                            const char **fmt, int *psize, int *ntoalign) {
1255   KOption opt = getoption(h, fmt, psize);
1256   int align = *psize;  /* usually, alignment follows size */
1257   if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
1258     if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1259       luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1260   }
1261   if (align <= 1 || opt == Kchar)  /* need no alignment? */
1262     *ntoalign = 0;
1263   else {
1264     if (align > h->maxalign)  /* enforce maximum alignment */
1265       align = h->maxalign;
1266     if ((align & (align - 1)) != 0)  /* is 'align' not a power of 2? */
1267       luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
1268     *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
1269   }
1270   return opt;
1271 }
1272 
1273 
1274 /*
1275 ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
1276 ** The final 'if' handles the case when 'size' is larger than
1277 ** the size of a Lua integer, correcting the extra sign-extension
1278 ** bytes if necessary (by default they would be zeros).
1279 */
1280 static void packint (luaL_Buffer *b, lua_Unsigned n,
1281                      int islittle, int size, int neg) {
1282   char *buff = luaL_prepbuffsize(b, size);
1283   int i;
1284   buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */
1285   for (i = 1; i < size; i++) {
1286     n >>= NB;
1287     buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1288   }
1289   if (neg && size > SZINT) {  /* negative number need sign extension? */
1290     for (i = SZINT; i < size; i++)  /* correct extra bytes */
1291       buff[islittle ? i : size - 1 - i] = (char)MC;
1292   }
1293   luaL_addsize(b, size);  /* add result to buffer */
1294 }
1295 
1296 
1297 #ifndef _KERNEL
1298 /*
1299 ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
1300 ** given 'islittle' is different from native endianness.
1301 */
1302 static void copywithendian (volatile char *dest, volatile const char *src,
1303                             int size, int islittle) {
1304   if (islittle == nativeendian.little) {
1305     while (size-- != 0)
1306       *(dest++) = *(src++);
1307   }
1308   else {
1309     dest += size - 1;
1310     while (size-- != 0)
1311       *(dest--) = *(src++);
1312   }
1313 }
1314 #endif /* _KERNEL */
1315 
1316 
1317 static int str_pack (lua_State *L) {
1318   luaL_Buffer b;
1319   Header h;
1320   const char *fmt = luaL_checkstring(L, 1);  /* format string */
1321   int arg = 1;  /* current argument to pack */
1322   size_t totalsize = 0;  /* accumulate total size of result */
1323   initheader(L, &h);
1324   lua_pushnil(L);  /* mark to separate arguments from string buffer */
1325   luaL_buffinit(L, &b);
1326   while (*fmt != '\0') {
1327     int size, ntoalign;
1328     KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1329     totalsize += ntoalign + size;
1330     while (ntoalign-- > 0)
1331      luaL_addchar(&b, LUA_PACKPADBYTE);  /* fill alignment */
1332     arg++;
1333     switch (opt) {
1334       case Kint: {  /* signed integers */
1335         lua_Integer n = luaL_checkinteger(L, arg);
1336         if (size < SZINT) {  /* need overflow check? */
1337           lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1338           luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1339         }
1340         packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
1341         break;
1342       }
1343       case Kuint: {  /* unsigned integers */
1344         lua_Integer n = luaL_checkinteger(L, arg);
1345         if (size < SZINT)  /* need overflow check? */
1346           luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1347                            arg, "unsigned overflow");
1348         packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
1349         break;
1350       }
1351 #ifndef _KERNEL
1352       case Kfloat: {  /* floating-point options */
1353         volatile Ftypes u;
1354         char *buff = luaL_prepbuffsize(&b, size);
1355         lua_Number n = luaL_checknumber(L, arg);  /* get argument */
1356         if (size == sizeof(u.f)) u.f = (float)n;  /* copy it into 'u' */
1357         else if (size == sizeof(u.d)) u.d = (double)n;
1358         else u.n = n;
1359         /* move 'u' to final result, correcting endianness if needed */
1360         copywithendian(buff, u.buff, size, h.islittle);
1361         luaL_addsize(&b, size);
1362         break;
1363       }
1364 #endif /* _KERNEL */
1365       case Kchar: {  /* fixed-size string */
1366         size_t len;
1367         const char *s = luaL_checklstring(L, arg, &len);
1368         if ((size_t)size <= len)  /* string larger than (or equal to) needed? */
1369           luaL_addlstring(&b, s, size);  /* truncate string to asked size */
1370         else {  /* string smaller than needed */
1371           luaL_addlstring(&b, s, len);  /* add it all */
1372           while (len++ < (size_t)size)  /* pad extra space */
1373             luaL_addchar(&b, LUA_PACKPADBYTE);
1374         }
1375         break;
1376       }
1377       case Kstring: {  /* strings with length count */
1378         size_t len;
1379         const char *s = luaL_checklstring(L, arg, &len);
1380         luaL_argcheck(L, size >= (int)sizeof(size_t) ||
1381                          len < ((size_t)1 << (size * NB)),
1382                          arg, "string length does not fit in given size");
1383         packint(&b, (lua_Unsigned)len, h.islittle, size, 0);  /* pack length */
1384         luaL_addlstring(&b, s, len);
1385         totalsize += len;
1386         break;
1387       }
1388       case Kzstr: {  /* zero-terminated string */
1389         size_t len;
1390         const char *s = luaL_checklstring(L, arg, &len);
1391         luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1392         luaL_addlstring(&b, s, len);
1393         luaL_addchar(&b, '\0');  /* add zero at the end */
1394         totalsize += len + 1;
1395         break;
1396       }
1397       case Kpadding: luaL_addchar(&b, LUA_PACKPADBYTE);  /* FALLTHROUGH */
1398       case Kpaddalign: case Knop:
1399         arg--;  /* undo increment */
1400         break;
1401     }
1402   }
1403   luaL_pushresult(&b);
1404   return 1;
1405 }
1406 
1407 
1408 static int str_packsize (lua_State *L) {
1409   Header h;
1410   const char *fmt = luaL_checkstring(L, 1);  /* format string */
1411   size_t totalsize = 0;  /* accumulate total size of result */
1412   initheader(L, &h);
1413   while (*fmt != '\0') {
1414     int size, ntoalign;
1415     KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1416     size += ntoalign;  /* total space used by option */
1417     luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
1418                      "format result too large");
1419     totalsize += size;
1420     switch (opt) {
1421       case Kstring:  /* strings with length count */
1422       case Kzstr:    /* zero-terminated string */
1423         luaL_argerror(L, 1, "variable-length format");
1424         /* call never return, but to avoid warnings: *//* FALLTHROUGH */
1425       default:  break;
1426     }
1427   }
1428   lua_pushinteger(L, (lua_Integer)totalsize);
1429   return 1;
1430 }
1431 
1432 
1433 /*
1434 ** Unpack an integer with 'size' bytes and 'islittle' endianness.
1435 ** If size is smaller than the size of a Lua integer and integer
1436 ** is signed, must do sign extension (propagating the sign to the
1437 ** higher bits); if size is larger than the size of a Lua integer,
1438 ** it must check the unread bytes to see whether they do not cause an
1439 ** overflow.
1440 */
1441 static lua_Integer unpackint (lua_State *L, const char *str,
1442                               int islittle, int size, int issigned) {
1443   lua_Unsigned res = 0;
1444   int i;
1445   int limit = (size  <= SZINT) ? size : SZINT;
1446   for (i = limit - 1; i >= 0; i--) {
1447     res <<= NB;
1448     res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
1449   }
1450   if (size < SZINT) {  /* real size smaller than lua_Integer? */
1451     if (issigned) {  /* needs sign extension? */
1452       lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1453       res = ((res ^ mask) - mask);  /* do sign extension */
1454     }
1455   }
1456   else if (size > SZINT) {  /* must check unread bytes */
1457     int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1458     for (i = limit; i < size; i++) {
1459       if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
1460         luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
1461     }
1462   }
1463   return (lua_Integer)res;
1464 }
1465 
1466 
1467 static int str_unpack (lua_State *L) {
1468   Header h;
1469   const char *fmt = luaL_checkstring(L, 1);
1470   size_t ld;
1471   const char *data = luaL_checklstring(L, 2, &ld);
1472   size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1;
1473   int n = 0;  /* number of results */
1474   luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1475   initheader(L, &h);
1476   while (*fmt != '\0') {
1477     int size, ntoalign;
1478     KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1479     if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld)
1480       luaL_argerror(L, 2, "data string too short");
1481     pos += ntoalign;  /* skip alignment */
1482     /* stack space for item + next position */
1483     luaL_checkstack(L, 2, "too many results");
1484     n++;
1485     switch (opt) {
1486       case Kint:
1487       case Kuint: {
1488         lua_Integer res = unpackint(L, data + pos, h.islittle, size,
1489                                        (opt == Kint));
1490         lua_pushinteger(L, res);
1491         break;
1492       }
1493 #ifndef _KERNEL
1494       case Kfloat: {
1495         volatile Ftypes u;
1496         lua_Number num;
1497         copywithendian(u.buff, data + pos, size, h.islittle);
1498         if (size == sizeof(u.f)) num = (lua_Number)u.f;
1499         else if (size == sizeof(u.d)) num = (lua_Number)u.d;
1500         else num = u.n;
1501         lua_pushnumber(L, num);
1502         break;
1503       }
1504 #endif /* _KERNEL */
1505       case Kchar: {
1506         lua_pushlstring(L, data + pos, size);
1507         break;
1508       }
1509       case Kstring: {
1510         size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
1511         luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short");
1512         lua_pushlstring(L, data + pos + size, len);
1513         pos += len;  /* skip string */
1514         break;
1515       }
1516       case Kzstr: {
1517         size_t len = (int)strlen(data + pos);
1518         lua_pushlstring(L, data + pos, len);
1519         pos += len + 1;  /* skip string plus final '\0' */
1520         break;
1521       }
1522       case Kpaddalign: case Kpadding: case Knop:
1523         n--;  /* undo increment */
1524         break;
1525     }
1526     pos += size;
1527   }
1528   lua_pushinteger(L, pos + 1);  /* next position */
1529   return n + 1;
1530 }
1531 
1532 /* }====================================================== */
1533 
1534 
1535 static const luaL_Reg strlib[] = {
1536   {"byte", str_byte},
1537   {"char", str_char},
1538   {"dump", str_dump},
1539   {"find", str_find},
1540   {"format", str_format},
1541   {"gmatch", gmatch},
1542   {"gsub", str_gsub},
1543   {"len", str_len},
1544   {"lower", str_lower},
1545   {"match", str_match},
1546   {"rep", str_rep},
1547   {"reverse", str_reverse},
1548   {"sub", str_sub},
1549   {"upper", str_upper},
1550   {"pack", str_pack},
1551   {"packsize", str_packsize},
1552   {"unpack", str_unpack},
1553   {NULL, NULL}
1554 };
1555 
1556 
1557 static void createmetatable (lua_State *L) {
1558   lua_createtable(L, 0, 1);  /* table to be metatable for strings */
1559   lua_pushliteral(L, "");  /* dummy string */
1560   lua_pushvalue(L, -2);  /* copy table */
1561   lua_setmetatable(L, -2);  /* set table as metatable for strings */
1562   lua_pop(L, 1);  /* pop dummy string */
1563   lua_pushvalue(L, -2);  /* get string library */
1564   lua_setfield(L, -2, "__index");  /* metatable.__index = string */
1565   lua_pop(L, 1);  /* pop metatable */
1566 }
1567 
1568 
1569 /*
1570 ** Open string library
1571 */
1572 LUAMOD_API int luaopen_string (lua_State *L) {
1573   luaL_newlib(L, strlib);
1574   createmetatable(L);
1575   return 1;
1576 }
1577 
1578