forked from renatomaia/lua-memory
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lmemmod.c
860 lines (782 loc) · 24.5 KB
/
lmemmod.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
#define lmemmod_c
#include "lmemlib.h"
#ifndef _KERNEL
#include <string.h>
#else
#include <linux/module.h>
#include <linux/string.h>
#endif /* _KERNEL */
#include <lualib.h>
static lua_Integer posrelat (lua_Integer pos, size_t len);
static int str2byte (lua_State *L, const char *s, size_t l);
static void code2char (lua_State *L, int idx, char *p, lua_Integer n);
static const char *lmemfind (const char *s1, size_t l1,
const char *s2, size_t l2);
static int mem_create (lua_State *L) {
if (lua_gettop(L) == 0) {
luamem_newref(L);
luamem_setref(L, 1, NULL, 0, luamem_free);
} else {
char *p;
size_t len;
const char *s = NULL;
if (lua_type(L, 1) == LUA_TNUMBER) {
len = luamem_checklenarg(L, 1);
} else {
lua_Integer posi, pose;
s = luamem_checkstring(L, 1, &len);
posi = posrelat(luaL_optinteger(L, 2, 1), len);
pose = posrelat(luaL_optinteger(L, 3, -1), len);
if (posi < 1) posi = 1;
if (pose > (lua_Integer)len) pose = len;
if (posi > pose) {
len = 0;
s = NULL;
} else {
if (pose - posi >= INT_MAX) /* arithmetic overflow? */
return luaL_error(L, "string slice too long");
len = (pose - posi) + 1;
s += posi-1;
}
}
p = luamem_newalloc(L, len);
if (s) memcpy(p, s, len*sizeof(char));
else memset(p, 0, len*sizeof(char));
}
return 1;
}
static void memfill (char *mem, size_t size, const char *s, size_t len) {
do {
size_t n = size < len ? size : len;
memmove(mem, s, n * sizeof(char));
mem += n;
size -= n;
} while (size > 0);
}
static int mem_resize (lua_State *L) {
size_t len;
luamem_Unref unref;
char *mem = luamem_tomemoryx(L, 1, &len, &unref, NULL);
size_t size = luamem_checklenarg(L, 2);
luaL_argcheck(L, unref == luamem_free, 1, "resizable memory expected");
if (len != size) {
size_t sl, n = len < size ? size-len : 0;
const char *s = luamem_optstring(L, 3, NULL, &sl);
char *resized = (char *)luamem_realloc(L, mem, len, size);
if (size && !resized) luaL_error(L, "out of memory");
luamem_setref(L, 1, mem, len, NULL); /* don't free `mem` again */
luamem_setref(L, 1, resized, size, luamem_free);
if (n) {
resized += len;
if (sl) memfill(resized, n, s, sl);
else memset(resized, 0, n*sizeof(char));
}
}
return 0;
}
static int mem_type (lua_State *L) {
luamem_Unref unref;
int type;
luamem_tomemoryx(L, 1, NULL, &unref, &type);
if (type == LUAMEM_TALLOC) {
lua_pushliteral(L, "fixed");
} else if (type == LUAMEM_TREF) {
if (unref == luamem_free) lua_pushliteral(L, "resizable");
else lua_pushliteral(L, "other");
} else {
lua_pushnil(L);
}
return 1;
}
static int mem_len (lua_State *L) {
size_t len;
luamem_checkmemory(L, 1, &len);
lua_pushinteger(L, (lua_Integer)len);
return 1;
}
static int mem_tostring (lua_State *L) {
size_t len;
const char *s = luamem_checkstring(L, 1, &len);
lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), len);
lua_Integer pose = posrelat(luaL_optinteger(L, 3, -1), len);
int n;
if (posi < 1) posi = 1;
if (pose > (lua_Integer)len) pose = len;
n = (int)(pose - posi + 1);
if (posi + n <= pose) /* arithmetic overflow? */
return luaL_error(L, "string slice too long");
if (n > 0) lua_pushlstring(L, s + posi -1, n);
else lua_pushliteral(L, "");
return 1;
}
static int mem_diff (lua_State *L) {
size_t l1, l2;
const char *s1 = luamem_checkstring(L, 1, &l1);
const char *s2 = luamem_checkstring(L, 2, &l2);
size_t i, n=(l1<l2 ? l1 : l2);
for (i=0; (i<n) && (s1[i]==s2[i]); ++i);
if (i<n) {
lua_pushinteger(L, i+1);
lua_pushboolean(L, s1[i]<s2[i]);
} else if (l1==l2) {
lua_pushnil(L);
lua_pushboolean(L, 0);
} else {
lua_pushinteger(L, i+1);
lua_pushboolean(L, l1<l2);
}
return 2;
}
static int mem_get (lua_State *L) {
size_t len;
const char *s = luamem_checkmemory(L, 1, &len);
return str2byte(L, s, len);
}
static int mem_set (lua_State *L) {
size_t len;
lua_Integer n = lua_gettop(L)-2; /* number of bytes */
char *p = luamem_checkmemory(L, 1, &len);
lua_Integer i = posrelat(luaL_checkinteger(L, 2), len);
luaL_argcheck(L, 1 <= i && i <= (lua_Integer)len, 2, "index out of bounds");
len = 1+len-i;
code2char(L, 3, p+i-1, n < (lua_Integer)len ? n : (lua_Integer)len);
return 0;
}
static int mem_find (lua_State *L) {
size_t len, sl;
const char *p = luamem_checkstring(L, 1, &len);
const char *s = luamem_checkstring(L, 2, &sl);
lua_Integer i = posrelat(luaL_optinteger(L, 3, 1), len);
lua_Integer j = posrelat(luaL_optinteger(L, 4, -1), len);
lua_Integer os = posrelat(luaL_optinteger(L, 5, 1), sl);
if (os < 1) os = 1;
if (i <= j && os <= (lua_Integer)sl) {
int n = (int)(j - i + 1);
if (i + n <= j) /* arithmetic overflow? */
return luaL_error(L, "string slice too long");
--os;
sl -= os;
s = lmemfind(p + i - 1, (size_t)n, s + os, sl);
if (s) {
lua_pushinteger(L, (s - p) + 1);
lua_pushinteger(L, (s - p) + sl);
return 2;
}
}
return 0;
}
static int mem_fill (lua_State *L) {
size_t len, sl;
char *p = luamem_checkmemory(L, 1, &len);
lua_Integer i = posrelat(luaL_optinteger(L, 3, 1), len);
lua_Integer j = posrelat(luaL_optinteger(L, 4, -1), len);
char c;
const char *s = NULL;
lua_Integer os;
if (lua_type(L, 2) == LUA_TNUMBER) {
s = &c;
sl = 1;
os = 1;
code2char(L, 2, &c, 1);
} else {
s = luamem_checkstring(L, 2, &sl);
os = posrelat(luaL_optinteger(L, 5, 1), sl);
}
if (os < 1) os = 1;
if (i <= j && os <= (lua_Integer)sl) {
size_t n = (size_t)(j-i+1);
luaL_argcheck(L, 1 <= i && i <= (lua_Integer)len, 3, "index out of bounds");
luaL_argcheck(L, 1 <= j && j <= (lua_Integer)len, 4, "index out of bounds");
if (i+(lua_Integer)n <= j) /* arithmetic overflow? */
return luaL_error(L, "string slice too long");
--os;
memfill(p+i-1, n, s+os, sl-os);
}
return 0;
}
static int mem_pack (lua_State *L);
static int mem_unpack (lua_State *L);
static const luaL_Reg lib[] = {
{"create", mem_create},
{"type", mem_type},
{"resize", mem_resize},
{"len", mem_len},
{"diff", mem_diff},
{"find", mem_find},
{"fill", mem_fill},
{"get", mem_get},
{"set", mem_set},
{"pack", mem_pack},
{"unpack", mem_unpack},
{"tostring", mem_tostring},
{NULL, NULL}
};
static const luaL_Reg meta[] = {
{"__len", mem_len},
{"__tostring", mem_tostring},
{NULL, NULL}
};
static void setupmetatable (lua_State *L) {
if (lua_getmetatable(L, -1)) {
luaL_setfuncs(L, meta, 0); /* add metamethods to metatable */
lua_pushvalue(L, 1); /* push library */
lua_setfield(L, -2, "__index"); /* metatable.__index = library */
lua_pop(L, 1); /* pop metatable */
}
lua_pop(L, 1); /* pop memory */
}
LUAMEMMOD_API int luaopen_memory (lua_State *L) {
luaL_newlib(L, lib);
luamem_newalloc(L, 0);
setupmetatable(L);
luamem_newref(L);
setupmetatable(L);
return 1;
}
#ifdef _KERNEL
MODULE_LICENSE("Dual MIT/BSD");
MODULE_DESCRIPTION("Library for manipulation of memory areas in Lua");
EXPORT_SYMBOL(luamem_addvalue);
EXPORT_SYMBOL(luamem_checklenarg);
EXPORT_SYMBOL(luamem_checkmemory);
EXPORT_SYMBOL(luamem_checkstring);
EXPORT_SYMBOL(luamem_free);
EXPORT_SYMBOL(luamem_isstring);
EXPORT_SYMBOL(luamem_newalloc);
EXPORT_SYMBOL(luamem_newref);
EXPORT_SYMBOL(luamem_pushresult);
EXPORT_SYMBOL(luamem_pushresultsize);
EXPORT_SYMBOL(luamem_realloc);
EXPORT_SYMBOL(luamem_setref);
EXPORT_SYMBOL(luamem_tomemoryx);
EXPORT_SYMBOL(luamem_tostring);
EXPORT_SYMBOL(luamem_type);
EXPORT_SYMBOL(luaopen_memory);
static int __init modinit (void) {
return 0;
}
static void __exit modexit (void) {
}
module_init(modinit);
module_exit(modexit);
#endif /* _KERNEL */
/*
* NOTE: most of the code below is copied from the source of Lua 5.3.1 by
* R. Ierusalimschy, L. H. de Figueiredo, W. Celes - Lua.org, PUC-Rio.
*
* Copyright (C) 1994-2015 Lua.org, PUC-Rio.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* macro to 'unsign' a character */
#define uchar(c) ((unsigned char)(c))
/* translate a relative string position: negative means back from end */
static lua_Integer posrelat (lua_Integer pos, size_t len) {
if (pos >= 0) return pos;
else if (0u - (size_t)pos > len) return 0;
else return (lua_Integer)len + pos + 1;
}
static int str2byte (lua_State *L, const char *s, size_t l) {
lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l);
lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);
int n, i;
if (posi < 1) posi = 1;
if (pose > (lua_Integer)l) pose = l;
if (posi > pose) return 0; /* empty interval; return no values */
n = (int)(pose - posi + 1);
if (posi + n <= pose) /* arithmetic overflow? */
return luaL_error(L, "string slice too long");
luaL_checkstack(L, n, "string slice too long");
for (i=0; i<n; i++)
lua_pushinteger(L, uchar(s[posi+i-1]));
return n;
}
static void code2char (lua_State *L, int idx, char *p, lua_Integer n) {
int i;
for (i=0; i<n; ++i, ++idx) {
lua_Integer c = luaL_checkinteger(L, idx);
luaL_argcheck(L, uchar(c) == c, idx, "value out of range");
p[i] = uchar(c);
}
}
static const char *lmemfind (const char *s1, size_t l1,
const char *s2, size_t l2) {
if (l2 == 0) return s1; /* empty strings are everywhere */
else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
else {
const char *init; /* to search for a '*s2' inside 's1' */
l2--; /* 1st char will be checked by 'memchr' */
l1 = l1-l2; /* 's2' cannot be found after that */
while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
init++; /* 1st char is already checked */
if (memcmp(init, s2+1, l2) == 0)
return init-1;
else { /* correct 'l1' and 's1' to try again */
l1 -= init-s1;
s1 = init;
}
}
return NULL; /* not found */
}
}
/*
** {======================================================
** PACK/UNPACK
** =======================================================
*/
/* value used for padding */
#if !defined(LUA_PACKPADBYTE)
#define LUA_PACKPADBYTE 0x00
#endif
/* maximum size for the binary representation of an integer */
#define MAXINTSIZE 16
/* number of bits in a character */
#define NB CHAR_BIT
/* mask for one character (NB 1's) */
#define MC ((1 << NB) - 1)
/* size of a lua_Integer */
#define SZINT ((int)sizeof(lua_Integer))
/* dummy union to get native endianness */
static const union {
int dummy;
char little; /* true iff machine is little endian */
} nativeendian = {1};
/* dummy structure to get native alignment requirements */
struct cD {
char c;
#ifndef _KERNEL
union { double d; void *p; lua_Integer i; lua_Number n; } u;
#else /* _KERNEL */
union { void *p; lua_Integer i; lua_Number n; } u;
#endif /* _KERNEL */
};
#define MAXALIGN (offsetof(struct cD, u))
#ifndef _KERNEL
/*
** Union for serializing floats
*/
typedef union Ftypes {
float f;
double d;
lua_Number n;
char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
} Ftypes;
#endif /* _KERNEL */
/*
** information to pack/unpack stuff
*/
typedef struct Header {
lua_State *L;
int islittle;
int maxalign;
} Header;
/*
** options for pack/unpack
*/
typedef enum KOption {
Kint, /* signed integers */
Kuint, /* unsigned integers */
#ifndef _KERNEL
Kfloat, /* floating-point numbers */
#endif /* _KERNEL */
Kchar, /* fixed-length strings */
Kstring, /* strings with prefixed length */
Kzstr, /* zero-terminated strings */
Kpadding, /* padding */
Kpaddalign, /* padding for alignment */
Knop /* no-op (configuration or spaces) */
} KOption;
/*
** Read an integer numeral from string 'fmt' or return 'df' if
** there is no numeral
*/
static int digit (int c) { return '0' <= c && c <= '9'; }
static int getnum (const char **fmt, int df) {
if (!digit(**fmt)) /* no number? */
return df; /* return default value */
else {
int a = 0;
do {
a = a*10 + (*((*fmt)++) - '0');
} while (digit(**fmt) && a <= ((int)LUAMEM_MAXALLOC - 9)/10);
return a;
}
}
/*
** Read an integer numeral and raises an error if it is larger
** than the maximum size for integers.
*/
static int getnumlimit (Header *h, const char **fmt, int df) {
int sz = getnum(fmt, df);
if (sz > MAXINTSIZE || sz <= 0)
luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
sz, MAXINTSIZE);
return sz;
}
/*
** Initialize Header
*/
static void initheader (lua_State *L, Header *h) {
h->L = L;
h->islittle = nativeendian.little;
h->maxalign = 1;
}
/*
** Read and classify next option. 'size' is filled with option's size.
*/
static KOption getoption (Header *h, const char **fmt, int *size) {
int opt = *((*fmt)++);
*size = 0; /* default */
switch (opt) {
case 'b': *size = sizeof(char); return Kint;
case 'B': *size = sizeof(char); return Kuint;
case 'h': *size = sizeof(short); return Kint;
case 'H': *size = sizeof(short); return Kuint;
case 'l': *size = sizeof(long); return Kint;
case 'L': *size = sizeof(long); return Kuint;
case 'j': *size = sizeof(lua_Integer); return Kint;
case 'J': *size = sizeof(lua_Integer); return Kuint;
case 'T': *size = sizeof(size_t); return Kuint;
#ifndef _KERNEL
case 'f': *size = sizeof(float); return Kfloat;
case 'd': *size = sizeof(double); return Kfloat;
case 'n': *size = sizeof(lua_Number); return Kfloat;
#else /* _KERNEL */
case 'n': *size = sizeof(lua_Number); return Kint;
#endif /* _KERNEL */
case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
case 'c':
*size = getnum(fmt, -1);
if (*size == -1)
luaL_error(h->L, "missing size for format option 'c'");
return Kchar;
case 'z': return Kzstr;
case 'x': *size = 1; return Kpadding;
case 'X': return Kpaddalign;
case ' ': break;
case '<': h->islittle = 1; break;
case '>': h->islittle = 0; break;
case '=': h->islittle = nativeendian.little; break;
case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
default: luaL_error(h->L, "invalid format option '%c'", opt);
}
return Knop;
}
/*
** Read, classify, and fill other details about the next option.
** 'psize' is filled with option's size, 'notoalign' with its
** alignment requirements.
** Local variable 'size' gets the size to be aligned. (Kpadal option
** always gets its full alignment, other options are limited by
** the maximum alignment ('maxalign'). Kchar option needs no alignment
** despite its size.
*/
static KOption getdetails (Header *h, size_t totalsize,
const char **fmt, int *psize, int *ntoalign) {
KOption opt = getoption(h, fmt, psize);
int align = *psize; /* usually, alignment follows size */
if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
luaL_argerror(h->L, 1, "invalid next option for option 'X'");
}
if (align <= 1 || opt == Kchar) /* need no alignment? */
*ntoalign = 0;
else {
if (align > h->maxalign) /* enforce maximum alignment */
align = h->maxalign;
if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
*ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
}
return opt;
}
static char *getbytes (char **b, size_t *i, size_t lb, size_t sz) {
size_t newtotal = *i+sz;
if (newtotal<=lb) {
char *res = *b;
*b += sz;
*i = newtotal;
return res;
}
return NULL;
}
static int packfailed (lua_State *L, size_t i, size_t arg) {
lua_pushboolean(L, 0);
lua_replace(L, arg-2);
lua_pushinteger(L, i+1);
lua_replace(L, arg-1);
return 3+lua_gettop(L)-arg;
}
static int packchar (char **b, size_t *i, size_t lb, const char c) {
if (*i<lb) {
(void)(*i)++;
*((*b)++) = c;
return 1;
}
return 0;
}
static int packstream (char **b, size_t *i, size_t lb,
const char *s, size_t sl) {
if (sl > 0) { /* avoid 'memcpy' when 's' can be NULL */
char *d = getbytes(b, i, lb, sl);
if (d == NULL) return 0;
memcpy(d, s, sl * sizeof(char));
}
return 1;
}
/*
** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
** The final 'if' handles the case when 'size' is larger than
** the size of a Lua integer, correcting the extra sign-extension
** bytes if necessary (by default they would be zeros).
*/
static int packint (char **b, size_t *pos, size_t lb,
lua_Unsigned n, int islittle, int size, int neg) {
char *buff = getbytes(b, pos, lb, size);
if (buff) {
int i;
buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
for (i = 1; i < size; i++) {
n >>= NB;
buff[islittle ? i : size - 1 - i] = (char)(n & MC);
}
if (neg && size > SZINT) { /* negative number need sign extension? */
for (i = SZINT; i < size; i++) /* correct extra bytes */
buff[islittle ? i : size - 1 - i] = (char)MC;
}
return 1;
}
return 0;
}
#ifndef _KERNEL
/*
** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
** given 'islittle' is different from native endianness.
*/
static void copywithendian (volatile char *dest, volatile const char *src,
int size, int islittle) {
if (islittle == nativeendian.little) {
while (size-- != 0)
*(dest++) = *(src++);
}
else {
dest += size - 1;
while (size-- != 0)
*(dest--) = *(src++);
}
}
#endif /* _KERNEL */
static int mem_pack (lua_State *L) {
Header h;
size_t i, lb;
char *mem = luamem_checkmemory(L, 1, &lb);
const char *fmt = luaL_checkstring(L, 2); /* format string */
lua_Integer pos = posrelat(luaL_checkinteger(L, 3), lb)-1;
int arg = 3; /* current argument to pack */
luaL_argcheck(L, 0 <= pos && pos <= (lua_Integer)lb, 3,
"index out of bounds");
initheader(L, &h);
i = (size_t)pos;
mem += i;
while (*fmt != '\0') {
int size, ntoalign;
KOption opt = getdetails(&h, i, &fmt, &size, &ntoalign);
arg++;
if (!getbytes(&mem, &i, lb, ntoalign)) /* skip alignment */
return packfailed(L, i, arg);
switch (opt) {
case Kint: { /* signed integers */
lua_Integer n = luaL_checkinteger(L, arg);
if (size < SZINT) { /* need overflow check? */
lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
}
if (!packint(&mem, &i, lb, (lua_Unsigned)n, h.islittle, size, (n < 0)))
return packfailed(L, i, arg);
break;
}
case Kuint: { /* unsigned integers */
lua_Integer n = luaL_checkinteger(L, arg);
if (size < SZINT) /* need overflow check? */
luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
arg, "unsigned overflow");
if (!packint(&mem, &i, lb, (lua_Unsigned)n, h.islittle, size, 0))
return packfailed(L, i, arg);
break;
}
#ifndef _KERNEL
case Kfloat: { /* floating-point options */
volatile Ftypes u;
lua_Number n;
char *data = getbytes(&mem, &i, lb, size);
if (!data) return packfailed(L, i, arg);
n = luaL_checknumber(L, arg); /* get argument */
if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
else if (size == sizeof(u.d)) u.d = (double)n;
else u.n = n;
/* move 'u' to final result, correcting endianness if needed */
copywithendian(data, u.buff, size, h.islittle);
break;
}
#endif /* _KERNEL */
case Kchar: { /* fixed-size string */
size_t len;
const char *s = luamem_checkstring(L, arg, &len);
luaL_argcheck(L, len == (size_t)size, arg, "wrong length");
if (!packstream(&mem, &i, lb, s, size))
return packfailed(L, i, arg);
break;
}
case Kstring: { /* strings with length count */
size_t len;
const char *s = luamem_checkstring(L, arg, &len);
luaL_argcheck(L, size >= (int)sizeof(size_t) ||
len < ((size_t)1 << (size * NB)),
arg, "string length does not fit in given size");
if (!packint(&mem, &i, lb, (lua_Unsigned)len, h.islittle, size, 0) || /* pack length */
!packstream(&mem, &i, lb, s, len))
return packfailed(L, i, arg);
break;
}
case Kzstr: { /* zero-terminated string */
size_t len;
const char *s = luamem_checkstring(L, arg, &len);
luaL_argcheck(L, memchr(s, '\0', len) == NULL, arg,
"string contains zeros");
if (!packstream(&mem, &i, lb, s, len) || !packchar(&mem, &i, lb, '\0'))
return packfailed(L, i, arg);
break;
}
case Kpadding: {
if (!getbytes(&mem, &i, lb, 1))
return packfailed(L, i, arg);
/* go through */
}
case Kpaddalign: case Knop:
arg--; /* undo increment */
break;
}
}
lua_pushboolean(L, 1);
lua_pushinteger(L, i+1);
return 2;
}
/*
** Unpack an integer with 'size' bytes and 'islittle' endianness.
** If size is smaller than the size of a Lua integer and integer
** is signed, must do sign extension (propagating the sign to the
** higher bits); if size is larger than the size of a Lua integer,
** it must check the unread bytes to see whether they do not cause an
** overflow.
*/
static lua_Integer unpackint (lua_State *L, const char *str,
int islittle, int size, int issigned) {
lua_Unsigned res = 0;
int i;
int limit = (size <= SZINT) ? size : SZINT;
for (i = limit - 1; i >= 0; i--) {
res <<= NB;
res |= (lua_Unsigned)uchar(str[islittle ? i : size - 1 - i]);
}
if (size < SZINT) { /* real size smaller than lua_Integer? */
if (issigned) { /* needs sign extension? */
lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
res = ((res ^ mask) - mask); /* do sign extension */
}
}
else if (size > SZINT) { /* must check unread bytes */
int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
for (i = limit; i < size; i++) {
if (uchar(str[islittle ? i : size - 1 - i]) != mask)
luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
}
}
return (lua_Integer)res;
}
static int mem_unpack (lua_State *L) {
Header h;
size_t ld;
const char *data = luamem_checkmemory(L, 1, &ld);
const char *fmt = luaL_checkstring(L, 2);
size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1;
int n = 0; /* number of results */
luaL_argcheck(L, pos <= ld, 3, "initial position out of bounds");
initheader(L, &h);
while (*fmt != '\0') {
int size, ntoalign;
KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld)
luaL_argerror(L, 1, "data too short");
pos += ntoalign; /* skip alignment */
/* stack space for item + next position */
luaL_checkstack(L, 1, "too many results");
n++;
switch (opt) {
case Kint:
case Kuint: {
lua_Integer res = unpackint(L, data + pos, h.islittle, size,
(opt == Kint));
lua_pushinteger(L, res);
break;
}
#ifndef _KERNEL
case Kfloat: {
volatile Ftypes u;
lua_Number num;
copywithendian(u.buff, data + pos, size, h.islittle);
if (size == sizeof(u.f)) num = (lua_Number)u.f;
else if (size == sizeof(u.d)) num = (lua_Number)u.d;
else num = u.n;
lua_pushnumber(L, num);
break;
}
#endif /* _KERNEL */
case Kchar: {
lua_pushlstring(L, data + pos, size);
break;
}
case Kstring: {
size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short");
lua_pushlstring(L, data + pos + size, len);
pos += len; /* skip string */
break;
}
case Kzstr: {
size_t len;
const char *z = (const char *)memchr(data + pos, '\0', ld - pos);
luaL_argcheck(L, z, 2, "data string too short");
len = (size_t)(z - data - pos);
lua_pushlstring(L, data + pos, len);
pos += len + 1; /* skip string plus final '\0' */
break;
}
case Kpaddalign: case Kpadding: case Knop:
n--; /* undo increment */
break;
}
pos += size;
}
lua_pushinteger(L, pos + 1); /* next position */
return n + 1;
}
/* }====================================================== */