forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.zig
1904 lines (1590 loc) · 69.8 KB
/
fs.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
const std = @import("std");
const bun = @import("root").bun;
const string = bun.string;
const Output = bun.Output;
const Global = bun.Global;
const Environment = bun.Environment;
const strings = bun.strings;
const MutableString = bun.MutableString;
const StoredFileDescriptorType = bun.StoredFileDescriptorType;
const FileDescriptor = bun.FileDescriptor;
const FeatureFlags = bun.FeatureFlags;
const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
const sync = @import("sync.zig");
const Mutex = @import("./lock.zig").Lock;
const Semaphore = sync.Semaphore;
const Fs = @This();
const path_handler = @import("./resolver/resolve_path.zig");
const PathString = bun.PathString;
const allocators = bun.allocators;
const OOM = bun.OOM;
const MAX_PATH_BYTES = bun.MAX_PATH_BYTES;
const PathBuffer = bun.PathBuffer;
const WPathBuffer = bun.WPathBuffer;
pub const debug = Output.scoped(.fs, true);
// pub const FilesystemImplementation = @import("fs_impl.zig");
pub const Preallocate = struct {
pub const Counts = struct {
pub const dir_entry: usize = 2048;
pub const files: usize = 4096;
};
};
pub const FileSystem = struct {
top_level_dir: string,
// used on subsequent updates
top_level_dir_buf: bun.PathBuffer = undefined,
fs: Implementation,
dirname_store: *DirnameStore,
filename_store: *FilenameStore,
threadlocal var tmpdir_handle: ?std.fs.Dir = null;
pub fn topLevelDirWithoutTrailingSlash(this: *const FileSystem) []const u8 {
if (this.top_level_dir.len > 1 and this.top_level_dir[this.top_level_dir.len - 1] == std.fs.path.sep) {
return this.top_level_dir[0 .. this.top_level_dir.len - 1];
} else {
return this.top_level_dir;
}
}
pub fn tmpdir(fs: *FileSystem) !std.fs.Dir {
if (tmpdir_handle == null) {
tmpdir_handle = try fs.fs.openTmpDir();
}
return tmpdir_handle.?;
}
pub fn getFdPath(this: *const FileSystem, fd: FileDescriptor) ![]const u8 {
var buf: bun.PathBuffer = undefined;
const dir = try bun.getFdPath(fd, &buf);
return try this.dirname_store.append([]u8, dir);
}
var tmpname_id_number = std.atomic.Value(u32).init(0);
pub fn tmpname(_: *const FileSystem, extname: string, buf: []u8, hash: u64) ![*:0]u8 {
const hex_value = @as(u64, @truncate(@as(u128, @intCast(hash)) | @as(u128, @intCast(std.time.nanoTimestamp()))));
return try std.fmt.bufPrintZ(buf, ".{any}-{any}.{s}", .{
bun.fmt.hexIntLower(hex_value),
bun.fmt.hexIntUpper(tmpname_id_number.fetchAdd(1, .monotonic)),
extname,
});
}
pub var max_fd: std.posix.fd_t = 0;
pub inline fn setMaxFd(fd: std.posix.fd_t) void {
if (Environment.isWindows) {
return;
}
if (!FeatureFlags.store_file_descriptors) {
return;
}
max_fd = @max(fd, max_fd);
}
pub var instance_loaded: bool = false;
pub var instance: FileSystem = undefined;
pub const DirnameStore = allocators.BSSStringList(Preallocate.Counts.dir_entry, 128);
pub const FilenameStore = allocators.BSSStringList(Preallocate.Counts.files, 64);
pub const Error = error{
ENOENT,
EACCESS,
INVALID_NAME,
ENOTDIR,
};
pub fn init(top_level_dir: ?string) !*FileSystem {
return initWithForce(top_level_dir, false);
}
pub fn initWithForce(top_level_dir_: ?string, comptime force: bool) !*FileSystem {
const allocator = bun.fs_allocator;
var top_level_dir = top_level_dir_ orelse (if (Environment.isBrowser) "/project/" else try bun.getcwdAlloc(allocator));
// Ensure there's a trailing separator in the top level directory
// This makes path resolution more reliable
if (!bun.path.isSepAny(top_level_dir[top_level_dir.len - 1])) {
const tld = try allocator.alloc(u8, top_level_dir.len + 1);
bun.copy(u8, tld, top_level_dir);
tld[tld.len - 1] = std.fs.path.sep;
top_level_dir = tld;
}
if (!instance_loaded or force) {
instance = FileSystem{
.top_level_dir = top_level_dir,
.fs = Implementation.init(top_level_dir),
// must always use default_allocator since the other allocators may not be threadsafe when an element resizes
.dirname_store = DirnameStore.init(bun.default_allocator),
.filename_store = FilenameStore.init(bun.default_allocator),
};
instance_loaded = true;
_ = DirEntry.EntryStore.init(allocator);
}
return &instance;
}
pub const DirEntry = struct {
pub const EntryMap = bun.StringHashMapUnmanaged(*Entry);
pub const EntryStore = allocators.BSSList(Entry, Preallocate.Counts.files);
dir: string,
fd: StoredFileDescriptorType = .zero,
generation: bun.Generation = 0,
data: EntryMap,
// pub fn removeEntry(dir: *DirEntry, name: string) !void {
// // dir.data.remove(name);
// }
pub fn addEntry(dir: *DirEntry, prev_map: ?*EntryMap, entry: *const bun.DirIterator.IteratorResult, allocator: std.mem.Allocator, comptime Iterator: type, iterator: Iterator) !void {
const name_slice = entry.name.slice();
const _kind: Entry.Kind = switch (entry.kind) {
.directory => .dir,
// This might be wrong!
.sym_link => .file,
.file => .file,
else => return,
};
const stored = try brk: {
if (prev_map) |map| {
var stack_fallback = std.heap.stackFallback(512, allocator);
const stack = stack_fallback.get();
const prehashed = bun.StringHashMapContext.PrehashedCaseInsensitive.init(stack, name_slice);
defer prehashed.deinit(stack);
if (map.getAdapted(name_slice, prehashed)) |existing| {
existing.mutex.lock();
defer existing.mutex.unlock();
existing.dir = dir.dir;
existing.need_stat = existing.need_stat or existing.cache.kind != _kind;
// TODO: is this right?
if (existing.cache.kind != _kind) {
existing.cache.kind = _kind;
existing.cache.symlink = PathString.empty;
}
break :brk existing;
}
}
// name_slice only lives for the duration of the iteration
const name = try strings.StringOrTinyString.initAppendIfNeeded(
name_slice,
*FileSystem.FilenameStore,
FileSystem.FilenameStore.instance,
);
const name_lowercased = try strings.StringOrTinyString.initLowerCaseAppendIfNeeded(
name_slice,
*FileSystem.FilenameStore,
FileSystem.FilenameStore.instance,
);
break :brk EntryStore.instance.append(.{
.base_ = name,
.base_lowercase_ = name_lowercased,
.dir = dir.dir,
.mutex = .{},
// Call "stat" lazily for performance. The "@material-ui/icons" package
// contains a directory with over 11,000 entries in it and running "stat"
// for each entry was a big performance issue for that package.
.need_stat = entry.kind == .sym_link,
.cache = .{
.symlink = PathString.empty,
.kind = _kind,
},
});
};
const stored_name = stored.base();
try dir.data.put(allocator, stored.base_lowercase(), stored);
if (comptime Iterator != void) {
iterator.next(stored, dir.fd);
}
if (comptime FeatureFlags.verbose_fs) {
if (_kind == .dir) {
Output.prettyln(" + {s}/", .{stored_name});
} else {
Output.prettyln(" + {s}", .{stored_name});
}
}
}
pub fn init(dir: string, generation: bun.Generation) DirEntry {
if (comptime FeatureFlags.verbose_fs) {
Output.prettyln("\n {s}", .{dir});
}
return .{
.dir = dir,
.data = .{},
.generation = generation,
};
}
pub const Err = struct {
original_err: anyerror,
canonical_error: anyerror,
};
pub fn deinit(d: *DirEntry, allocator: std.mem.Allocator) void {
d.data.deinit(allocator);
allocator.free(d.dir);
}
pub fn get(entry: *const DirEntry, _query: string) ?Entry.Lookup {
if (_query.len == 0 or _query.len > bun.MAX_PATH_BYTES) return null;
var scratch_lookup_buffer: bun.PathBuffer = undefined;
const query = strings.copyLowercaseIfNeeded(_query, &scratch_lookup_buffer);
const result = entry.data.get(query) orelse return null;
const basename = result.base();
if (!strings.eqlLong(basename, _query, true)) {
return Entry.Lookup{ .entry = result, .diff_case = Entry.Lookup.DifferentCase{
.dir = entry.dir,
.query = _query,
.actual = basename,
} };
}
return Entry.Lookup{ .entry = result, .diff_case = null };
}
pub fn getComptimeQuery(entry: *const DirEntry, comptime query_str: anytype) ?Entry.Lookup {
comptime var query_var: [query_str.len]u8 = undefined;
comptime for (query_str, 0..) |c, i| {
query_var[i] = std.ascii.toLower(c);
};
const query_hashed = comptime std.hash_map.hashString(&query_var);
const query = query_var[0..query_str.len].*;
const result = entry.data.getAdapted(
@as([]const u8, &query),
struct {
pub fn hash(_: @This(), _: []const u8) @TypeOf(query_hashed) {
return query_hashed;
}
pub fn eql(_: @This(), _: []const u8, b: []const u8) bool {
return strings.eqlComptime(b, query);
}
}{},
) orelse return null;
const basename = result.base();
if (!strings.eqlComptime(basename, comptime query[0..query_str.len])) {
return Entry.Lookup{
.entry = result,
.diff_case = Entry.Lookup.DifferentCase{
.dir = entry.dir,
.query = &query,
.actual = basename,
},
};
}
return Entry.Lookup{ .entry = result, .diff_case = null };
}
pub fn hasComptimeQuery(entry: *const DirEntry, comptime query_str: anytype) bool {
comptime var query_var: [query_str.len]u8 = undefined;
comptime for (query_str, 0..) |c, i| {
query_var[i] = std.ascii.toLower(c);
};
const query = query_var[0..query_str.len].*;
const query_hashed = comptime std.hash_map.hashString(&query);
return entry.data.containsAdapted(
@as([]const u8, &query),
struct {
pub fn hash(_: @This(), _: []const u8) @TypeOf(query_hashed) {
return query_hashed;
}
pub fn eql(_: @This(), _: []const u8, b: []const u8) bool {
return strings.eqlComptime(b, &query);
}
}{},
);
}
};
pub const Entry = struct {
cache: Cache = .{},
dir: string,
base_: strings.StringOrTinyString,
// Necessary because the hash table uses it as a key
base_lowercase_: strings.StringOrTinyString,
mutex: Mutex,
need_stat: bool = true,
abs_path: PathString = PathString.empty,
pub inline fn base(this: *Entry) string {
return this.base_.slice();
}
pub inline fn base_lowercase(this: *Entry) string {
return this.base_lowercase_.slice();
}
pub const Lookup = struct {
entry: *Entry,
diff_case: ?DifferentCase,
pub const DifferentCase = struct {
dir: string,
query: string,
actual: string,
};
};
pub fn deinit(e: *Entry, allocator: std.mem.Allocator) void {
e.base_.deinit(allocator);
allocator.free(e.dir);
allocator.free(e.cache.symlink.slice());
allocator.destroy(e);
}
pub const Cache = struct {
symlink: PathString = PathString.empty,
/// Too much code expects this to be 0
/// don't make it bun.invalid_fd
fd: StoredFileDescriptorType = .zero,
kind: Kind = .file,
};
pub const Kind = enum {
dir,
file,
};
pub fn kind(entry: *Entry, fs: *Implementation, store_fd: bool) Kind {
if (entry.need_stat) {
entry.need_stat = false;
// This is technically incorrect, but we are choosing not to handle errors here
entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd, store_fd) catch return entry.cache.kind;
}
return entry.cache.kind;
}
pub fn symlink(entry: *Entry, fs: *Implementation, store_fd: bool) string {
if (entry.need_stat) {
entry.need_stat = false;
// This is technically incorrect, but we are choosing not to handle errors here
// This error can happen if the file was deleted between the time the directory was scanned and the time it was read
entry.cache = fs.kind(entry.dir, entry.base(), entry.cache.fd, store_fd) catch return "";
}
return entry.cache.symlink.slice();
}
};
// pub fn statBatch(fs: *FileSystemEntry, paths: []string) ![]?Stat {
// }
// pub fn stat(fs: *FileSystemEntry, path: string) !Stat {
// }
// pub fn readFile(fs: *FileSystemEntry, path: string) ?string {
// }
// pub fn readDir(fs: *FileSystemEntry, path: string) ?[]string {
// }
pub fn normalize(_: *@This(), str: string) string {
return @call(bun.callmod_inline, path_handler.normalizeString, .{ str, true, .auto });
}
pub fn normalizeBuf(_: *@This(), buf: []u8, str: string) string {
return @call(bun.callmod_inline, path_handler.normalizeStringBuf, .{ str, buf, false, .auto, false });
}
pub fn join(_: *@This(), parts: anytype) string {
return @call(bun.callmod_inline, path_handler.joinStringBuf, .{
&join_buf,
parts,
.loose,
});
}
pub fn joinBuf(_: *@This(), parts: anytype, buf: []u8) string {
return @call(bun.callmod_inline, path_handler.joinStringBuf, .{
buf,
parts,
.loose,
});
}
pub fn relative(_: *@This(), from: string, to: string) string {
return @call(bun.callmod_inline, path_handler.relative, .{
from,
to,
});
}
pub fn relativePlatform(_: *@This(), from: string, to: string, comptime platform: path_handler.Platform) string {
return @call(bun.callmod_inline, path_handler.relativePlatform, .{
from,
to,
platform,
false,
});
}
pub fn relativeTo(f: *@This(), to: string) string {
return @call(bun.callmod_inline, path_handler.relative, .{
f.top_level_dir,
to,
});
}
pub fn relativeFrom(f: *@This(), from: string) string {
return @call(bun.callmod_inline, path_handler.relative, .{
from,
f.top_level_dir,
});
}
pub fn absAlloc(f: *@This(), allocator: std.mem.Allocator, parts: anytype) !string {
const joined = path_handler.joinAbsString(
f.top_level_dir,
parts,
.loose,
);
return try allocator.dupe(u8, joined);
}
pub fn absAllocZ(f: *@This(), allocator: std.mem.Allocator, parts: anytype) ![*:0]const u8 {
const joined = path_handler.joinAbsString(
f.top_level_dir,
parts,
.loose,
);
return try allocator.dupeZ(u8, joined);
}
pub fn abs(f: *@This(), parts: anytype) string {
return path_handler.joinAbsString(
f.top_level_dir,
parts,
.loose,
);
}
pub fn absBuf(f: *@This(), parts: anytype, buf: []u8) string {
return path_handler.joinAbsStringBuf(f.top_level_dir, buf, parts, .loose);
}
pub fn absBufZ(f: *@This(), parts: anytype, buf: []u8) stringZ {
return path_handler.joinAbsStringBufZ(f.top_level_dir, buf, parts, .loose);
}
pub fn joinAlloc(f: *@This(), allocator: std.mem.Allocator, parts: anytype) !string {
const joined = f.join(parts);
return try allocator.dupe(u8, joined);
}
pub fn printLimits() void {
const LIMITS = [_]std.posix.rlimit_resource{ std.posix.rlimit_resource.STACK, std.posix.rlimit_resource.NOFILE };
Output.print("{{\n", .{});
inline for (LIMITS, 0..) |limit_type, i| {
const limit = std.posix.getrlimit(limit_type) catch return;
if (i == 0) {
Output.print(" \"stack\": [{d}, {d}],\n", .{ limit.cur, limit.max });
} else if (i == 1) {
Output.print(" \"files\": [{d}, {d}]\n", .{ limit.cur, limit.max });
}
}
Output.print("}}\n", .{});
Output.flush();
}
pub const RealFS = struct {
entries_mutex: Mutex = .{},
entries: *EntriesOption.Map,
cwd: string,
file_limit: usize = 32,
file_quota: usize = 32,
pub var win_tempdir_cache: ?[]const u8 = undefined;
pub fn platformTempDir() []const u8 {
return switch (Environment.os) {
// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-gettemppathw#remarks
.windows => win_tempdir_cache orelse {
const value = bun.getenvZ("TEMP") orelse bun.getenvZ("TMP") orelse brk: {
if (bun.getenvZ("SystemRoot") orelse bun.getenvZ("windir")) |windir| {
break :brk bun.fmt.allocPrint(
bun.default_allocator,
"{s}\\Temp",
.{strings.withoutTrailingSlash(windir)},
) catch bun.outOfMemory();
}
if (bun.getenvZ("USERPROFILE")) |profile| {
var buf: bun.PathBuffer = undefined;
var parts = [_]string{"AppData\\Local\\Temp"};
const out = bun.path.joinAbsStringBuf(profile, &buf, &parts, .loose);
break :brk bun.default_allocator.dupe(u8, out) catch bun.outOfMemory();
}
var tmp_buf: bun.PathBuffer = undefined;
const cwd = std.posix.getcwd(&tmp_buf) catch @panic("Failed to get cwd for platformTempDir");
const root = bun.path.windowsFilesystemRoot(cwd);
break :brk bun.fmt.allocPrint(
bun.default_allocator,
"{s}\\Windows\\Temp",
.{strings.withoutTrailingSlash(root)},
) catch bun.outOfMemory();
};
win_tempdir_cache = value;
return value;
},
.mac => "/private/tmp",
else => "/tmp",
};
}
pub const Tmpfile = switch (Environment.os) {
.windows => TmpfileWindows,
else => TmpfilePosix,
};
pub var tmpdir_path: []const u8 = undefined;
pub var tmpdir_path_set = false;
pub fn tmpdirPath(_: *const @This()) []const u8 {
if (!tmpdir_path_set) {
tmpdir_path = bun.getenvZ("BUN_TMPDIR") orelse bun.getenvZ("TMPDIR") orelse platformTempDir();
tmpdir_path_set = true;
}
return tmpdir_path;
}
pub fn openTmpDir(_: *const RealFS) !std.fs.Dir {
if (!tmpdir_path_set) {
tmpdir_path = bun.getenvZ("BUN_TMPDIR") orelse bun.getenvZ("TMPDIR") orelse platformTempDir();
tmpdir_path_set = true;
}
if (comptime Environment.isWindows) {
return (try bun.sys.openDirAtWindowsA(bun.invalid_fd, tmpdir_path, .{
.iterable = true,
// we will not delete the temp directory
.can_rename_or_delete = false,
.read_only = true,
}).unwrap()).asDir();
}
return try bun.openDirAbsolute(tmpdir_path);
}
pub fn entriesAt(this: *RealFS, index: allocators.IndexType, generation: bun.Generation) ?*EntriesOption {
var existing = this.entries.atIndex(index) orelse return null;
if (existing.* == .entries) {
if (existing.entries.generation < generation) {
var handle = bun.openDirForIteration(std.fs.cwd(), existing.entries.dir) catch |err| {
existing.entries.data.clearAndFree(bun.fs_allocator);
return this.readDirectoryError(existing.entries.dir, err) catch unreachable;
};
defer handle.close();
const new_entry = this.readdir(
false,
&existing.entries.data,
existing.entries.dir,
generation,
handle,
void,
void{},
) catch |err| {
existing.entries.data.clearAndFree(bun.fs_allocator);
return this.readDirectoryError(existing.entries.dir, err) catch unreachable;
};
existing.entries.data.clearAndFree(bun.fs_allocator);
existing.entries.* = new_entry;
}
}
return existing;
}
pub fn getDefaultTempDir() string {
return bun.getenvZ("BUN_TMPDIR") orelse bun.getenvZ("TMPDIR") orelse platformTempDir();
}
pub fn setTempdir(path: ?string) void {
tmpdir_path = path orelse getDefaultTempDir();
tmpdir_path_set = true;
}
pub const TmpfilePosix = struct {
fd: bun.FileDescriptor = bun.invalid_fd,
dir_fd: bun.FileDescriptor = bun.invalid_fd,
pub inline fn dir(this: *TmpfilePosix) std.fs.Dir {
return this.dir_fd.asDir();
}
pub inline fn file(this: *TmpfilePosix) std.fs.File {
return this.fd.asFile();
}
pub fn close(this: *TmpfilePosix) void {
if (this.fd != bun.invalid_fd) _ = bun.sys.close(this.fd);
}
pub fn create(this: *TmpfilePosix, _: *RealFS, name: [:0]const u8) !void {
// We originally used a temporary directory, but it caused EXDEV.
const dir_fd = std.fs.cwd().fd;
const flags = bun.O.CREAT | bun.O.RDWR | bun.O.CLOEXEC;
this.dir_fd = bun.toFD(dir_fd);
const result = try bun.sys.openat(bun.toFD(dir_fd), name, flags, std.posix.S.IRWXU).unwrap();
this.fd = bun.toFD(result);
}
pub fn promoteToCWD(this: *TmpfilePosix, from_name: [*:0]const u8, name: [*:0]const u8) !void {
bun.assert(this.fd != bun.invalid_fd);
bun.assert(this.dir_fd != bun.invalid_fd);
try C.moveFileZWithHandle(this.fd, this.dir_fd, bun.sliceTo(from_name, 0), bun.FD.cwd(), bun.sliceTo(name, 0));
this.close();
}
pub fn closeAndDelete(this: *TmpfilePosix, name: [*:0]const u8) void {
this.close();
if (comptime !Environment.isLinux) {
if (this.dir_fd == bun.invalid_fd) return;
this.dir().deleteFileZ(name) catch {};
}
}
};
pub const TmpfileWindows = struct {
fd: bun.FileDescriptor = bun.invalid_fd,
existing_path: []const u8 = "",
pub inline fn dir(_: *TmpfileWindows) std.fs.Dir {
return Fs.FileSystem.instance.tmpdir();
}
pub inline fn file(this: *TmpfileWindows) std.fs.File {
return this.fd.asFile();
}
pub fn close(this: *TmpfileWindows) void {
if (this.fd != bun.invalid_fd) _ = bun.sys.close(this.fd);
}
pub fn create(this: *TmpfileWindows, rfs: *RealFS, name: [:0]const u8) !void {
const tmpdir_ = try rfs.openTmpDir();
const flags = bun.O.CREAT | bun.O.WRONLY | bun.O.CLOEXEC;
this.fd = try bun.sys.openat(bun.toFD(tmpdir_.fd), name, flags, 0).unwrap();
var buf: bun.PathBuffer = undefined;
const existing_path = try bun.getFdPath(this.fd, &buf);
this.existing_path = try bun.default_allocator.dupe(u8, existing_path);
}
pub fn promoteToCWD(this: *TmpfileWindows, from_name: [*:0]const u8, name: [:0]const u8) !void {
_ = from_name;
var existing_buf: bun.WPathBuffer = undefined;
var new_buf: bun.WPathBuffer = undefined;
this.close();
const existing = bun.strings.toExtendedPathNormalized(&new_buf, this.existing_path);
const new = if (std.fs.path.isAbsoluteWindows(name))
bun.strings.toExtendedPathNormalized(&existing_buf, name)
else
bun.strings.toWPathNormalized(&existing_buf, name);
if (comptime Environment.allow_assert) {
debug("moveFileExW({s}, {s})", .{ bun.fmt.utf16(existing), bun.fmt.utf16(new) });
}
if (bun.windows.kernel32.MoveFileExW(existing.ptr, new.ptr, bun.windows.MOVEFILE_COPY_ALLOWED | bun.windows.MOVEFILE_REPLACE_EXISTING | bun.windows.MOVEFILE_WRITE_THROUGH) == bun.windows.FALSE) {
try bun.windows.Win32Error.get().unwrap();
}
}
pub fn closeAndDelete(this: *TmpfileWindows, name: [*:0]const u8) void {
_ = name;
this.close();
}
};
pub fn needToCloseFiles(rfs: *const RealFS) bool {
if (!FeatureFlags.store_file_descriptors) {
return true;
}
if (Environment.isWindows) {
// 'false' is okay here because windows gives you a seemingly unlimited number of open
// file handles, while posix has a lower limit.
//
// This limit does not extend to the C-Runtime which is only 512 to 8196 or so,
// but we know that all resolver-related handles are not C-Runtime handles because
// `setMaxFd` on Windows (besides being a no-op) only takes in `HANDLE`.
//
// Handles are automatically closed when the process exits as stated here:
// https://learn.microsoft.com/en-us/windows/win32/procthread/terminating-a-process
// But in a crazy experiment to find the upper-bound of the number of open handles,
// I found that opening upwards of 500k to a million handles in a single process
// would cause the process to hang while closing. This might just be Windows slowly
// closing the handles, not sure. This is likely not something to worry about.
//
// If it is decided that not closing files ever is a bad idea. This should be
// replaced with some form of intelligent count of how many files we opened.
// On POSIX we can get away with measuring how high `fd` gets because it typically
// assigns these descriptors in ascending order (1 2 3 ...). Windows does not
// guarantee this.
return false;
}
// If we're not near the max amount of open files, don't worry about it.
return !(rfs.file_limit > 254 and rfs.file_limit > (FileSystem.max_fd + 1) * 2);
}
/// Returns `true` if an entry was removed
pub fn bustEntriesCache(rfs: *RealFS, file_path: string) bool {
return rfs.entries.remove(file_path);
}
pub const Limit = struct {
pub var handles: usize = 0;
pub var stack: usize = 0;
};
// Always try to max out how many files we can keep open
pub fn adjustUlimit() !usize {
if (comptime !Environment.isPosix) {
return std.math.maxInt(usize);
}
const LIMITS = [_]std.posix.rlimit_resource{ std.posix.rlimit_resource.STACK, std.posix.rlimit_resource.NOFILE };
inline for (LIMITS, 0..) |limit_type, i| {
const limit = try std.posix.getrlimit(limit_type);
if (limit.cur < limit.max) {
var new_limit = std.mem.zeroes(std.posix.rlimit);
new_limit.cur = limit.max;
new_limit.max = limit.max;
if (std.posix.setrlimit(limit_type, new_limit)) {
if (i == 1) {
Limit.handles = limit.max;
} else {
Limit.stack = limit.max;
}
} else |_| {}
}
if (i == LIMITS.len - 1) return limit.max;
}
}
var _entries_option_map: *EntriesOption.Map = undefined;
var _entries_option_map_loaded: bool = false;
pub fn init(
cwd: string,
) RealFS {
const file_limit = adjustUlimit() catch unreachable;
if (!_entries_option_map_loaded) {
_entries_option_map = EntriesOption.Map.init(bun.fs_allocator);
_entries_option_map_loaded = true;
}
return RealFS{
.entries = _entries_option_map,
.cwd = cwd,
.file_limit = file_limit,
.file_quota = file_limit,
};
}
pub const ModKeyError = error{
Unusable,
};
pub const ModKey = struct {
inode: std.fs.File.INode = 0,
size: u64 = 0,
mtime: i128 = 0,
mode: std.fs.File.Mode = 0,
threadlocal var hash_name_buf: [1024]u8 = undefined;
pub fn hashName(
this: *const ModKey,
basename: string,
) !string {
const hex_int = this.hash();
return try std.fmt.bufPrint(
&hash_name_buf,
"{s}-{any}",
.{
basename,
bun.fmt.hexIntLower(hex_int),
},
);
}
pub fn hash(
this: *const ModKey,
) u64 {
var hash_bytes: [32]u8 = undefined;
// We shouldn't just read the contents of the ModKey into memory
// The hash should be deterministic across computers and operating systems.
// inode is non-deterministic across volumes within the same compuiter
// so if we're not going to do a full content hash, we should use mtime and size.
// even mtime is debatable.
var hash_bytes_remain: []u8 = hash_bytes[0..];
std.mem.writeInt(@TypeOf(this.size), hash_bytes_remain[0..@sizeOf(@TypeOf(this.size))], this.size, .little);
hash_bytes_remain = hash_bytes_remain[@sizeOf(@TypeOf(this.size))..];
std.mem.writeInt(@TypeOf(this.mtime), hash_bytes_remain[0..@sizeOf(@TypeOf(this.mtime))], this.mtime, .little);
hash_bytes_remain = hash_bytes_remain[@sizeOf(@TypeOf(this.mtime))..];
bun.assert(hash_bytes_remain.len == 8);
hash_bytes_remain[0..8].* = @as([8]u8, @bitCast(@as(u64, 0)));
return bun.hash(&hash_bytes);
}
pub fn generate(_: *RealFS, _: string, file: std.fs.File) anyerror!ModKey {
const stat = try file.stat();
const seconds = @divTrunc(stat.mtime, @as(@TypeOf(stat.mtime), std.time.ns_per_s));
// We can't detect changes if the file system zeros out the modification time
if (seconds == 0 and std.time.ns_per_s == 0) {
return error.Unusable;
}
// Don't generate a modification key if the file is too new
const now = std.time.nanoTimestamp();
const now_seconds = @divTrunc(now, std.time.ns_per_s);
if (seconds > seconds or (seconds == now_seconds and stat.mtime > now)) {
return error.Unusable;
}
return ModKey{
.inode = stat.inode,
.size = stat.size,
.mtime = stat.mtime,
.mode = stat.mode,
// .uid = stat.
};
}
pub const SafetyGap = 3;
};
pub fn modKeyWithFile(fs: *RealFS, path: string, file: anytype) anyerror!ModKey {
return try ModKey.generate(fs, path, file);
}
pub fn modKey(fs: *RealFS, path: string) anyerror!ModKey {
var file = try std.fs.openFileAbsolute(path, std.fs.File.OpenFlags{ .mode = .read_only });
defer {
if (fs.needToCloseFiles()) {
file.close();
}
}
return try fs.modKeyWithFile(path, file);
}
pub const EntriesOption = union(Tag) {
entries: *DirEntry,
err: DirEntry.Err,
pub const Tag = enum {
entries,
err,
};
// This custom map implementation:
// - Preallocates a fixed amount of directory name space
// - Doesn't store directory names which don't exist.
pub const Map = allocators.BSSMap(EntriesOption, Preallocate.Counts.dir_entry, false, 256, true);
};
pub fn openDir(_: *RealFS, unsafe_dir_string: string) !std.fs.Dir {
const dirfd = if (Environment.isWindows)
bun.sys.openDirAtWindowsA(bun.invalid_fd, unsafe_dir_string, .{ .iterable = true, .no_follow = false, .read_only = true })
else
bun.sys.openA(
unsafe_dir_string,
bun.O.DIRECTORY,
0,
);
const fd = try dirfd.unwrap();
return fd.asDir();
}
fn readdir(
fs: *RealFS,
store_fd: bool,
prev_map: ?*DirEntry.EntryMap,
_dir: string,
generation: bun.Generation,
handle: std.fs.Dir,
comptime Iterator: type,
iterator: Iterator,
) !DirEntry {
_ = fs;
var iter = bun.iterateDir(handle);
var dir = DirEntry.init(_dir, generation);
const allocator = bun.fs_allocator;
errdefer dir.deinit(allocator);
if (store_fd) {
FileSystem.setMaxFd(handle.fd);
dir.fd = bun.toFD(handle.fd);
}
while (try iter.next().unwrap()) |*_entry| {
debug("readdir entry {s}", .{_entry.name.slice()});
try dir.addEntry(prev_map, _entry, allocator, Iterator, iterator);
}
debug("readdir({d}, {s}) = {d}", .{ handle.fd, _dir, dir.data.count() });
return dir;
}
fn readDirectoryError(fs: *RealFS, dir: string, err: anyerror) OOM!*EntriesOption {
if (comptime FeatureFlags.enable_entry_cache) {
var get_or_put_result = try fs.entries.getOrPut(dir);
const opt = try fs.entries.put(&get_or_put_result, EntriesOption{
.err = DirEntry.Err{ .original_err = err, .canonical_error = err },
});
return opt;
}