lstrlib.c 45 KB

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