forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsys.zig
3438 lines (2953 loc) · 117 KB
/
sys.zig
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
// This file is entirely based on Zig's std.posix
// The differences are in error handling
const std = @import("std");
const builtin = @import("builtin");
const bun = @import("root").bun;
const posix = std.posix;
const assertIsValidWindowsPath = bun.strings.assertIsValidWindowsPath;
const default_allocator = bun.default_allocator;
const kernel32 = bun.windows;
const mem = std.mem;
const mode_t = posix.mode_t;
const libc = std.posix.system;
const windows = bun.windows;
const C = bun.C;
const Environment = bun.Environment;
const JSC = bun.JSC;
const MAX_PATH_BYTES = bun.MAX_PATH_BYTES;
const PathString = bun.PathString;
const Syscall = @This();
const SystemError = JSC.SystemError;
const linux = syscall;
pub const sys_uv = if (Environment.isWindows) @import("./sys_uv.zig") else Syscall;
const log = bun.Output.scoped(.SYS, false);
pub const syslog = log;
pub const syscall = switch (Environment.os) {
.linux => std.os.linux,
// This is actually libc on MacOS
// We don't directly use the Darwin syscall interface.
.mac => bun.AsyncIO.system,
else => @compileError("not implemented"),
};
fn toPackedO(number: anytype) std.posix.O {
return @bitCast(number);
}
pub const O = switch (Environment.os) {
.mac => struct {
pub const PATH = 0x0000;
pub const RDONLY = 0x0000;
pub const WRONLY = 0x0001;
pub const RDWR = 0x0002;
pub const NONBLOCK = 0x0004;
pub const APPEND = 0x0008;
pub const CREAT = 0x0200;
pub const TRUNC = 0x0400;
pub const EXCL = 0x0800;
pub const SHLOCK = 0x0010;
pub const EXLOCK = 0x0020;
pub const NOFOLLOW = 0x0100;
pub const SYMLINK = 0x200000;
pub const EVTONLY = 0x8000;
pub const CLOEXEC = 0x1000000;
pub const ACCMODE = 3;
pub const ALERT = 536870912;
pub const ASYNC = 64;
pub const DIRECTORY = 1048576;
pub const DP_GETRAWENCRYPTED = 1;
pub const DP_GETRAWUNENCRYPTED = 2;
pub const DSYNC = 4194304;
pub const FSYNC = SYNC;
pub const NOCTTY = 131072;
pub const POPUP = 2147483648;
pub const SYNC = 128;
pub const toPacked = toPackedO;
},
.linux, .wasm => switch (Environment.isX86) {
true => struct {
pub const RDONLY = 0x0000;
pub const WRONLY = 0x0001;
pub const RDWR = 0x0002;
pub const CREAT = 0o100;
pub const EXCL = 0o200;
pub const NOCTTY = 0o400;
pub const TRUNC = 0o1000;
pub const APPEND = 0o2000;
pub const NONBLOCK = 0o4000;
pub const DSYNC = 0o10000;
pub const SYNC = 0o4010000;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0o200000;
pub const NOFOLLOW = 0o400000;
pub const CLOEXEC = 0o2000000;
pub const ASYNC = 0o20000;
pub const DIRECT = 0o40000;
pub const LARGEFILE = 0;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20200000;
pub const NDELAY = NONBLOCK;
pub const toPacked = toPackedO;
},
false => struct {
pub const RDONLY = 0x0000;
pub const WRONLY = 0x0001;
pub const RDWR = 0x0002;
pub const CREAT = 0o100;
pub const EXCL = 0o200;
pub const NOCTTY = 0o400;
pub const TRUNC = 0o1000;
pub const APPEND = 0o2000;
pub const NONBLOCK = 0o4000;
pub const DSYNC = 0o10000;
pub const SYNC = 0o4010000;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0o40000;
pub const NOFOLLOW = 0o100000;
pub const CLOEXEC = 0o2000000;
pub const ASYNC = 0o20000;
pub const DIRECT = 0o200000;
pub const LARGEFILE = 0o400000;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20040000;
pub const NDELAY = NONBLOCK;
pub const toPacked = toPackedO;
},
},
.windows => struct {
pub const RDONLY = 0o0;
pub const WRONLY = 0o1;
pub const RDWR = 0o2;
pub const CREAT = 0o100;
pub const EXCL = 0o200;
pub const NOCTTY = 0o400;
pub const TRUNC = 0o1000;
pub const APPEND = 0o2000;
pub const NONBLOCK = 0o4000;
pub const DSYNC = 0o10000;
pub const SYNC = 0o4010000;
pub const RSYNC = 0o4010000;
pub const DIRECTORY = 0o200000;
pub const NOFOLLOW = 0o400000;
pub const CLOEXEC = 0o2000000;
pub const ASYNC = 0o20000;
pub const DIRECT = 0o40000;
pub const LARGEFILE = 0;
pub const NOATIME = 0o1000000;
pub const PATH = 0o10000000;
pub const TMPFILE = 0o20200000;
pub const NDELAY = NONBLOCK;
pub const toPacked = toPackedO;
},
};
pub const S = if (Environment.isLinux) linux.S else if (Environment.isPosix) std.posix.S else struct {};
pub const Tag = enum(u8) {
TODO,
dup,
access,
connect,
chmod,
chown,
clonefile,
close,
copy_file_range,
copyfile,
fchmod,
fchmodat,
fchown,
fcntl,
fdatasync,
fstat,
fstatat,
fsync,
ftruncate,
futimens,
getdents64,
getdirentries64,
lchmod,
lchown,
link,
lseek,
lstat,
lutimes,
mkdir,
mkdtemp,
fnctl,
memfd_create,
mmap,
munmap,
open,
pread,
pwrite,
read,
readlink,
rename,
stat,
symlink,
symlinkat,
unlink,
utimes,
write,
getcwd,
getenv,
chdir,
fcopyfile,
recv,
send,
sendfile,
sendmmsg,
splice,
rmdir,
truncate,
realpath,
futime,
pidfd_open,
poll,
watch,
kevent,
kqueue,
epoll_ctl,
kill,
waitpid,
posix_spawn,
getaddrinfo,
writev,
pwritev,
readv,
preadv,
ioctl_ficlone,
accept,
bind2,
connect2,
listen,
pipe,
try_write,
socketpair,
uv_spawn,
uv_pipe,
uv_tty_set_mode,
uv_open_osfhandle,
// Below this line are Windows API calls only.
WriteFile,
NtQueryDirectoryFile,
NtSetInformationFile,
GetFinalPathNameByHandle,
CloseHandle,
SetFilePointerEx,
SetEndOfFile,
pub fn isWindows(this: Tag) bool {
return @intFromEnum(this) > @intFromEnum(Tag.WriteFile);
}
pub var strings = std.EnumMap(Tag, JSC.C.JSStringRef).initFull(null);
};
pub const Error = struct {
const E = bun.C.E;
const retry_errno = if (Environment.isLinux)
@as(Int, @intCast(@intFromEnum(E.AGAIN)))
else if (Environment.isMac)
@as(Int, @intCast(@intFromEnum(E.AGAIN)))
else
@as(Int, @intCast(@intFromEnum(E.INTR)));
const todo_errno = std.math.maxInt(Int) - 1;
pub const Int = if (Environment.isWindows) u16 else u8; // @TypeOf(@intFromEnum(E.BADF));
/// TODO: convert to function
pub const oom = fromCode(E.NOMEM, .read);
errno: Int = todo_errno,
fd: bun.FileDescriptor = bun.invalid_fd,
from_libuv: if (Environment.isWindows) bool else void = if (Environment.isWindows) false else undefined,
path: []const u8 = "",
syscall: Syscall.Tag = Syscall.Tag.TODO,
pub fn clone(this: *const Error, allocator: std.mem.Allocator) !Error {
var copy = this.*;
copy.path = try allocator.dupe(u8, copy.path);
return copy;
}
pub fn fromCode(errno: E, syscall_tag: Syscall.Tag) Error {
return .{
.errno = @as(Int, @intCast(@intFromEnum(errno))),
.syscall = syscall_tag,
};
}
pub fn fromCodeInt(errno: anytype, syscall_tag: Syscall.Tag) Error {
return .{
.errno = @as(Int, @intCast(if (Environment.isWindows) @abs(errno) else errno)),
.syscall = syscall_tag,
};
}
pub fn format(self: Error, comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void {
try self.toSystemError().format(fmt, opts, writer);
}
pub inline fn getErrno(this: Error) E {
return @as(E, @enumFromInt(this.errno));
}
pub inline fn isRetry(this: *const Error) bool {
return this.getErrno() == .AGAIN;
}
pub const retry = Error{
.errno = retry_errno,
.syscall = .read,
};
pub inline fn withFd(this: Error, fd: anytype) Error {
if (Environment.allow_assert) bun.assert(fd != bun.invalid_fd);
return Error{
.errno = this.errno,
.syscall = this.syscall,
.fd = fd,
};
}
pub inline fn withPath(this: Error, path: anytype) Error {
if (std.meta.Child(@TypeOf(path)) == u16) {
@compileError("Do not pass WString path to withPath, it needs the path encoded as utf8");
}
return Error{
.errno = this.errno,
.syscall = this.syscall,
.path = bun.span(path),
};
}
pub inline fn withPathLike(this: Error, pathlike: anytype) Error {
return switch (pathlike) {
.fd => |fd| this.withFd(fd),
.path => |path| this.withPath(path.slice()),
};
}
pub fn name(this: *const Error) []const u8 {
if (comptime Environment.isWindows) {
const system_errno = brk: {
// setRuntimeSafety(false) because we use tagName function, which will be null on invalid enum value.
@setRuntimeSafety(false);
if (this.from_libuv) {
break :brk @as(C.SystemErrno, @enumFromInt(@intFromEnum(bun.windows.libuv.translateUVErrorToE(this.errno))));
}
break :brk @as(C.SystemErrno, @enumFromInt(this.errno));
};
if (bun.tagName(bun.C.SystemErrno, system_errno)) |errname| {
return errname;
}
} else if (this.errno > 0 and this.errno < C.SystemErrno.max) {
const system_errno = @as(C.SystemErrno, @enumFromInt(this.errno));
if (bun.tagName(bun.C.SystemErrno, system_errno)) |errname| {
return errname;
}
}
return "UNKNOWN";
}
pub fn toZigErr(this: Error) anyerror {
return bun.errnoToZigErr(this.errno);
}
pub fn toSystemError(this: Error) SystemError {
var err = SystemError{
.errno = @as(c_int, this.errno) * -1,
.syscall = bun.String.static(@tagName(this.syscall)),
};
// errno label
if (!Environment.isWindows) {
if (this.errno > 0 and this.errno < C.SystemErrno.max) {
const system_errno = @as(C.SystemErrno, @enumFromInt(this.errno));
err.code = bun.String.static(@tagName(system_errno));
if (C.SystemErrno.labels.get(system_errno)) |label| {
err.message = bun.String.static(label);
}
}
} else {
const system_errno = brk: {
// setRuntimeSafety(false) because we use tagName function, which will be null on invalid enum value.
@setRuntimeSafety(false);
if (this.from_libuv) {
break :brk @as(C.SystemErrno, @enumFromInt(@intFromEnum(bun.windows.libuv.translateUVErrorToE(err.errno))));
}
break :brk @as(C.SystemErrno, @enumFromInt(this.errno));
};
if (bun.tagName(bun.C.SystemErrno, system_errno)) |errname| {
err.code = bun.String.static(errname);
if (C.SystemErrno.labels.get(system_errno)) |label| {
err.message = bun.String.static(label);
}
}
}
if (this.path.len > 0) {
err.path = bun.String.createUTF8(this.path);
}
if (this.fd != bun.invalid_fd) {
err.fd = this.fd;
}
return err;
}
pub inline fn todo() Error {
if (Environment.isDebug) {
@panic("bun.sys.Error.todo() was called");
}
return Error{ .errno = todo_errno, .syscall = .TODO };
}
pub fn toJS(this: Error, ctx: JSC.C.JSContextRef) JSC.C.JSObjectRef {
return this.toSystemError().toErrorInstance(ctx).asObjectRef();
}
pub fn toJSC(this: Error, ptr: *JSC.JSGlobalObject) JSC.JSValue {
return this.toSystemError().toErrorInstance(ptr);
}
};
pub fn Maybe(comptime ReturnTypeT: type) type {
return JSC.Node.Maybe(ReturnTypeT, Error);
}
pub fn getcwd(buf: *bun.PathBuffer) Maybe([]const u8) {
const Result = Maybe([]const u8);
return switch (getcwdZ(buf)) {
.err => |err| Result{ .err = err },
.result => |cwd| Result{ .result = cwd },
};
}
pub fn getcwdZ(buf: *bun.PathBuffer) Maybe([:0]const u8) {
const Result = Maybe([:0]const u8);
buf[0] = 0;
if (comptime Environment.isWindows) {
var wbuf: bun.WPathBuffer = undefined;
const len: windows.DWORD = kernel32.GetCurrentDirectoryW(wbuf.len, &wbuf);
if (Result.errnoSys(len, .getcwd)) |err| return err;
return Result{ .result = bun.strings.fromWPath(buf, wbuf[0..len]) };
}
const rc: ?[*:0]u8 = @ptrCast(std.c.getcwd(buf, bun.MAX_PATH_BYTES));
return if (rc != null)
Result{ .result = rc.?[0..std.mem.len(rc.?) :0] }
else
Result.errnoSys(@as(c_int, 0), .getcwd).?;
}
pub fn fchmod(fd: bun.FileDescriptor, mode: bun.Mode) Maybe(void) {
if (comptime Environment.isWindows) {
return sys_uv.fchmod(fd, mode);
}
return Maybe(void).errnoSys(C.fchmod(fd.cast(), mode), .fchmod) orelse
Maybe(void).success;
}
pub fn fchmodat(fd: bun.FileDescriptor, path: [:0]const u8, mode: bun.Mode, flags: i32) Maybe(void) {
if (comptime Environment.isWindows) @compileError("Use fchmod instead");
return Maybe(void).errnoSys(C.fchmodat(fd.cast(), path.ptr, mode, flags), .fchmodat) orelse
Maybe(void).success;
}
pub fn chmod(path: [:0]const u8, mode: bun.Mode) Maybe(void) {
if (comptime Environment.isWindows) {
return sys_uv.chmod(path, mode);
}
return Maybe(void).errnoSysP(C.chmod(path.ptr, mode), .chmod, path) orelse
Maybe(void).success;
}
pub fn chdirOSPath(destination: bun.OSPathSliceZ) Maybe(void) {
assertIsValidWindowsPath(bun.OSPathChar, destination);
if (comptime Environment.isPosix) {
const rc = syscall.chdir(destination);
return Maybe(void).errnoSys(rc, .chdir) orelse Maybe(void).success;
}
if (comptime Environment.isWindows) {
if (kernel32.SetCurrentDirectory(destination) == windows.FALSE) {
log("SetCurrentDirectory({}) = {d}", .{ bun.fmt.utf16(destination), kernel32.GetLastError() });
return Maybe(void).errnoSys(0, .chdir) orelse Maybe(void).success;
}
log("SetCurrentDirectory({}) = {d}", .{ bun.fmt.utf16(destination), 0 });
return Maybe(void).success;
}
@compileError("Not implemented yet");
}
pub fn chdir(destination: anytype) Maybe(void) {
const Type = @TypeOf(destination);
if (comptime Environment.isPosix) {
if (comptime Type == []u8 or Type == []const u8) {
return chdirOSPath(
&(std.posix.toPosixPath(destination) catch return .{ .err = .{
.errno = @intFromEnum(bun.C.SystemErrno.EINVAL),
.syscall = .chdir,
} }),
);
}
return chdirOSPath(destination);
}
if (comptime Environment.isWindows) {
if (comptime Type == *[*:0]u16) {
if (kernel32.SetCurrentDirectory(destination) != 0) {
return Maybe(void).errnoSys(0, .chdir) orelse Maybe(void).success;
}
return Maybe(void).success;
}
if (comptime Type == bun.OSPathSliceZ or Type == [:0]u16) {
return chdirOSPath(@as(bun.OSPathSliceZ, destination));
}
var wbuf: bun.WPathBuffer = undefined;
return chdirOSPath(bun.strings.toWDirPath(&wbuf, destination));
}
return Maybe(void).todo();
}
pub fn sendfile(src: bun.FileDescriptor, dest: bun.FileDescriptor, len: usize) Maybe(usize) {
while (true) {
const rc = std.os.linux.sendfile(
dest.cast(),
src.cast(),
null,
// we set a maximum to avoid EINVAL
@min(len, std.math.maxInt(i32) - 1),
);
if (Maybe(usize).errnoSysFd(rc, .sendfile, src)) |err| {
if (err.getErrno() == .INTR) continue;
return err;
}
return .{ .result = rc };
}
}
pub fn stat(path: [:0]const u8) Maybe(bun.Stat) {
if (Environment.isWindows) {
return sys_uv.stat(path);
} else {
var stat_ = mem.zeroes(bun.Stat);
const rc = C.stat(path, &stat_);
if (comptime Environment.allow_assert)
log("stat({s}) = {d}", .{ bun.asByteSlice(path), rc });
if (Maybe(bun.Stat).errnoSys(rc, .stat)) |err| return err;
return Maybe(bun.Stat){ .result = stat_ };
}
}
pub fn lstat(path: [:0]const u8) Maybe(bun.Stat) {
if (Environment.isWindows) {
return sys_uv.lstat(path);
} else {
var stat_ = mem.zeroes(bun.Stat);
if (Maybe(bun.Stat).errnoSys(C.lstat(path, &stat_), .lstat)) |err| return err;
return Maybe(bun.Stat){ .result = stat_ };
}
}
pub fn fstat(fd: bun.FileDescriptor) Maybe(bun.Stat) {
if (Environment.isWindows) {
const dec = bun.FDImpl.decode(fd);
if (dec.kind == .system) {
const uvfd = bun.toLibUVOwnedFD(fd) catch return .{ .err = Error.fromCode(.MFILE, .uv_open_osfhandle) };
return sys_uv.fstat(uvfd);
} else return sys_uv.fstat(fd);
}
var stat_ = mem.zeroes(bun.Stat);
const rc = C.fstat(fd.cast(), &stat_);
if (comptime Environment.allow_assert)
log("fstat({}) = {d}", .{ fd, rc });
if (Maybe(bun.Stat).errnoSys(rc, .fstat)) |err| return err;
return Maybe(bun.Stat){ .result = stat_ };
}
pub fn mkdiratA(dir_fd: bun.FileDescriptor, file_path: []const u8) Maybe(void) {
var buf: bun.WPathBuffer = undefined;
return mkdiratW(dir_fd, bun.strings.toWPathNormalized(&buf, file_path));
}
pub fn mkdiratZ(dir_fd: bun.FileDescriptor, file_path: [*:0]const u8, mode: mode_t) Maybe(void) {
return switch (Environment.os) {
.mac => Maybe(void).errnoSysP(syscall.mkdirat(@intCast(dir_fd.cast()), file_path, mode), .mkdir, file_path) orelse Maybe(void).success,
.linux => Maybe(void).errnoSysP(linux.mkdirat(@intCast(dir_fd.cast()), file_path, mode), .mkdir, file_path) orelse Maybe(void).success,
else => @compileError("mkdir is not implemented on this platform"),
};
}
fn mkdiratPosix(dir_fd: bun.FileDescriptor, file_path: []const u8, mode: mode_t) Maybe(void) {
return mkdiratZ(
dir_fd,
&(std.posix.toPosixPath(file_path) catch return .{ .err = Error.fromCode(.NAMETOOLONG, .mkdir) }),
mode,
);
}
pub const mkdirat = if (Environment.isWindows)
mkdiratW
else
mkdiratPosix;
pub fn mkdiratW(dir_fd: bun.FileDescriptor, file_path: []const u16, _: i32) Maybe(void) {
const dir_to_make = openDirAtWindowsNtPath(dir_fd, file_path, .{ .iterable = false, .can_rename_or_delete = true, .create = true });
if (dir_to_make == .err) {
return .{ .err = dir_to_make.err };
}
_ = close(dir_to_make.result);
return .{ .result = {} };
}
pub fn fstatat(fd: bun.FileDescriptor, path: [:0]const u8) Maybe(bun.Stat) {
if (Environment.isWindows) {
return switch (openatWindowsA(fd, path, 0)) {
.result => |file| {
// :(
defer _ = close(file);
return fstat(file);
},
.err => |err| Maybe(bun.Stat){ .err = err },
};
}
var stat_ = mem.zeroes(bun.Stat);
if (Maybe(bun.Stat).errnoSys(syscall.fstatat(fd.int(), path, &stat_, 0), .fstatat)) |err| {
log("fstatat({}, {s}) = {s}", .{ fd, path, @tagName(err.getErrno()) });
return err;
}
log("fstatat({}, {s}) = 0", .{ fd, path });
return Maybe(bun.Stat){ .result = stat_ };
}
pub fn mkdir(file_path: [:0]const u8, flags: bun.Mode) Maybe(void) {
return switch (Environment.os) {
.mac => Maybe(void).errnoSysP(syscall.mkdir(file_path, flags), .mkdir, file_path) orelse Maybe(void).success,
.linux => Maybe(void).errnoSysP(syscall.mkdir(file_path, flags), .mkdir, file_path) orelse Maybe(void).success,
.windows => {
var wbuf: bun.WPathBuffer = undefined;
return Maybe(void).errnoSysP(
kernel32.CreateDirectoryW(bun.strings.toWPath(&wbuf, file_path).ptr, null),
.mkdir,
file_path,
) orelse Maybe(void).success;
},
else => @compileError("mkdir is not implemented on this platform"),
};
}
pub fn mkdirA(file_path: []const u8, flags: bun.Mode) Maybe(void) {
if (comptime Environment.isMac) {
return Maybe(void).errnoSysP(syscall.mkdir(&(std.posix.toPosixPath(file_path) catch return Maybe(void){
.err = .{
.errno = @intFromEnum(bun.C.E.NOMEM),
.syscall = .open,
},
}), flags), .mkdir, file_path) orelse Maybe(void).success;
}
if (comptime Environment.isLinux) {
return Maybe(void).errnoSysP(linux.mkdir(&(std.posix.toPosixPath(file_path) catch return Maybe(void){
.err = .{
.errno = @intFromEnum(bun.C.E.NOMEM),
.syscall = .open,
},
}), flags), .mkdir, file_path) orelse Maybe(void).success;
}
if (comptime Environment.isWindows) {
var wbuf: bun.WPathBuffer = undefined;
const wpath = bun.strings.toWPath(&wbuf, file_path);
assertIsValidWindowsPath(u16, wpath);
return Maybe(void).errnoSysP(
kernel32.CreateDirectoryW(wpath.ptr, null),
.mkdir,
file_path,
) orelse Maybe(void).success;
}
}
pub fn mkdirOSPath(file_path: bun.OSPathSliceZ, flags: bun.Mode) Maybe(void) {
return switch (Environment.os) {
else => mkdir(file_path, flags),
.windows => {
const rc = kernel32.CreateDirectoryW(file_path, null);
if (Maybe(void).errnoSys(
rc,
.mkdir,
)) |err| {
log("CreateDirectoryW({}) = {s}", .{ bun.fmt.fmtOSPath(file_path, .{}), err.err.name() });
return err;
}
log("CreateDirectoryW({}) = 0", .{bun.fmt.fmtOSPath(file_path, .{})});
return Maybe(void).success;
},
};
}
const fnctl_int = if (Environment.isLinux) usize else c_int;
pub fn fcntl(fd: bun.FileDescriptor, cmd: i32, arg: fnctl_int) Maybe(fnctl_int) {
const result = fcntl_symbol(fd.cast(), cmd, arg);
if (Maybe(fnctl_int).errnoSys(result, .fcntl)) |err| return err;
return .{ .result = @intCast(result) };
}
pub fn getErrno(rc: anytype) bun.C.E {
if (comptime Environment.isWindows) {
if (comptime @TypeOf(rc) == bun.windows.NTSTATUS) {
return bun.windows.translateNTStatusToErrno(rc);
}
if (bun.windows.Win32Error.get().toSystemErrno()) |e| {
return e.toE();
}
return bun.C.E.UNKNOWN;
}
return bun.C.getErrno(rc);
}
const w = std.os.windows;
pub fn normalizePathWindows(
comptime T: type,
dir_fd: bun.FileDescriptor,
path_: []const T,
buf: *bun.WPathBuffer,
) Maybe([:0]const u16) {
if (comptime T != u8 and T != u16) {
@compileError("normalizePathWindows only supports u8 and u16 character types");
}
var wbuf: if (T == u16) void else bun.WPathBuffer = undefined;
var path = if (T == u16) path_ else bun.strings.convertUTF8toUTF16InBuffer(&wbuf, path_);
if (std.fs.path.isAbsoluteWindowsWTF16(path)) {
// handle the special "nul" device
// we technically should handle the other DOS devices too.
if (path_.len >= "\\nul".len and
(bun.strings.eqlComptimeT(T, path_[path_.len - "\\nul".len ..], "\\nul") or
bun.strings.eqlComptimeT(T, path_[path_.len - "\\NUL".len ..], "\\NUL")))
{
@memcpy(buf[0..bun.strings.w("\\??\\NUL").len], bun.strings.w("\\??\\NUL"));
buf[bun.strings.w("\\??\\NUL").len] = 0;
return .{ .result = buf[0..bun.strings.w("\\??\\NUL").len :0] };
}
const norm = bun.path.normalizeStringGenericTZ(u16, path, buf, .{ .add_nt_prefix = true, .zero_terminate = true });
return .{ .result = norm };
}
if (bun.strings.indexOfAnyT(T, path_, &.{ '\\', '/', '.' }) == null) {
if (buf.len < path.len) {
return .{
.err = .{
.errno = @intFromEnum(bun.C.E.NOMEM),
.syscall = .open,
},
};
}
// Skip the system call to get the final path name if it doesn't have any of the above characters.
@memcpy(buf[0..path.len], path);
buf[path.len] = 0;
return .{
.result = buf[0..path.len :0],
};
}
const base_fd = if (dir_fd == bun.invalid_fd)
std.fs.cwd().fd
else
dir_fd.cast();
const base_path = bun.windows.GetFinalPathNameByHandle(base_fd, w.GetFinalPathNameByHandleFormat{}, buf) catch {
return .{ .err = .{
.errno = @intFromEnum(bun.C.E.BADFD),
.syscall = .open,
} };
};
if (path.len >= 2 and bun.path.isDriveLetterT(u16, path[0]) and path[1] == ':') {
path = path[2..];
}
var buf1: bun.WPathBuffer = undefined;
@memcpy(buf1[0..base_path.len], base_path);
buf1[base_path.len] = '\\';
@memcpy(buf1[base_path.len + 1 .. base_path.len + 1 + path.len], path);
const norm = bun.path.normalizeStringGenericTZ(u16, buf1[0 .. base_path.len + 1 + path.len], buf, .{ .add_nt_prefix = true, .zero_terminate = true });
return .{
.result = norm,
};
}
fn openDirAtWindowsNtPath(
dirFd: bun.FileDescriptor,
path: []const u16,
options: WindowsOpenDirOptions,
) Maybe(bun.FileDescriptor) {
const iterable = options.iterable;
const no_follow = options.no_follow;
const can_rename_or_delete = options.can_rename_or_delete;
const read_only = options.read_only;
assertIsValidWindowsPath(u16, path);
const base_flags = w.STANDARD_RIGHTS_READ | w.FILE_READ_ATTRIBUTES | w.FILE_READ_EA |
w.SYNCHRONIZE | w.FILE_TRAVERSE;
const iterable_flag: u32 = if (iterable) w.FILE_LIST_DIRECTORY else 0;
const rename_flag: u32 = if (can_rename_or_delete) w.DELETE else 0;
const read_only_flag: u32 = if (read_only) 0 else w.FILE_ADD_FILE | w.FILE_ADD_SUBDIRECTORY;
const flags: u32 = iterable_flag | base_flags | rename_flag | read_only_flag;
const path_len_bytes: u16 = @truncate(path.len * 2);
var nt_name = w.UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @constCast(path.ptr),
};
var attr = w.OBJECT_ATTRIBUTES{
.Length = @sizeOf(w.OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsWTF16(path))
null
else if (dirFd == bun.invalid_fd)
std.fs.cwd().fd
else
dirFd.cast(),
.Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
const open_reparse_point: w.DWORD = if (no_follow) w.FILE_OPEN_REPARSE_POINT else 0x0;
var fd: w.HANDLE = w.INVALID_HANDLE_VALUE;
var io: w.IO_STATUS_BLOCK = undefined;
const rc = w.ntdll.NtCreateFile(
&fd,
flags,
&attr,
&io,
null,
0,
FILE_SHARE,
if (options.create) w.FILE_OPEN_IF else w.FILE_OPEN,
w.FILE_DIRECTORY_FILE | w.FILE_SYNCHRONOUS_IO_NONALERT | w.FILE_OPEN_FOR_BACKUP_INTENT | open_reparse_point,
null,
0,
);
if (comptime Environment.allow_assert) {
if (rc == .INVALID_PARAMETER) {
// Double check what flags you are passing to this
//
// - access_mask probably needs w.SYNCHRONIZE,
// - options probably needs w.FILE_SYNCHRONOUS_IO_NONALERT
// - disposition probably needs w.FILE_OPEN
bun.Output.debugWarn("NtCreateFile({}, {}) = {s} (dir) = {d}\nYou are calling this function with the wrong flags!!!", .{ dirFd, bun.fmt.utf16(path), @tagName(rc), @intFromPtr(fd) });
} else if (rc == .OBJECT_PATH_SYNTAX_BAD or rc == .OBJECT_NAME_INVALID) {
bun.Output.debugWarn("NtCreateFile({}, {}) = {s} (dir) = {d}\nYou are calling this function without normalizing the path correctly!!!", .{ dirFd, bun.fmt.utf16(path), @tagName(rc), @intFromPtr(fd) });
} else {
log("NtCreateFile({}, {}) = {s} (dir) = {d}", .{ dirFd, bun.fmt.utf16(path), @tagName(rc), @intFromPtr(fd) });
}
}
switch (windows.Win32Error.fromNTStatus(rc)) {
.SUCCESS => {
return .{
.result = bun.toFD(fd),
};
},
else => |code| {
if (code.toSystemErrno()) |sys_err| {
return .{
.err = .{
.errno = @intFromEnum(sys_err),
.syscall = .open,
},
};
}
return .{
.err = .{
.errno = @intFromEnum(bun.C.E.UNKNOWN),
.syscall = .open,
},
};
},
}
}
pub const WindowsOpenDirOptions = packed struct {
iterable: bool = false,
no_follow: bool = false,
can_rename_or_delete: bool = false,
create: bool = false,
read_only: bool = false,
};
fn openDirAtWindowsT(
comptime T: type,
dirFd: bun.FileDescriptor,
path: []const T,
options: WindowsOpenDirOptions,
) Maybe(bun.FileDescriptor) {
var wbuf: bun.WPathBuffer = undefined;
const norm = switch (normalizePathWindows(T, dirFd, path, &wbuf)) {
.err => |err| return .{ .err = err },
.result => |norm| norm,
};
if (comptime T == u8) {
log("openDirAtWindows({s}) = {s}", .{ path, bun.fmt.utf16(norm) });
} else {
log("openDirAtWindowsT({s}) = {s}", .{ bun.fmt.utf16(path), bun.fmt.utf16(norm) });
}
return openDirAtWindowsNtPath(dirFd, norm, options);
}
pub fn openDirAtWindows(
dirFd: bun.FileDescriptor,
path: []const u16,
options: WindowsOpenDirOptions,
) Maybe(bun.FileDescriptor) {
return openDirAtWindowsT(u16, dirFd, path, options);
}
pub noinline fn openDirAtWindowsA(
dirFd: bun.FileDescriptor,
path: []const u8,
options: WindowsOpenDirOptions,
) Maybe(bun.FileDescriptor) {
return openDirAtWindowsT(u8, dirFd, path, options);
}
/// For this function to open an absolute path, it must start with "\??\". Otherwise
/// you need a reference file descriptor the "invalid_fd" file descriptor is used
/// to signify that the current working directory should be used.
///
/// When using this function I highly recommend reading this first:
/// https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntcreatefile
///
/// It is very very very easy to mess up flags here. Please review existing
/// examples to this call and the above function that maps unix flags to
/// the windows ones.
///
/// It is very easy to waste HOURS on the subtle semantics of this function.