2
0

lstrlib.c 45 KB

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