-
Notifications
You must be signed in to change notification settings - Fork 1
/
luajit-0001-add-win32-utf-8-filesystem-functions.patch
855 lines (840 loc) · 24.1 KB
/
luajit-0001-add-win32-utf-8-filesystem-functions.patch
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
From c92ec4586cb91e430aa2c9d7894cf0128a729633 Mon Sep 17 00:00:00 2001
From: shinchiro <shinchiro@users.noreply.github.com>
Date: Tue, 25 Jul 2023 22:53:21 +0800
Subject: [PATCH] Add win32 UTF-8 filesystem functions
Taken from https://github.com/wm4/libinsanity
---
src/Makefile | 2 +-
src/Makefile.dep | 3 +-
src/lib_io.c | 1 +
src/lib_os.c | 1 +
src/lib_package.c | 1 +
src/lj_clib.c | 1 +
src/lj_fs_io.c | 582 +++++++++++++++++++++++++++++++++++++++++
src/lj_fs_io.h | 60 +++++
src/lj_fs_io_replace.h | 50 ++++
src/lj_load.c | 1 +
src/lj_trace.c | 1 +
src/ljamalg.c | 1 +
12 files changed, 702 insertions(+), 2 deletions(-)
create mode 100644 src/lj_fs_io.c
create mode 100644 src/lj_fs_io.h
create mode 100644 src/lj_fs_io_replace.h
diff --git a/src/Makefile b/src/Makefile
index 68a9a7c..26137e4 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -513,7 +513,7 @@ LJCORE_O= lj_assert.o lj_gc.o lj_err.o lj_char.o lj_bc.o lj_obj.o lj_buf.o \
lj_asm.o lj_trace.o lj_gdbjit.o \
lj_ctype.o lj_cdata.o lj_cconv.o lj_ccall.o lj_ccallback.o \
lj_carith.o lj_clib.o lj_cparse.o \
- lj_lib.o lj_alloc.o lib_aux.o \
+ lj_lib.o lj_alloc.o lj_fs_io.o lib_aux.o \
$(LJLIB_O) lib_init.o lj_str_hash.o
ifeq (x64,$(TARGET_LJARCH))
diff --git a/src/Makefile.dep b/src/Makefile.dep
index 400ef8b..5f26250 100644
--- a/src/Makefile.dep
+++ b/src/Makefile.dep
@@ -47,6 +47,7 @@ lib_table.o: lib_table.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
lj_tab.h lj_ff.h lj_ffdef.h lj_lib.h lj_libdef.h
lj_alloc.o: lj_alloc.c lj_def.h lua.h luaconf.h lj_arch.h lj_alloc.h \
lj_prng.h
+lj_fs_io.o: lj_fs_io.c lj_fs_io.h
lj_api.o: lj_api.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h lj_func.h lj_udata.h \
lj_meta.h lj_state.h lj_bc.h lj_frame.h lj_trace.h lj_jit.h lj_ir.h \
@@ -237,7 +238,7 @@ ljamalg.o: ljamalg.c lua.h luaconf.h lauxlib.h lj_assert.c lj_obj.h \
lj_opt_narrow.c lj_opt_dce.c lj_opt_loop.c lj_snap.h lj_opt_split.c \
lj_opt_sink.c lj_mcode.c lj_snap.c lj_record.c lj_record.h lj_ffrecord.h \
lj_crecord.c lj_crecord.h lj_ffrecord.c lj_recdef.h lj_asm.c lj_asm.h \
- lj_emit_*.h lj_asm_*.h lj_trace.c lj_gdbjit.h lj_gdbjit.c lj_alloc.c \
+ lj_emit_*.h lj_asm_*.h lj_trace.c lj_gdbjit.h lj_gdbjit.c lj_alloc.c lj_fs_io.c \
lib_aux.c lib_base.c lj_libdef.h lib_math.c lib_string.c lib_table.c \
lib_io.c lib_os.c lib_package.c lib_debug.c lib_bit.c lib_jit.c \
lib_ffi.c lib_buffer.c lib_init.c
diff --git a/src/lib_io.c b/src/lib_io.c
index c22faa2..3014b06 100644
--- a/src/lib_io.c
+++ b/src/lib_io.c
@@ -25,6 +25,7 @@
#include "lj_strfmt.h"
#include "lj_ff.h"
#include "lj_lib.h"
+#include "lj_fs_io_replace.h"
/* Userdata payload for I/O file. */
typedef struct IOFileUD {
diff --git a/src/lib_os.c b/src/lib_os.c
index 4b4e150..0515579 100644
--- a/src/lib_os.c
+++ b/src/lib_os.c
@@ -22,6 +22,7 @@
#include "lj_buf.h"
#include "lj_str.h"
#include "lj_lib.h"
+#include "lj_fs_io_replace.h"
#if LJ_TARGET_POSIX
#include <unistd.h>
diff --git a/src/lib_package.c b/src/lib_package.c
index 63a9121..70fdc53 100644
--- a/src/lib_package.c
+++ b/src/lib_package.c
@@ -16,6 +16,7 @@
#include "lj_obj.h"
#include "lj_err.h"
#include "lj_lib.h"
+#include "lj_fs_io_replace.h"
/* ------------------------------------------------------------------------ */
diff --git a/src/lj_clib.c b/src/lj_clib.c
index f0ef6ed..8b22824 100644
--- a/src/lj_clib.c
+++ b/src/lj_clib.c
@@ -17,6 +17,7 @@
#include "lj_cdata.h"
#include "lj_clib.h"
#include "lj_strfmt.h"
+#include "lj_fs_io_replace.h"
/* -- OS-specific functions ----------------------------------------------- */
diff --git a/src/lj_fs_io.c b/src/lj_fs_io.c
new file mode 100644
index 0000000..80668b7
--- /dev/null
+++ b/src/lj_fs_io.c
@@ -0,0 +1,582 @@
+// This file is copyrighted.
+
+#define lj_fs_io_c
+#define LUA_CORE
+
+#ifdef __MINGW32__
+
+#include <windows.h>
+
+#include <assert.h>
+#include <direct.h>
+#include <io.h>
+#include <fcntl.h>
+#include <strings.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <errno.h>
+#include <stddef.h>
+
+#include "lj_fs_io.h"
+
+// Like free(), but do not clobber errno and the win32 error state. It is
+// unknown whether MSVCRT's free() clobbers these, but do not take any chances.
+static void free_keep_err(void *ptr)
+{
+ int err = errno;
+ DWORD bill = GetLastError();
+
+ free(ptr);
+
+ errno = err;
+ SetLastError(bill);
+}
+
+static void set_errno_from_lasterror(void)
+{
+ // This just handles the error codes expected from CreateFile at the moment
+ switch (GetLastError()) {
+ case ERROR_FILE_NOT_FOUND:
+ errno = ENOENT;
+ break;
+ case ERROR_SHARING_VIOLATION:
+ case ERROR_ACCESS_DENIED:
+ errno = EACCES;
+ break;
+ case ERROR_FILE_EXISTS:
+ case ERROR_ALREADY_EXISTS:
+ errno = EEXIST;
+ break;
+ case ERROR_PIPE_BUSY:
+ errno = EAGAIN;
+ break;
+ default:
+ errno = EINVAL;
+ break;
+ }
+}
+
+// Returns NULL + errno on failure.
+static wchar_t *lin_utf8_to_winchar(const char *in)
+{
+ int res = MultiByteToWideChar(CP_UTF8, 0, in, -1, NULL, 0);
+ if (res <= 0) {
+ set_errno_from_lasterror();
+ return NULL;
+ }
+ wchar_t *str = malloc(res * sizeof(wchar_t));
+ if (!str) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ if (MultiByteToWideChar(CP_UTF8, 0, in, -1, str, res) <= 0) {
+ set_errno_from_lasterror();
+ return NULL;
+ }
+ return str;
+}
+
+// Returns NULL + errno on failure.
+static char *lin_winchar_to_utf8(const wchar_t *in)
+{
+ int res = WideCharToMultiByte(CP_UTF8, 0, in, -1, NULL, 0, NULL, NULL);
+ if (res <= 0) {
+ set_errno_from_lasterror();
+ return NULL;
+ }
+ char *str = malloc(res);
+ if (!str) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ if (WideCharToMultiByte(CP_UTF8, 0, in, -1, str, res, NULL, NULL) <= 0) {
+ set_errno_from_lasterror();
+ return NULL;
+ }
+ return str;
+}
+
+static time_t filetime_to_unix_time(int64_t wintime)
+{
+ static const int64_t hns_per_second = 10000000ll;
+ static const int64_t win_to_unix_epoch = 11644473600ll;
+ return wintime / hns_per_second - win_to_unix_epoch;
+}
+
+static bool get_file_ids_win8(HANDLE h, lin_dev_t *dev, lin_ino_t *ino)
+{
+ FILE_ID_INFO ii;
+ if (!GetFileInformationByHandleEx(h, FileIdInfo, &ii, sizeof(ii)))
+ return false;
+ *dev = ii.VolumeSerialNumber;
+ // The definition of FILE_ID_128 differs between mingw-w64 and the Windows
+ // SDK, but we can ignore that by just memcpying it. This will also
+ // truncate the file ID on 32-bit Windows, which doesn't support __int128.
+ // 128-bit file IDs are only used for ReFS, so that should be okay.
+ assert(sizeof(*ino) <= sizeof(ii.FileId));
+ memcpy(ino, &ii.FileId, sizeof(*ino));
+ return true;
+}
+
+static bool get_file_ids(HANDLE h, lin_dev_t *dev, lin_ino_t *ino)
+{
+ // GetFileInformationByHandle works on FAT partitions and Windows 7, but
+ // doesn't work in UWP and can produce non-unique IDs on ReFS
+ BY_HANDLE_FILE_INFORMATION bhfi;
+ if (!GetFileInformationByHandle(h, &bhfi))
+ return false;
+ *dev = bhfi.dwVolumeSerialNumber;
+ *ino = ((lin_ino_t)bhfi.nFileIndexHigh << 32) | bhfi.nFileIndexLow;
+ return true;
+}
+
+// Like fstat(), but with a Windows HANDLE
+static int hstat(HANDLE h, struct lin_stat *buf)
+{
+ // Handle special (or unknown) file types first
+ switch (GetFileType(h) & ~FILE_TYPE_REMOTE) {
+ case FILE_TYPE_PIPE:
+ *buf = (struct lin_stat){ .st_nlink = 1, .st_mode = _S_IFIFO | 0644 };
+ return 0;
+ case FILE_TYPE_CHAR: // character device
+ *buf = (struct lin_stat){ .st_nlink = 1, .st_mode = _S_IFCHR | 0644 };
+ return 0;
+ case FILE_TYPE_UNKNOWN:
+ errno = EBADF;
+ return -1;
+ }
+
+ struct lin_stat st = { 0 };
+
+ FILE_BASIC_INFO bi;
+ if (!GetFileInformationByHandleEx(h, FileBasicInfo, &bi, sizeof(bi))) {
+ errno = EBADF;
+ return -1;
+ }
+ st.st_atime = filetime_to_unix_time(bi.LastAccessTime.QuadPart);
+ st.st_mtime = filetime_to_unix_time(bi.LastWriteTime.QuadPart);
+ st.st_ctime = filetime_to_unix_time(bi.ChangeTime.QuadPart);
+
+ FILE_STANDARD_INFO si;
+ if (!GetFileInformationByHandleEx(h, FileStandardInfo, &si, sizeof(si))) {
+ errno = EBADF;
+ return -1;
+ }
+ st.st_nlink = si.NumberOfLinks;
+
+ // Here we pretend Windows has POSIX permissions by pretending all
+ // directories are 755 and regular files are 644
+ if (si.Directory) {
+ st.st_mode |= _S_IFDIR | 0755;
+ } else {
+ st.st_mode |= _S_IFREG | 0644;
+ st.st_size = si.EndOfFile.QuadPart;
+ }
+
+ if (!get_file_ids_win8(h, &st.st_dev, &st.st_ino)) {
+ // Fall back to the Windows 7 method (also used for FAT in Win8)
+ if (!get_file_ids(h, &st.st_dev, &st.st_ino)) {
+ errno = EBADF;
+ return -1;
+ }
+ }
+
+ *buf = st;
+ return 0;
+}
+
+int lin_stat(const char *path, struct lin_stat *buf)
+{
+ wchar_t *wpath = lin_utf8_to_winchar(path);
+ if (!wpath)
+ return -1;
+ HANDLE h = CreateFileW(wpath, FILE_READ_ATTRIBUTES,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
+ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | SECURITY_SQOS_PRESENT |
+ SECURITY_IDENTIFICATION, NULL);
+ free(wpath);
+ if (h == INVALID_HANDLE_VALUE) {
+ set_errno_from_lasterror();
+ return -1;
+ }
+
+ int ret = hstat(h, buf);
+ CloseHandle(h);
+ return ret;
+}
+
+int lin_fstat(int fd, struct lin_stat *buf)
+{
+ HANDLE h = (HANDLE)_get_osfhandle(fd);
+ if (h == INVALID_HANDLE_VALUE) {
+ errno = EBADF;
+ return -1;
+ }
+ // Use our hstat() function rather than MSVCRT's fstat() because ours
+ // supports directories and device/inode numbers.
+ return hstat(h, buf);
+}
+
+int lin_open(const char *filename, int oflag, ...)
+{
+ // Always use all share modes, which is useful for opening files that are
+ // open in other processes, and also more POSIX-like
+ static const DWORD share =
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
+ // Setting FILE_APPEND_DATA and avoiding GENERIC_WRITE/FILE_WRITE_DATA
+ // will make the file handle use atomic append behavior
+ static const DWORD append =
+ FILE_APPEND_DATA | FILE_WRITE_ATTRIBUTES | FILE_WRITE_EA;
+
+ DWORD access = 0;
+ DWORD disposition = 0;
+ DWORD flags = 0;
+
+ switch (oflag & (_O_RDONLY | _O_RDWR | _O_WRONLY | _O_APPEND)) {
+ case _O_RDONLY:
+ access = GENERIC_READ;
+ flags |= FILE_FLAG_BACKUP_SEMANTICS; // For opening directories
+ break;
+ case _O_RDWR:
+ access = GENERIC_READ | GENERIC_WRITE;
+ break;
+ case _O_RDWR | _O_APPEND:
+ case _O_RDONLY | _O_APPEND:
+ access = GENERIC_READ | append;
+ break;
+ case _O_WRONLY:
+ access = GENERIC_WRITE;
+ break;
+ case _O_WRONLY | _O_APPEND:
+ access = append;
+ break;
+ default:
+ errno = EINVAL;
+ return -1;
+ }
+
+ switch (oflag & (_O_CREAT | _O_EXCL | _O_TRUNC)) {
+ case 0:
+ case _O_EXCL: // Like MSVCRT, ignore invalid use of _O_EXCL
+ disposition = OPEN_EXISTING;
+ break;
+ case _O_TRUNC:
+ case _O_TRUNC | _O_EXCL:
+ disposition = TRUNCATE_EXISTING;
+ break;
+ case _O_CREAT:
+ disposition = OPEN_ALWAYS;
+ flags |= FILE_ATTRIBUTE_NORMAL;
+ break;
+ case _O_CREAT | _O_TRUNC:
+ disposition = CREATE_ALWAYS;
+ break;
+ case _O_CREAT | _O_EXCL:
+ case _O_CREAT | _O_EXCL | _O_TRUNC:
+ disposition = CREATE_NEW;
+ flags |= FILE_ATTRIBUTE_NORMAL;
+ break;
+ }
+
+ // Opening a named pipe as a file can allow the pipe server to impersonate
+ // the calling process, which could be a security issue. Set SQOS flags, so
+ // pipe servers can only identify our process, not impersonate it.
+ if (disposition != CREATE_NEW)
+ flags |= SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION;
+
+ // Keep the same semantics for some MSVCRT-specific flags
+ if (oflag & _O_TEMPORARY) {
+ flags |= FILE_FLAG_DELETE_ON_CLOSE;
+ access |= DELETE;
+ }
+ if (oflag & _O_SHORT_LIVED)
+ flags |= FILE_ATTRIBUTE_TEMPORARY;
+ if (oflag & _O_SEQUENTIAL) {
+ flags |= FILE_FLAG_SEQUENTIAL_SCAN;
+ } else if (oflag & _O_RANDOM) {
+ flags |= FILE_FLAG_RANDOM_ACCESS;
+ }
+
+ // Open the Windows file handle
+ wchar_t *wpath = lin_utf8_to_winchar(filename);
+ if (!wpath)
+ return -1;
+ HANDLE h = CreateFileW(wpath, access, share, NULL, disposition, flags, NULL);
+ free(wpath);
+ if (h == INVALID_HANDLE_VALUE) {
+ set_errno_from_lasterror();
+ return -1;
+ }
+
+ // Map the Windows file handle to a CRT file descriptor. Note: MSVCRT only
+ // cares about the following oflags.
+ oflag &= _O_APPEND | _O_RDONLY | _O_RDWR | _O_WRONLY;
+ oflag |= _O_NOINHERIT; // We never create inheritable handles
+ int fd = _open_osfhandle((intptr_t)h, oflag);
+ if (fd < 0) {
+ CloseHandle(h);
+ return -1;
+ }
+
+ return fd;
+}
+
+int lin_creat(const char *filename, int mode)
+{
+ return lin_open(filename, _O_CREAT | _O_WRONLY | _O_TRUNC, mode);
+}
+
+FILE *lin_fopen(const char *filename, const char *mode)
+{
+ if (!mode[0]) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ int rwmode;
+ int oflags = 0;
+ switch (mode[0]) {
+ case 'r':
+ rwmode = _O_RDONLY;
+ break;
+ case 'w':
+ rwmode = _O_WRONLY;
+ oflags |= _O_CREAT | _O_TRUNC;
+ break;
+ case 'a':
+ rwmode = _O_WRONLY;
+ oflags |= _O_CREAT | _O_APPEND;
+ break;
+ default:
+ errno = EINVAL;
+ return NULL;
+ }
+
+ // Parse extra mode flags
+ for (const char *pos = mode + 1; *pos; pos++) {
+ switch (*pos) {
+ case '+': rwmode = _O_RDWR; break;
+ case 'x': oflags |= _O_EXCL; break;
+ // Ignore unknown flags (glibc does too)
+ default: break;
+ }
+ }
+
+ // Open a CRT file descriptor
+ int fd = lin_open(filename, rwmode | oflags);
+ if (fd < 0)
+ return NULL;
+
+ // Add 'b' to the mode so the CRT knows the file is opened in binary mode
+ char bmode[] = { mode[0], 'b', rwmode == _O_RDWR ? '+' : '\0', '\0' };
+ FILE *fp = fdopen(fd, bmode);
+ if (!fp) {
+ close(fd);
+ return NULL;
+ }
+
+ return fp;
+}
+
+// Windows' MAX_PATH/PATH_MAX/FILENAME_MAX is fixed to 260, but this limit
+// applies to unicode paths encoded with wchar_t (2 bytes on Windows). The UTF-8
+// version could end up bigger in memory. In the worst case each wchar_t is
+// encoded to 3 bytes in UTF-8, so in the worst case we have:
+// wcslen(wpath) * 3 <= strlen(utf8path)
+// Thus we need LIN_PATH_MAX as the UTF-8/char version of PATH_MAX.
+// Also make sure there's free space for the terminating \0.
+// (For codepoints encoded as UTF-16 surrogate pairs, UTF-8 has the same length.)
+#define LIN_PATH_MAX (FILENAME_MAX * 3 + 1)
+
+struct lin_dir {
+ DIR crap; // must be first member, unused, will be set to garbage
+ _WDIR *wdir;
+ union {
+ struct dirent dirent;
+ // dirent has space only for FILENAME_MAX bytes. _wdirent has space for
+ // FILENAME_MAX wchar_t, which might end up bigger as UTF-8 in some
+ // cases. Guarantee we can always hold _wdirent.d_name converted to
+ // UTF-8 (see LIN_PATH_MAX).
+ // This works because dirent.d_name is the last member of dirent.
+ char space[LIN_PATH_MAX];
+ };
+};
+
+DIR* lin_opendir(const char *path)
+{
+ wchar_t *wpath = lin_utf8_to_winchar(path);
+ if (!wpath)
+ return NULL;
+ _WDIR *wdir = _wopendir(wpath);
+ free_keep_err(wpath);
+ if (!wdir)
+ return NULL;
+ struct lin_dir *ldir = calloc(1, sizeof(*ldir));
+ if (!ldir) {
+ _wclosedir(wdir);
+ errno = ENOMEM;
+ return NULL;
+ }
+ // DIR is supposed to be opaque, but unfortunately the MinGW headers still
+ // define it. Make sure nobody tries to use it.
+ memset(&ldir->crap, 0xCD, sizeof(ldir->crap));
+ ldir->wdir = wdir;
+ return (DIR*)ldir;
+}
+
+struct dirent* lin_readdir(DIR *dir)
+{
+ struct lin_dir *ldir = (struct lin_dir*)dir;
+ struct _wdirent *wdirent = _wreaddir(ldir->wdir);
+ if (!wdirent)
+ return NULL;
+ size_t buffersize = sizeof(ldir->space) - offsetof(struct dirent, d_name);
+ if (WideCharToMultiByte(CP_UTF8, 0, wdirent->d_name, -1, ldir->dirent.d_name,
+ buffersize, NULL, NULL) <= 0)
+ {
+ set_errno_from_lasterror();
+ return NULL;
+ }
+ ldir->dirent.d_ino = 0;
+ ldir->dirent.d_reclen = 0;
+ ldir->dirent.d_namlen = strlen(ldir->dirent.d_name);
+ return &ldir->dirent;
+}
+
+int lin_closedir(DIR *dir)
+{
+ struct lin_dir *ldir = (struct lin_dir*)dir;
+ int res = _wclosedir(ldir->wdir);
+ free_keep_err(ldir);
+ return res;
+}
+
+int lin_mkdir(const char *path, int mode)
+{
+ wchar_t *wpath = lin_utf8_to_winchar(path);
+ if (!wpath)
+ return -1;
+ int res = _wmkdir(wpath);
+ free(wpath);
+ return res;
+}
+
+char *lin_getcwd(char *buf, size_t size)
+{
+ if (size >= SIZE_MAX / 3 - 1) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ size_t wbuffer = size * 3 + 1;
+ wchar_t *wres = malloc(sizeof(wchar_t) * wbuffer);
+ if (!wres) {
+ errno = ENOMEM;
+ return NULL;
+ }
+ DWORD wlen = GetFullPathNameW(L".", wbuffer, wres, NULL);
+ if (wlen >= wbuffer || wlen == 0) {
+ free(wres);
+ errno = wlen ? ERANGE : ENOENT;
+ return NULL;
+ }
+ char *t = lin_winchar_to_utf8(wres);
+ free_keep_err(wres);
+ if (!t)
+ return NULL;
+ size_t st = strlen(t);
+ if (st >= size) {
+ free(t);
+ errno = ERANGE;
+ return NULL;
+ }
+ memcpy(buf, t, st + 1);
+ free(t);
+ return buf;
+}
+
+off_t lin_lseek(int fd, off_t offset, int whence)
+{
+ HANDLE h = (HANDLE)_get_osfhandle(fd);
+ if (h != INVALID_HANDLE_VALUE && GetFileType(h) != FILE_TYPE_DISK) {
+ errno = ESPIPE;
+ return (off_t)-1;
+ }
+ return _lseeki64(fd, offset, whence);
+}
+
+static INIT_ONCE init_getenv_once = INIT_ONCE_STATIC_INIT;
+static char **utf8_environ;
+
+static void free_env(void)
+{
+ for (size_t n = 0; utf8_environ && utf8_environ[n]; n++)
+ free(utf8_environ[n]);
+ free(utf8_environ);
+ utf8_environ = NULL;
+}
+
+// Note: UNIX getenv() returns static strings, and we try to do the same. Since
+// using putenv() is not multithreading safe, we don't expect env vars to change
+// at runtime, and converting/allocating them in advance is ok.
+static void init_getenv(void)
+{
+ wchar_t *wenv = GetEnvironmentStringsW();
+ if (!wenv)
+ goto done;
+
+ wchar_t *wenv_cur = wenv;
+ size_t num_env = 0;
+ while (1) {
+ size_t len = wcslen(wenv_cur);
+ if (!len)
+ break;
+ num_env++;
+ wenv_cur += len + 1;
+ }
+
+ utf8_environ = calloc(sizeof(utf8_environ[0]), num_env + 1);
+ if (!utf8_environ)
+ goto done;
+
+ wenv_cur = wenv;
+ size_t cur_env = 0;
+ while (1) {
+ size_t len = wcslen(wenv_cur);
+ if (!len)
+ break;
+ assert(cur_env < num_env);
+ // On OOM, best-effort
+ utf8_environ[cur_env] = lin_winchar_to_utf8(wenv_cur);
+ if (utf8_environ[cur_env])
+ cur_env++;
+ wenv_cur += len + 1;
+ }
+
+done:
+ FreeEnvironmentStringsW(wenv);
+
+ // Avoid showing up in leak detectors etc.
+ atexit(free_env);
+}
+
+char *lin_getenv(const char *name)
+{
+ BOOL pending;
+ if (!InitOnceBeginInitialize(&init_getenv_once, 0, &pending, NULL))
+ return NULL;
+ if (pending) {
+ init_getenv();
+ InitOnceComplete(&init_getenv_once, 0, NULL);
+ }
+
+ size_t name_len = strlen(name);
+ for (size_t n = 0; utf8_environ && utf8_environ[n]; n++) {
+ char *env = utf8_environ[n];
+ if (strncasecmp(env, name, name_len) == 0 && env[name_len] == '=')
+ return env + name_len + 1;
+ }
+
+ return NULL;
+}
+
+#endif
diff --git a/src/lj_fs_io.h b/src/lj_fs_io.h
new file mode 100644
index 0000000..0bdcd20
--- /dev/null
+++ b/src/lj_fs_io.h
@@ -0,0 +1,60 @@
+// This file is copyrighted.
+
+#ifndef _LJ_FS_IO_H
+#define _LJ_FS_IO_H
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#ifdef __MINGW32__
+
+int lin_open(const char *filename, int oflag, ...);
+int lin_creat(const char *filename, int mode);
+FILE *lin_fopen(const char *filename, const char *mode);
+DIR *lin_opendir(const char *path);
+struct dirent *lin_readdir(DIR *dir);
+int lin_closedir(DIR *dir);
+int lin_mkdir(const char *path, int mode);
+char *lin_getcwd(char *buf, size_t size);
+off_t lin_lseek(int fd, off_t offset, int whence);
+
+// lin_stat types. MSVCRT's dev_t and ino_t are way too short to be unique.
+typedef uint64_t lin_dev_t;
+#ifdef _WIN64
+typedef unsigned __int128 lin_ino_t;
+#else
+// 32-bit Windows doesn't have a __int128-type, which means ReFS file IDs will
+// be truncated and might collide. This is probably not a problem because ReFS
+// is not available in consumer versions of Windows.
+typedef uint64_t lin_ino_t;
+#endif
+
+// lin_stat uses a different structure to MSVCRT, with 64-bit inodes
+struct lin_stat {
+ lin_dev_t st_dev;
+ lin_ino_t st_ino;
+ unsigned short st_mode;
+ unsigned int st_nlink;
+ short st_uid;
+ short st_gid;
+ lin_dev_t st_rdev;
+ int64_t st_size;
+ time_t st_atime;
+ time_t st_mtime;
+ time_t st_ctime;
+};
+
+int lin_stat(const char *path, struct lin_stat *buf);
+int lin_fstat(int fd, struct lin_stat *buf);
+
+char *lin_getenv(const char *name);
+
+#endif /* __MINGW32__ */
+
+#endif
diff --git a/src/lj_fs_io_replace.h b/src/lj_fs_io_replace.h
new file mode 100644
index 0000000..604e279
--- /dev/null
+++ b/src/lj_fs_io_replace.h
@@ -0,0 +1,50 @@
+// This file is copyrighted.
+
+#ifndef _LJ_FS_IO_REPLACE
+#define _LJ_FS_IO_REPLACE
+
+#include "lj_fs_io.h"
+
+#ifdef __MINGW32__
+
+#define dev_t lin_dev_t
+#define ino_t lin_ino_t
+
+#define open(...) lin_open(__VA_ARGS__)
+#define creat(...) lin_creat(__VA_ARGS__)
+#define fopen(...) lin_fopen(__VA_ARGS__)
+#define opendir(...) lin_opendir(__VA_ARGS__)
+#define readdir(...) lin_readdir(__VA_ARGS__)
+#define closedir(...) lin_closedir(__VA_ARGS__)
+#define mkdir(...) lin_mkdir(__VA_ARGS__)
+#define getcwd(...) lin_getcwd(__VA_ARGS__)
+#define getenv(...) lin_getenv(__VA_ARGS__)
+
+#undef lseek
+#define lseek(...) lin_lseek(__VA_ARGS__)
+
+// Affects both "stat()" and "struct stat".
+#undef stat
+#define stat lin_stat
+
+#undef fstat
+#define fstat(...) lin_fstat(__VA_ARGS__)
+
+#define utime(...) _utime(__VA_ARGS__)
+#define utimbuf _utimbuf
+
+#ifndef O_BINARY
+#define O_BINARY 0
+#endif
+
+#ifndef O_CLOEXEC
+#define O_CLOEXEC 0
+#endif
+
+#ifndef FD_CLOEXEC
+#define FD_CLOEXEC 0
+#endif
+
+#endif /* __MINGW32__ */
+
+#endif
diff --git a/src/lj_load.c b/src/lj_load.c
index 0aab488..150be4e 100644
--- a/src/lj_load.c
+++ b/src/lj_load.c
@@ -22,6 +22,7 @@
#include "lj_lex.h"
#include "lj_bcdump.h"
#include "lj_parse.h"
+#include "lj_fs_io_replace.h"
/* -- Load Lua source code and bytecode ----------------------------------- */
diff --git a/src/lj_trace.c b/src/lj_trace.c
index f816337..f15c4c7 100644
--- a/src/lj_trace.c
+++ b/src/lj_trace.c
@@ -31,6 +31,7 @@
#include "lj_vmevent.h"
#include "lj_target.h"
#include "lj_prng.h"
+#include "lj_fs_io_replace.h"
/* -- Error handling ------------------------------------------------------ */
diff --git a/src/ljamalg.c b/src/ljamalg.c
index 4d85950..68fb34b 100644
--- a/src/ljamalg.c
+++ b/src/ljamalg.c
@@ -18,6 +18,7 @@
#include "lua.h"
#include "lauxlib.h"
+#include "lj_fs_io.c"
#include "lj_assert.c"
#include "lj_gc.c"
#include "lj_err.c"
--
2.41.0