forked from starwing/lpath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lpath.c
2010 lines (1822 loc) · 60.1 KB
/
lpath.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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef __cplusplus
# define LP_NS_BEGIN extern "C" {
# define LP_NS_END }
#else
# define LP_NS_BEGIN
# define LP_NS_END
#endif
LP_NS_BEGIN
#define LUA_LIB
#include <lua.h>
#include <time.h>
#include <lauxlib.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#if LUA_VERSION_NUM >= 503
# define lua53_rawgetp lua_rawgetp
#elif LUA_VERSION_NUM == 502
static int lua53_rawgetp(lua_State *L, int idx, const void *p)
{ lua_rawgetp(L, idx, p); return lua_type(L, -1); }
#else
# define lua_rawlen lua_objlen
# define luaL_newlib(L,libs) luaL_register(L, lua_tostring(L, 1), libs);
static int lua53_rawgetp(lua_State *L, int idx, const void *p)
{ lua_pushlightuserdata(L, (void*)p); lua_rawget(L, idx); return lua_type(L, -1); }
static int lua_rawsetp(lua_State *L, int idx, const void *p)
{ lua_pushlightuserdata(L, (void*)p); lua_insert(L, -2); lua_rawset(L, idx); }
#endif
#ifndef LUAMOD_API
# define LUAMOD_API LUALIB_API
#endif
#define LP_VERSION "path 0.2"
#if _WIN32
# define LP_DIRSEP "\\"
# define LP_ALTSEP "/"
# define LP_EXTSEP "."
# define LP_CURDIR "."
# define LP_PARDIR ".."
# define LP_PATHSEP ";"
# define LP_DEVNULL "nul"
#else
# define LP_DIRSEP "/"
# define LP_ALTSEP "/"
# define LP_EXTSEP "."
# define LP_CURDIR "."
# define LP_PARDIR ".."
# define LP_PATHSEP ":"
# define LP_DEVNULL "/dev/null"
#endif
typedef struct lp_State lp_State;
typedef struct lp_DirData lp_DirData;
typedef int lp_WalkHandler(lp_State *S, void *ud, const char *s, int state);
#define LP_WALKIN 0
#define LP_WALKOUT 1
#define LP_WALKFILE 2
#define LP_MAX_COMPCOUNT 255
#define LP_MAX_TMPNUM 1000000
#define LP_BUFFERSIZE 4096
#define LP_MAX_SIZET ((~(size_t)0)-100)
#define LP_STATE_KEY ((void*)(ptrdiff_t)0x9A76B0FF)
#define LP_DIRDATA "lpath.Dir Context"
#define lp_returnself(L) do { lua_settop((L), 1); return 1; } while (0)
struct lp_State {
lua_State *L;
/* path buffer data */
char *ptr;
size_t size;
size_t capacity;
/* code page */
int current_cp;
};
static int lpL_delstate(lua_State *L) {
lp_State *S = (lp_State*)lua_touserdata(L, 1);
if (S != NULL) {
free(S->ptr);
memset(S, 0, sizeof(lp_State));
}
return 0;
}
static lp_State *lp_getstate(lua_State *L) {
lp_State *S;
if (lua53_rawgetp(L, LUA_REGISTRYINDEX, LP_STATE_KEY) == LUA_TUSERDATA)
S = (lp_State*)lua_touserdata(L, -1);
else {
S = (lp_State*)lua_newuserdata(L, sizeof(lp_State));
memset(S, 0, sizeof(lp_State));
lua_createtable(L, 0, 1);
lua_pushcfunction(L, lpL_delstate);
lua_setfield(L, -2, "__gc");
lua_setmetatable(L, -2);
S->ptr = (char*)malloc(LP_BUFFERSIZE);
S->capacity = LP_BUFFERSIZE;
lua_rawsetp(L, LUA_REGISTRYINDEX, LP_STATE_KEY);
}
lua_pop(L, 1);
S->L = L;
S->size = 0;
S->ptr[0] = 0;
return S;
}
/* buffer routines */
#define lp_buffer(S) ((S)->ptr)
#define lp_bufflen(S) ((S)->size)
#define lp_setbuffer(S,n) ((S)->size = (n))
#define lp_addsize(S,sz) ((S)->size += (sz))
#define lp_addstring(S,s) lp_addlstring((S),(s),strlen(s))
static char *lp_prepare(lp_State *S, size_t sz) {
if (sz > S->capacity || S->capacity - sz < S->size) {
char *ptr;
size_t expect = S->size + sz;
size_t newsize = LP_BUFFERSIZE;
while (newsize < expect && newsize < LP_MAX_SIZET)
newsize += newsize >> 1;
if (newsize < expect || (ptr = (char*)realloc(S->ptr, newsize)) == NULL) {
luaL_error(S->L, "lpath: out of memory");
return NULL;
}
S->ptr = ptr;
S->capacity = newsize;
}
return &S->ptr[S->size];
}
static char *lp_prepbuffsize(lp_State *S, size_t sz) {
char *ptr = lp_prepare(S, sz);
if (ptr == NULL) luaL_error(S->L, "path buffer out of memory");
return ptr;
}
static char *lp_prepbuffupdate(lp_State *S, size_t sz, void *ps) {
char *p = ps != NULL ? *(char**)ps : NULL;
char *ptr = S->ptr;
char *newptr = lp_prepbuffsize(S, sz);
if (ps != NULL && (p == NULL || (p >= S->ptr && p < S->ptr + S->size)))
*(char**)ps = S->ptr + (p == NULL ? 0 : p - ptr);
assert(newptr != NULL);
return newptr;
}
static void lp_addchar(lp_State *S, int ch)
{ *(char*)lp_prepbuffsize(S, 1) = ch; ++S->size; }
static void lp_addlstring(lp_State *S, const void *s, size_t len)
{ memcpy(lp_prepbuffsize(S, len), s, len); S->size += len; }
static int lp_pushresult(lp_State *S)
{ lua_pushlstring(S->L, S->ptr, S->size); return 1; }
/* path algorithms */
#define LP_ALTSEPCHAR (LP_ALTSEP[0])
#define LP_DIRSEPCHAR (LP_DIRSEP[0])
#define LP_EXTSEPCHAR (LP_EXTSEP[0])
#define LP_PATHSEPCHAR (LP_PATHSEP[0])
#define LP_CURDIRLEN (sizeof(LP_CURDIR)-1)
#define LP_PARDIRLEN (sizeof(LP_PARDIR)-1)
#define lp_isdirsep(ch) ((ch) == LP_DIRSEPCHAR || (ch) == LP_ALTSEPCHAR)
#define lp_isdirend(ch) (lp_isdirsep(ch) || ch == '\0')
#define lp_iscurdir(s) (memcmp((s), LP_CURDIR, LP_CURDIRLEN) == 0 && lp_isdirend(s[LP_CURDIRLEN]))
#define lp_ispardir(s) (memcmp((s), LP_PARDIR, LP_PARDIRLEN) == 0 && lp_isdirend(s[LP_PARDIRLEN]))
#define lp_charequal(ch1, ch2) (lp_normchar(ch1) == lp_normchar(ch2))
static const char *lp_nextsep(const char *p) {
while (*p != '\0' && !lp_isdirsep(*p))
++p;
return p;
}
static const char *lp_drivehead(const char *s) {
#ifdef _WIN32
if (lp_isdirsep(s[0]) && lp_isdirsep(s[1])
&& s[2] == '?' && lp_isdirsep(s[3]))
return s + 4;
#endif
return s;
}
static const char *lp_splitdrive(const char *s) {
#ifdef _WIN32
const char *os = s, *split = s, *mp;
retry:
if (lp_isdirsep(s[0]) && lp_isdirsep(s[1]) && !lp_isdirsep(s[2])) {
if (s[2] == '?' && lp_isdirsep(s[3]) && s == os) {
/* \\?\, prefix for long path */
s += 4, split += 4;
goto retry;
}
/* vvvvvvvvvvvvvvvvvvvv drive letter or UNC path
* \\machine\mountpoint\directory\etc\...
* directory ^^^^^^^^^^^^^^^
* a UNC path can't have two slashes in a row
* (after the initial two) */
if (*(mp = lp_nextsep(s + 2)) != '\0' && !lp_isdirend(mp[1]))
split = lp_nextsep(mp + 1);
}
else if (s[1] == ':')
split = s + 2;
return split;
#else
return s;
#endif
}
static const char *lp_splitpath(const char *s) {
const char *p;
s = lp_splitdrive(s);
if (*s == '\0')
return s;
p = s + strlen(s) - 1;
while (s < p && !lp_isdirsep(*p))
--p;
return lp_isdirsep(*p) ? p + 1 : s;
}
static const char *lp_splitext(const char *s) {
const char *e = s + strlen(s) - 1, *p = e;
while (s < p && *p != LP_EXTSEPCHAR && !lp_isdirsep(*p))
--p;
return *p == LP_EXTSEPCHAR ? p : e + 1;
}
static int lp_isabs(lua_State *L, const char *s) {
const char *p = lp_splitdrive(s);
lua_pushboolean(L, lp_isdirsep(*p));
return 1;
}
static int lp_normchar(int ch) {
if (lp_isdirsep(ch))
return LP_DIRSEPCHAR;
#ifdef _WIN32
if (ch >= 'a' && ch <='z')
return ch + 'A' - 'a';
#endif
return ch;
}
static int lp_driveequal(const char **pd1, const char **pd2) {
const char *d1 = lp_drivehead(*pd1);
const char *d2 = lp_drivehead(*pd2);
const char *p1 = lp_splitdrive(d1);
const char *p2 = lp_splitdrive(d2);
size_t l1 = p1 - d1, l2 = p2 - d2;
*pd1 = p1, *pd2 = p2;
if (l2 == 0) return 1;
else if (l1 != l2) return 0;
while (d1 < p1 && d2 < p2 && lp_charequal(*d1, *d2))
++d1, ++d2;
return d1 == p1;
}
static int lp_normpath(lua_State *L, const char *s) {
lp_State *S = lp_getstate(L);
const char *path = lp_splitdrive(s);
int isabs = lp_isdirsep(*path);
size_t top = 0, pos[LP_MAX_COMPCOUNT];
while (s < path)
lp_addchar(S, lp_normchar(*s++));
if (isabs) lp_addchar(S, LP_DIRSEPCHAR);
pos[top++] = lp_bufflen(S) + isabs;
while (*s != '\0') {
const char *e;
while (lp_isdirsep(*s)) ++s;
if (lp_iscurdir(s))
s += LP_CURDIRLEN;
else if (lp_ispardir(s)) {
s += LP_PARDIRLEN;
if (top > 1)
lp_setbuffer(S, pos[--top]);
else if (isabs)
lp_setbuffer(S, pos[top++]);
else {
lp_addlstring(S, LP_PARDIR, LP_PARDIRLEN);
lp_addchar(S, LP_DIRSEPCHAR);
}
}
else if (*(e = lp_nextsep(s)) == '\0') {
lp_addstring(S, s);
break;
}
else if (top >= LP_MAX_COMPCOUNT) {
lua_pushnil(S->L);
lua_pushstring(S->L, "path too complicate");
return -2;
}
else {
pos[top++] = lp_bufflen(S);
lp_addlstring(S, s, e-s);
lp_addchar(S, LP_DIRSEPCHAR);
s = e + 1;
}
}
if (lp_bufflen(S) == 0)
lua_pushstring(L, LP_CURDIR LP_DIRSEP);
else
lp_pushresult(S);
return 1;
}
static int lp_relpath(lua_State *L, const char *fn, const char *path) {
lp_State *S;
int count_dot2 = 0;
const char *f, *p, *d = fn;
if (!lp_driveequal(&fn, &path)) {
lua_pushstring(L, d);
return 1;
}
f = fn, p = path;
while (*f != '\0' && *p != '\0' && lp_charequal(*f, *p))
++f, ++p;
if (*f == '\0' && *p == '\0') {
lua_pushstring(L, LP_CURDIR LP_DIRSEP);
return 1;
}
while (fn < f && !lp_isdirsep(*f))
--f, --p;
if (path == p && !lp_isdirsep(*p))
++count_dot2;
for (; *p != '\0'; ++p)
if (lp_isdirsep(*p))
++count_dot2;
if (path < p && lp_isdirsep(p[-1]))
--count_dot2;
S = lp_getstate(L);
lp_addlstring(S, d, lp_splitdrive(d) - d);
while (count_dot2--)
lp_addstring(S, LP_PARDIR LP_DIRSEP);
lp_addstring(S, f == fn && !lp_isdirsep(*f) ? f : f + 1);
return lp_pushresult(S);
}
static int lpL_joinpath(lua_State *L) {
int i, top = lua_gettop(L);
lp_State *S = lp_getstate(L);
for (i = 1; i <= top; ++i) {
const char *s = lp_buffer(S);
const char *rd = lp_drivehead(luaL_checkstring(L, i));
const char *d = rd;
if (!lp_driveequal(&s, &d) || lp_isdirsep(d[0]))
lp_setbuffer(S, 0);
lp_addstring(S, rd);
if (d[0] != '\0' && i != top)
lp_addchar(S, LP_DIRSEPCHAR);
}
lua_settop(L, 0);
return lp_pushresult(S);
}
/* system specfied utils */
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#define LP_PLATFORM "windows"
#define lp_pusherror(L, t, f) lp_pusherrmsg((L), GetLastError(), (t), (f))
static int lp_pusherrmsg(lua_State *L, DWORD err, const char *title, const char *fn);
static char *lp_addmultibyte(lp_State *S, LPCWSTR ws) {
int cp = S->current_cp;
int wc = (int)wcslen(ws = ws ? ws : (WCHAR*)lp_buffer(S)), size = (wc+1)*3;
char *s = lp_prepbuffupdate(S, size, (void*)&ws);
int bc = WideCharToMultiByte(cp, 0, ws, wc+1, s, size, NULL, NULL);
if (bc > size) {
s = lp_prepbuffupdate(S, size = bc+1, (void*)ws);
bc = WideCharToMultiByte(cp, 0, ws, wc+1, s, size, NULL, NULL);
}
if (bc == 0) {
lp_pusherror(S->L, "multibyte", NULL);
lua_error(S->L);
}
lp_addsize(S, bc);
return s;
}
static WCHAR *lp_addlwidechar(lp_State *S, LPCSTR s, int bc) {
int cp = S->current_cp;
int size = (bc+1)*sizeof(WCHAR);
WCHAR *ws = (WCHAR*)lp_prepbuffupdate(S, size, (void*)&s);
int wc = MultiByteToWideChar(cp, 0, s, bc+1, ws, size);
if (wc > bc) {
ws = (WCHAR*)lp_prepbuffupdate(S, size = (wc+1)*sizeof(WCHAR), (void*)&s);
wc = MultiByteToWideChar(cp, 0, s, bc+1, ws, size);
}
if (wc == 0) {
lp_pusherror(S->L, "unicode", NULL);
lua_error(S->L);
}
lp_addsize(S, wc*sizeof(WCHAR));
return ws;
}
static WCHAR *lp_addwidechar(lp_State *S, LPCSTR s) {
int bc = (int)strlen(s = (s ? s : lp_buffer(S)));
return lp_addlwidechar(S, s, bc);
}
static WCHAR *lp_addwidepath(lp_State *S, LPCSTR s) {
int top, bc = (int)strlen(s = (s ? s : lp_buffer(S)));
if (bc < MAX_PATH) return lp_addlwidechar(S, s, bc);
top = (int)lp_bufflen(S);
lp_addlstring(S, L"\\\\?\\", 4*sizeof(WCHAR));
lp_addwidechar(S, s);
return (WCHAR*)((char*)lp_buffer(S) + top);
}
static const char *lp_win32error(lua_State *L, DWORD errnum) {
lp_State *S = lp_getstate(L);
const char *ret = NULL;
WCHAR *msg = NULL;
DWORD len = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
errnum,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPWSTR)&msg,
0, NULL);
if (len == 0)
ret = "get system error message error";
if ((ret = lp_prepare(S, len*3)) == NULL)
ret = "error message out of memory";
else {
int bc = WideCharToMultiByte(S->current_cp, 0, msg, len,
(char*)ret, len*3, NULL, NULL);
LocalFree(msg);
if (bc > (int)len*3)
ret = "error message too large";
else if (bc == 0)
ret = "mutibyte: format error message error";
else {
lp_addsize(S, bc);
lp_addchar(S, '\0');
}
}
return ret;
}
static int lp_pusherrmsg(lua_State *L, DWORD err, const char *title, const char *fn) {
const char *msg = lp_win32error(L, err);
lua_pushnil(L);
if (title && fn)
lua_pushfstring(L, "%s:%s:(errno=%d): %s", title, fn, err, msg);
else if (title || fn)
lua_pushfstring(L, "%s:(errno=%d): %s", title ? title : fn, err, msg);
else
lua_pushfstring(L, "lpath:(errno=%d): %s", err, msg);
return -2;
}
static int lpL_ansi(lua_State *L) {
lp_State *S = lp_getstate(L);
int cp = S->current_cp;
const char *utf8;
switch (lua_type(L, 1)) {
case LUA_TNONE:
case LUA_TNIL:
case LUA_TNUMBER:
S->current_cp = (UINT)lua_tonumber(L, 1);
return 0;
case LUA_TSTRING:
utf8 = lua_tostring(L, 1);
S->current_cp = CP_UTF8;
lp_addwidechar(S, utf8);
S->current_cp = cp;
lua_pushstring(L, lp_addmultibyte(S, NULL));
return 1;
default:
lua_pushfstring(L, "number/string expected, got %s",
luaL_typename(L, 1));
return luaL_argerror(L, 1, lua_tostring(L, -1));
}
}
static int lpL_utf8(lua_State *L) {
lp_State *S = lp_getstate(L);
int cp = S->current_cp;
const char *ansi;
switch (lua_type(L, 1)) {
case LUA_TNONE:
case LUA_TNIL:
case LUA_TNUMBER:
S->current_cp = (UINT)lua_tonumber(L, 1);
return 0;
case LUA_TSTRING:
ansi = lua_tostring(L, 1);
lp_addwidechar(S, ansi);
S->current_cp = CP_UTF8;
lua_pushstring(L, lp_addmultibyte(S, NULL));
S->current_cp = cp;
return 1;
default:
lua_pushfstring(L, "number/string expected, got %s",
luaL_typename(L, 1));
return luaL_argerror(L, 1, lua_tostring(L, -1));
}
return 0;
}
/* misc utils */
static void lp_pushuint64(lua_State *L, ULONGLONG ull) {
if (sizeof(lua_Integer) >= 8)
lua_pushinteger(L, (lua_Integer)ull);
else
lua_pushnumber(L, (lua_Number)ull);
}
static int lp_optftime(lua_State *L, int idx, PFILETIME pft) {
ULARGE_INTEGER ln;
if (lua_isnoneornil(L, idx))
return 0;
if (sizeof(lua_Integer) >= 8)
ln.QuadPart = (ULONGLONG)luaL_checkinteger(L, idx);
else
ln.QuadPart = (ULONGLONG)luaL_checknumber(L, idx);
pft->dwLowDateTime = ln.LowPart;
pft->dwHighDateTime = ln.HighPart;
return 1;
}
static void lp_pushftime(lua_State *L, PFILETIME pft) {
ULARGE_INTEGER ln;
ln.LowPart = pft->dwLowDateTime;
ln.HighPart = pft->dwHighDateTime;
lp_pushuint64(L, ln.QuadPart);
}
static int lpL_setenv(lua_State *L) {
const char *name = luaL_checkstring(L, 1);
const char *value = luaL_optstring(L, 2, NULL);
lp_State *S = lp_getstate(L);
WCHAR *wvalue;
lp_addwidechar(S, name);
wvalue = value ? lp_addwidechar(S, value) : NULL;
if (!SetEnvironmentVariableW((WCHAR*)lp_buffer(S), wvalue))
return -lp_pusherror(L, "setenv", NULL);
lua_settop(L, 2);
return 1;
}
static int lpL_getenv(lua_State *L) {
lp_State *S = lp_getstate(L);
WCHAR *ret, *ws = lp_addwidechar(S, luaL_checkstring(L, 1));
DWORD wc;
ret = (WCHAR*)lp_prepbuffupdate(S, MAX_PATH*sizeof(WCHAR), (void*)&ws);
wc = GetEnvironmentVariableW(ws, ret, MAX_PATH);
if (wc >= MAX_PATH) {
ret = (LPWSTR)lp_prepbuffupdate(S, wc*sizeof(WCHAR), (void*)&ws);
wc = GetEnvironmentVariableW(ws, ret, wc);
}
if (wc == 0)
return -lp_pusherror(S->L, "getenv", NULL);
lp_addsize(S, (wc+1)*sizeof(WCHAR));
lua_pushstring(L, lp_addmultibyte(S, ret));
return 1;
}
static int lp_expandvars(lua_State *L, const char *s) {
lp_State *S = lp_getstate(L);
WCHAR *ret, *ws = lp_addwidechar(S, s);
DWORD wc;
ret = (WCHAR*)lp_prepbuffupdate(S, MAX_PATH*sizeof(WCHAR), (void*)&ws);
wc = ExpandEnvironmentStringsW(ws, ret, MAX_PATH);
if (wc >= MAX_PATH) {
ret = (LPWSTR)lp_prepbuffupdate(S, wc*sizeof(WCHAR), (void*)&ws);
wc = ExpandEnvironmentStringsW(ws, ret, wc);
}
if (wc == 0) return lp_pusherror(L, "expandvars", s);
lp_addsize(S, wc*sizeof(WCHAR));
lua_pushstring(L, lp_addmultibyte(S, ret));
return 1;
}
static int lp_readreg(lp_State *S, HKEY hkey, LPCWSTR key) {
DWORD size = MAX_PATH * sizeof(WCHAR), ret;
WCHAR *wc = (lp_setbuffer(S, 0), (WCHAR*)lp_prepbuffsize(S, size));
while ((ret = RegQueryValueExW(hkey, key, NULL, NULL, (LPBYTE)wc, &size))
!= ERROR_SUCCESS) {
if (ret != ERROR_MORE_DATA) {
lua_pushstring(S->L, lp_addmultibyte(S, key));
return lp_pusherrmsg(S->L, ret, "platform", lua_tostring(S->L, -1));
}
wc = (WCHAR*)lp_prepbuffsize(S, size);
}
lp_addsize(S, size);
lp_addlstring(S, L"", sizeof(WCHAR));
return 0;
}
static int lpL_platform(lua_State *L) {
lp_State *S = lp_getstate(L);
WCHAR *dot, *root = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion";
DWORD major = 0, minor = 0, build, size = sizeof(DWORD);
HKEY hkey;
int ret;
if ((ret = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
root, 0, KEY_QUERY_VALUE, &hkey)) != ERROR_SUCCESS)
return -lp_pusherrmsg(L, ret, "platform", NULL);
if ((ret = lp_readreg(S, hkey, L"CurrentBuildNumber")) < 0)
{ ret = -ret; goto out; }
build = wcstoul((WCHAR*)lp_buffer(S), NULL, 10);
if (RegQueryValueExW(hkey, L"CurrentMajorVersionNumber",
NULL, NULL, (LPBYTE)&major, &size) != ERROR_SUCCESS
|| RegQueryValueExW(hkey, L"CurrentMinorVersionNumber",
NULL, NULL, (LPBYTE)&minor, &size) != ERROR_SUCCESS) {
if ((ret = lp_readreg(S, hkey, L"CurrentVersion")) < 0)
{ ret = -ret; goto out; }
major = wcstoul((WCHAR*)lp_buffer(S), &dot, 10);
if (*dot == L'.') minor = wcstoul(dot + 1, NULL, 10);
}
lua_pushfstring(L, "Windows %d.%d Build %d", major, minor, build);
lua_pushinteger(L, major);
lua_pushinteger(L, minor);
lua_pushinteger(L, build);
ret = 4;
out:RegCloseKey(hkey);
return ret;
}
/* path utils */
typedef DWORD WINAPI LPGETFINALPATHNAMEBYHANDLEW(
HANDLE hFile,
LPWSTR lpszFilePath,
DWORD cchFilePath,
DWORD dwFlags);
static LPGETFINALPATHNAMEBYHANDLEW *pGetFinalPathNameByHandleW;
static int lp_abs(lua_State *L, const char *s) {
lp_State *S = lp_getstate(L);
WCHAR *ws = lp_addwidepath(S, s);
WCHAR *ret = (WCHAR*)lp_prepbuffupdate(S,
MAX_PATH*sizeof(WCHAR), (void*)&ws);
DWORD wc = GetFullPathNameW(ws, MAX_PATH, ret, NULL);
if (wc >= MAX_PATH) {
ret = (WCHAR*)lp_prepbuffupdate(S, wc*sizeof(WCHAR), (void*)&ws);
wc = GetFullPathNameW(ws, wc, ret, NULL);
}
if (wc == 0) return lp_pusherror(L, "abs", s);
lp_addsize(S, (wc+1)*sizeof(WCHAR));
lua_pushstring(L, lp_addmultibyte(S, ret));
return 1;
}
static int lp_solvelink(lua_State *L, const char *s) {
lp_State *S = lp_getstate(L);
WCHAR *ret, *ws = lp_addwidepath(S, s);
HANDLE hFile = CreateFileW(ws, /* file to open */
0, /* open only for handle */
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, /* share for everything */
NULL, /* default security */
OPEN_EXISTING, /* existing file only */
0, /* no file attributes */
NULL); /* no attr. template */
DWORD wc;
if(hFile == INVALID_HANDLE_VALUE)
return lp_pusherror(L, "open", s);
lp_setbuffer(S, 0);
ret = (LPWSTR)lp_prepbuffsize(S, MAX_PATH*sizeof(WCHAR));
wc = pGetFinalPathNameByHandleW(hFile, ret, MAX_PATH, 0);
if (wc >= MAX_PATH) {
ret = (LPWSTR)lp_prepbuffsize(S, wc*sizeof(WCHAR));
wc = pGetFinalPathNameByHandleW(hFile, ret, wc, 0);
}
CloseHandle(hFile);
if (wc == 0) return lp_pusherror(L, "realpath", s);
lp_addsize(S, (wc + 1) * sizeof(WCHAR));
if (wc > MAX_PATH + 4)
lua_pushstring(L, lp_addmultibyte(S, ret));
else
lua_pushstring(L, lp_addmultibyte(S, ret+4));
return 1;
}
static int lp_realpath(lua_State *L, const char *s) {
if (!pGetFinalPathNameByHandleW) {
HMODULE hModule = GetModuleHandleA("KERNEL32.dll");
if (hModule != NULL)
pGetFinalPathNameByHandleW = (LPGETFINALPATHNAMEBYHANDLEW*)
GetProcAddress(hModule, "GetFinalPathNameByHandleW");
}
if (pGetFinalPathNameByHandleW == NULL)
return lp_abs(L, s);
return lp_solvelink(L, s);
}
static int lp_type(lua_State *L, const char *s) {
LPCWSTR ws = lp_addwidepath(lp_getstate(L), s);
DWORD attr = GetFileAttributesW(ws);
int isdir, islink;
if (attr == INVALID_FILE_ATTRIBUTES)
return lp_pusherror(L, "type", s);
isdir = attr & FILE_ATTRIBUTE_DIRECTORY;
islink = attr & FILE_ATTRIBUTE_REPARSE_POINT;
lua_pushstring(L, islink ? "link" :
isdir ? "dir" : "file");
return 1;
}
/* dir utils */
struct lp_DirData {
lp_State *S;
HANDLE hFile;
WIN32_FIND_DATAW wfd;
DWORD err;
};
static int lpL_deldir(lua_State *L) {
lp_DirData *d = (lp_DirData*)luaL_checkudata(L, 1, LP_DIRDATA);
if (d->hFile != INVALID_HANDLE_VALUE) {
FindClose(d->hFile);
d->hFile = INVALID_HANDLE_VALUE;
}
return 0;
}
static int lpL_diriter(lua_State *L) {
lp_DirData *d = (lp_DirData*)lua_touserdata(L, 1);
const char *fn;
retry:
if (d == NULL || d->err == ERROR_NO_MORE_FILES)
return 0;
else if (d->err != NO_ERROR) {
lp_pusherrmsg(L, d->err, "dir.iter", NULL);
return lua_error(L);
}
fn = lp_addmultibyte(d->S, d->wfd.cFileName);
while (lp_iscurdir(fn) || lp_ispardir(fn)) {
if (!FindNextFileW(d->hFile, &d->wfd))
{ d->err = GetLastError(); goto retry; }
fn = lp_addmultibyte(d->S, d->wfd.cFileName);
}
lua_pushstring(L, fn);
lua_pushstring(L, d->wfd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY?"dir":"file");
lp_pushuint64(L, ((ULONGLONG)d->wfd.nFileSizeHigh<<32)|d->wfd.nFileSizeLow);
lp_pushftime(L, &d->wfd.ftCreationTime);
lp_pushftime(L, &d->wfd.ftLastWriteTime);
lp_pushftime(L, &d->wfd.ftLastAccessTime);
if (!FindNextFileW(d->hFile, &d->wfd))
d->err = GetLastError();
return 6;
}
static int lp_dir(lua_State *L, const char *s) {
lp_State *S = lp_getstate(L);
lp_DirData *d;
lp_addwidepath(S, s);
lp_setbuffer(S, lp_bufflen(S)-sizeof(WCHAR));
lp_addlstring(S, L"\\*", 3*sizeof(WCHAR));
d = (lp_DirData*)lua_newuserdata(L, sizeof(lp_DirData));
d->hFile = FindFirstFileW((WCHAR*)lp_buffer(S), &d->wfd);
if (d->hFile == INVALID_HANDLE_VALUE) {
lp_pusherror(L, "dir", s);
lua_error(L);
}
if (luaL_newmetatable(L, LP_DIRDATA)) {
lua_pushcfunction(L, lpL_deldir);
lua_setfield(L, -2, "__gc");
}
d->S = S;
d->err = NO_ERROR;
lua_setmetatable(L, -2);
lua_pushcfunction(L, lpL_diriter);
lua_insert(L, -2);
return 2;
}
static int lp_walkpath(lua_State *L, const char *s, lp_WalkHandler *h, void *ud) {
lp_State *S = lp_getstate(L);
DWORD err, attr = GetFileAttributesW(lp_addwidechar(S, s));
WIN32_FIND_DATAW wfd;
int ret = 0, top = 0;
size_t pos[LP_MAX_COMPCOUNT];
HANDLE hFile[LP_MAX_COMPCOUNT];
WCHAR *path;
if (*s != '\0' && attr == INVALID_FILE_ATTRIBUTES)
return 0;
if (*s != '\0' && (attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
return h(S, ud, s, LP_WALKFILE);
wfd.cFileName[0] = 0;
wfd.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
if ((lp_bufflen(S) -= sizeof(WCHAR)) > 0) {
path = (WCHAR*)lp_buffer(S) + lp_bufflen(S)/sizeof(WCHAR);
while (--path, lp_isdirsep(*path)) lp_bufflen(S) -= sizeof(WCHAR);
}
pos[0] = lp_bufflen(S);
do {
size_t len = wcslen(wfd.cFileName)*sizeof(WCHAR);
lp_setbuffer(S, pos[top]);
lp_addlstring(S, wfd.cFileName, len + sizeof(WCHAR));
if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
ret = h(S, ud, lp_addmultibyte(S, NULL), LP_WALKFILE);
if (ret < 0) break;
}
else if (top < LP_MAX_COMPCOUNT-1
&& wcscmp(wfd.cFileName, L".")
&& wcscmp(wfd.cFileName, L".."))
{
ret = h(S, ud, lp_addmultibyte(S, NULL), LP_WALKIN);
if (ret < 0) break;
if (ret != 0) {
lp_setbuffer(S, pos[top] + len);
lp_addlstring(S, L"\\*", 3*sizeof(WCHAR));
hFile[++top] = FindFirstFileW((WCHAR*)lp_buffer(S), &wfd);
if (hFile[top] == INVALID_HANDLE_VALUE) {
err = GetLastError();
lua_pushstring(L, lp_addmultibyte(S, NULL));
ret = lp_pusherrmsg(L, err, "findfile1", lua_tostring(L, -1));
break;
}
pos[top] = lp_bufflen(S) - 2*sizeof(WCHAR);
continue;
}
}
for (; top != 0 && !FindNextFileW(hFile[top], &wfd); --top) {
if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
lua_pushstring(L, lp_addmultibyte(S, NULL));
ret = lp_pusherrmsg(L, err, "findfile2", lua_tostring(L, -1));
goto out;
}
FindClose(hFile[top]);
lp_setbuffer(S, pos[top]);
lp_addlstring(S, L"", sizeof(WCHAR));
ret = h(S, ud, lp_addmultibyte(S, NULL), LP_WALKOUT);
if (ret < 0) goto out;
}
} while (top);
out:while (top) FindClose(hFile[top--]);
return ret;
}
static int lpL_getcwd(lua_State *L) {
lp_State *S = lp_getstate(L);
WCHAR *ret = (WCHAR*)lp_prepbuffsize(S, MAX_PATH*sizeof(WCHAR));
DWORD wc = GetCurrentDirectoryW(MAX_PATH, ret);
if (wc >= MAX_PATH) {
ret = (WCHAR*)lp_prepbuffsize(S, wc*sizeof(WCHAR));
wc = GetCurrentDirectoryW(wc, ret);
}
if (wc == 0) return lp_pusherror(L, "getcwd", NULL);
lp_addsize(S, (wc + 1) * sizeof(WCHAR));
lua_pushstring(L, lp_addmultibyte(S, ret));
return 1;
}
static int lpL_binpath(lua_State *L) {
lp_State *S = lp_getstate(L);
WCHAR *ret = (WCHAR*)lp_prepbuffsize(S, MAX_PATH*sizeof(WCHAR));
DWORD wc = GetModuleFileNameW(NULL, ret, MAX_PATH);
if (wc > MAX_PATH) {
ret = (WCHAR*)lp_prepbuffsize(S, wc*sizeof(WCHAR));
wc = GetModuleFileNameW(NULL, ret, wc);
}
if (wc == 0) return lp_pusherror(L, "binpath", NULL);
lp_addsize(S, (wc + 1) * sizeof(WCHAR));
lua_pushstring(L, lp_addmultibyte(S, ret));
return 1;
}
static int lpL_tmpdir(lua_State* L) {
size_t len;
const char *s, *prefix = luaL_optstring(L, 1, "lua_");
lp_State *S = lp_getstate(L);
WCHAR tmpdir[MAX_PATH + 1];
if (GetTempPathW(MAX_PATH + 1, tmpdir) == 0)
return -lp_pusherror(L, "tmpdir", NULL);
lua_pushstring(L, lp_addmultibyte(S, tmpdir));
s = lua_tolstring(L, -1, &len);
srand(((int)(ptrdiff_t)&L) ^ clock());
do {
int magic = ((unsigned)rand()<<16|rand()) % LP_MAX_TMPNUM;
const char *fmt = lp_isdirsep(s[len-1]) ?
"%s%s%d" LP_DIRSEP : "%s" LP_DIRSEP "%s%d" LP_DIRSEP;
lua_settop(L, 3);
lua_pushfstring(L, fmt, s, prefix, magic);
lp_setbuffer(S, 0);
} while (GetFileAttributesW(lp_addwidepath(S, lua_tostring(L, -1))) !=
INVALID_FILE_ATTRIBUTES);
if (!CreateDirectoryW(lp_addwidepath(S, lua_tostring(L, -1)), NULL))
return -lp_pusherror(L, "tmpdir", lp_addmultibyte(S, NULL));
return 1;
}
static int lp_chdir(lua_State *L, const char *s) {
LPCWSTR ws = lp_addwidepath(lp_getstate(L), s);
if (!SetCurrentDirectoryW(ws))
return lp_pusherror(L, "chdir", s);
return 0;
}
static int lp_mkdir(lua_State *L, const char *s) {
LPCWSTR ws = lp_addwidepath(lp_getstate(L), s);
if (!CreateDirectoryW(ws, NULL)) {
DWORD err = GetLastError();
if (err == ERROR_ALREADY_EXISTS)
lp_returnself(L);
return lp_pusherrmsg(L, err, "mkdir", s);
}
return 1;
}
static int lp_rmdir(lua_State *L, const char *s) {
LPCWSTR ws = lp_addwidepath(lp_getstate(L), s);
if (!RemoveDirectoryW(ws))
return lp_pusherror(L, "rmdir", s);
return 0;
}
static int lp_makedirs(lua_State *L, const char *s) {
lp_State *S = lp_getstate(L);
WCHAR *ws, *cur, old;
DWORD err;
int rets;
if ((rets = lp_normpath(L, s)) < 0) return rets;
lp_setbuffer(S, 0);
ws = lp_addwidepath(S, s = lua_tostring(L, -1));
cur = ws + (lp_splitdrive(s) - s);
if (lp_isdirsep(*cur)) ++cur;
for (old = *cur; old != 0; *cur = old, ++cur) {
while (*cur != 0 && !lp_isdirsep(*cur))
cur++;
old = *cur, *cur = 0;
if (CreateDirectoryW(ws, NULL)
|| (err = GetLastError()) == ERROR_ALREADY_EXISTS)
continue;
lua_pushstring(L, lp_addmultibyte(S, ws));
return lp_pusherrmsg(L, err, "makedirs", lua_tostring(L, -1));
}
return 0;
}
static int rmdir_walker(lp_State *S, void *ud, const char *s, int state) {
LPCWSTR ws = lp_addwidechar(S, s);
(void)ud;
if (state == LP_WALKIN)
return 1;
if (state == LP_WALKFILE && !DeleteFileW(ws))
return lp_pusherror(S->L, "removedirs", s);
else if (state == LP_WALKOUT && !RemoveDirectoryW(ws))
return lp_pusherror(S->L, "removedirs", s);
return 0;
}
static int unlock_walker(lp_State *S, void *ud, const char *s, int state) {
LPCWSTR ws = lp_addwidechar(S, s);
(void)ud;
if (state == LP_WALKIN)
return 1;
if (state == LP_WALKFILE
&& !SetFileAttributesW(ws,
GetFileAttributesW(ws) & ~FILE_ATTRIBUTE_READONLY))
return lp_pusherror(S->L, "unlock", s);
return 0;
}
/* file utils */
static int lp_exists(lua_State *L, const char *s) {
LPCWSTR ws = lp_addwidepath(lp_getstate(L), s);
HANDLE hFile = CreateFileW(ws, /* file to open */
FILE_WRITE_ATTRIBUTES, /* open only for handle */
FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, /* share for everything */
NULL, /* default security */
OPEN_EXISTING, /* existing file only */
FILE_FLAG_BACKUP_SEMANTICS, /* open directory also */
NULL); /* no attr. template */
CloseHandle(hFile);