forked from google/gvisor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sys_file.go
1942 lines (1663 loc) · 56.4 KB
/
sys_file.go
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
// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package linux
import (
"io"
"syscall"
"gvisor.googlesource.com/gvisor/pkg/abi/linux"
"gvisor.googlesource.com/gvisor/pkg/sentry/arch"
"gvisor.googlesource.com/gvisor/pkg/sentry/context"
"gvisor.googlesource.com/gvisor/pkg/sentry/fs"
"gvisor.googlesource.com/gvisor/pkg/sentry/fs/lock"
"gvisor.googlesource.com/gvisor/pkg/sentry/kernel"
"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/auth"
"gvisor.googlesource.com/gvisor/pkg/sentry/kernel/kdefs"
ktime "gvisor.googlesource.com/gvisor/pkg/sentry/kernel/time"
"gvisor.googlesource.com/gvisor/pkg/sentry/limits"
"gvisor.googlesource.com/gvisor/pkg/sentry/usermem"
"gvisor.googlesource.com/gvisor/pkg/syserror"
)
// fileOpAt performs an operation on the second last component in the path.
func fileOpAt(t *kernel.Task, dirFD kdefs.FD, path string, fn func(root *fs.Dirent, d *fs.Dirent, name string) error) error {
// Extract the last component.
dir, name := fs.SplitLast(path)
if dir == "/" {
// Common case: we are accessing a file in the root.
root := t.FSContext().RootDirectory()
err := fn(root, root, name)
root.DecRef()
return err
} else if dir == "." && dirFD == linux.AT_FDCWD {
// Common case: we are accessing a file relative to the current
// working directory; skip the look-up.
wd := t.FSContext().WorkingDirectory()
root := t.FSContext().RootDirectory()
err := fn(root, wd, name)
wd.DecRef()
root.DecRef()
return err
}
return fileOpOn(t, dirFD, dir, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent) error {
return fn(root, d, name)
})
}
// fileOpOn performs an operation on the last entry of the path.
func fileOpOn(t *kernel.Task, dirFD kdefs.FD, path string, resolve bool, fn func(root *fs.Dirent, d *fs.Dirent) error) error {
var (
d *fs.Dirent // The file.
wd *fs.Dirent // The working directory (if required.)
rel *fs.Dirent // The relative directory for search (if required.)
f *fs.File // The file corresponding to dirFD (if required.)
err error
)
// Extract the working directory (maybe).
if len(path) > 0 && path[0] == '/' {
// Absolute path; rel can be nil.
} else if dirFD == linux.AT_FDCWD {
// Need to reference the working directory.
wd = t.FSContext().WorkingDirectory()
rel = wd
} else {
// Need to extract the given FD.
f = t.FDMap().GetFile(dirFD)
if f == nil {
return syserror.EBADF
}
rel = f.Dirent
if !fs.IsDir(rel.Inode.StableAttr) {
return syserror.ENOTDIR
}
}
// Grab the root (always required.)
root := t.FSContext().RootDirectory()
// Lookup the node.
if resolve {
d, err = t.MountNamespace().FindInode(t, root, rel, path, linux.MaxSymlinkTraversals)
} else {
d, err = t.MountNamespace().FindLink(t, root, rel, path, linux.MaxSymlinkTraversals)
}
root.DecRef()
if wd != nil {
wd.DecRef()
}
if f != nil {
f.DecRef()
}
if err != nil {
return err
}
err = fn(root, d)
d.DecRef()
return err
}
// copyInPath copies a path in.
func copyInPath(t *kernel.Task, addr usermem.Addr, allowEmpty bool) (path string, dirPath bool, err error) {
path, err = t.CopyInString(addr, syscall.PathMax)
if err != nil {
return "", false, err
}
if path == "" && !allowEmpty {
return "", false, syserror.ENOENT
}
// If the path ends with a /, then checks must be enforced in various
// ways in the different callers. We pass this back to the caller.
path, dirPath = fs.TrimTrailingSlashes(path)
return path, dirPath, nil
}
func openAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr, flags uint) (fd uintptr, err error) {
path, dirPath, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return 0, err
}
err = fileOpOn(t, dirFD, path, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent) error {
// First check a few things about the filesystem before trying to get the file
// reference.
//
// It's required that Check does not try to open files not that aren't backed by
// this dirent (e.g. pipes and sockets) because this would result in opening these
// files an extra time just to check permissions.
if err := d.Inode.CheckPermission(t, flagsToPermissions(flags)); err != nil {
return err
}
fileFlags := linuxToFlags(flags)
isDir := fs.IsDir(d.Inode.StableAttr)
// If O_DIRECTORY is set, but the file is not a directory, then fail.
if fileFlags.Directory && !isDir {
return syserror.ENOTDIR
}
// If it's a directory, then make sure.
if dirPath && !isDir {
return syserror.ENOTDIR
}
// Don't allow directories to be opened writable.
if isDir && fileFlags.Write {
return syserror.EISDIR
}
file, err := d.Inode.GetFile(t, d, fileFlags)
if err != nil {
return syserror.ConvertIntr(err, kernel.ERESTARTSYS)
}
defer file.DecRef()
// Success.
fdFlags := kernel.FDFlags{CloseOnExec: flags&syscall.O_CLOEXEC != 0}
newFD, err := t.FDMap().NewFDFrom(0, file, fdFlags, t.ThreadGroup().Limits())
if err != nil {
return err
}
// Set return result in frame.
fd = uintptr(newFD)
// Generate notification for opened file.
d.InotifyEvent(linux.IN_OPEN, 0)
return nil
})
return fd, err // Use result in frame.
}
func mknodAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr, mode linux.FileMode) error {
path, dirPath, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return err
}
if dirPath {
return syserror.ENOENT
}
return fileOpAt(t, dirFD, path, func(root *fs.Dirent, d *fs.Dirent, name string) error {
if !fs.IsDir(d.Inode.StableAttr) {
return syserror.ENOTDIR
}
// Do we have the appropriate permissions on the parent?
if err := d.Inode.CheckPermission(t, fs.PermMask{Write: true, Execute: true}); err != nil {
return err
}
// Attempt a creation.
perms := fs.FilePermsFromMode(mode &^ linux.FileMode(t.FSContext().Umask()))
switch mode.FileType() {
case 0:
// "Zero file type is equivalent to type S_IFREG." - mknod(2)
fallthrough
case linux.ModeRegular:
// We are not going to return the file, so the actual
// flags used don't matter, but they cannot be empty or
// Create will complain.
flags := fs.FileFlags{Read: true, Write: true}
file, err := d.Create(t, root, name, flags, perms)
if err != nil {
return err
}
file.DecRef()
return nil
case linux.ModeNamedPipe:
return d.CreateFifo(t, root, name, perms)
case linux.ModeSocket:
// While it is possible create a unix domain socket file on linux
// using mknod(2), in practice this is pretty useless from an
// application. Linux internally uses mknod() to create the socket
// node during bind(2), but we implement bind(2) independently. If
// an application explicitly creates a socket node using mknod(),
// you can't seem to bind() or connect() to the resulting socket.
//
// Instead of emulating this seemingly useless behaviour, we'll
// indicate that the filesystem doesn't support the creation of
// sockets.
return syserror.EOPNOTSUPP
case linux.ModeCharacterDevice:
fallthrough
case linux.ModeBlockDevice:
// TODO: We don't support creating block or character
// devices at the moment.
//
// When we start supporting block and character devices, we'll
// need to check for CAP_MKNOD here.
return syserror.EPERM
default:
// "EINVAL - mode requested creation of something other than a
// regular file, device special file, FIFO or socket." - mknod(2)
return syserror.EINVAL
}
})
}
// Mknod implements the linux syscall mknod(2).
func Mknod(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
path := args[0].Pointer()
mode := linux.FileMode(args[1].ModeT())
// We don't need this argument until we support creation of device nodes.
_ = args[2].Uint() // dev
return 0, nil, mknodAt(t, linux.AT_FDCWD, path, mode)
}
// Mknodat implements the linux syscall mknodat(2).
func Mknodat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
dirFD := kdefs.FD(args[0].Int())
path := args[1].Pointer()
mode := linux.FileMode(args[2].ModeT())
// We don't need this argument until we support creation of device nodes.
_ = args[3].Uint() // dev
return 0, nil, mknodAt(t, dirFD, path, mode)
}
func createAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr, flags uint, mode linux.FileMode) (fd uintptr, err error) {
path, dirPath, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return 0, err
}
if dirPath {
return 0, syserror.ENOENT
}
err = fileOpAt(t, dirFD, path, func(root *fs.Dirent, d *fs.Dirent, name string) error {
if !fs.IsDir(d.Inode.StableAttr) {
return syserror.ENOTDIR
}
// Does this file exist already?
targetDirent, err := t.MountNamespace().FindInode(t, root, d, name, linux.MaxSymlinkTraversals)
var newFile *fs.File
switch err {
case nil:
// The file existed.
defer targetDirent.DecRef()
// Check if we wanted to create.
if flags&syscall.O_EXCL != 0 {
return syserror.EEXIST
}
// Like sys_open, check for a few things about the
// filesystem before trying to get a reference to the
// fs.File. The same constraints on Check apply.
if err := targetDirent.Inode.CheckPermission(t, flagsToPermissions(flags)); err != nil {
return err
}
// Should we truncate the file?
if flags&syscall.O_TRUNC != 0 {
if err := targetDirent.Inode.Truncate(t, targetDirent, 0); err != nil {
return err
}
}
// Create a new fs.File.
newFile, err = targetDirent.Inode.GetFile(t, targetDirent, linuxToFlags(flags))
if err != nil {
return syserror.ConvertIntr(err, kernel.ERESTARTSYS)
}
defer newFile.DecRef()
case syserror.EACCES:
// Permission denied while walking to the file.
return err
default:
// Do we have write permissions on the parent?
if err := d.Inode.CheckPermission(t, fs.PermMask{Write: true, Execute: true}); err != nil {
return err
}
// Attempt a creation.
perms := fs.FilePermsFromMode(mode &^ linux.FileMode(t.FSContext().Umask()))
newFile, err = d.Create(t, root, name, linuxToFlags(flags), perms)
if err != nil {
// No luck, bail.
return err
}
defer newFile.DecRef()
targetDirent = newFile.Dirent
}
// Success.
fdFlags := kernel.FDFlags{CloseOnExec: flags&syscall.O_CLOEXEC != 0}
newFD, err := t.FDMap().NewFDFrom(0, newFile, fdFlags, t.ThreadGroup().Limits())
if err != nil {
return err
}
// Set result in frame.
fd = uintptr(newFD)
// Queue the open inotify event. The creation event is
// automatically queued when the dirent is targetDirent. The
// open events are implemented at the syscall layer so we need
// to manually queue one here.
targetDirent.InotifyEvent(linux.IN_OPEN, 0)
return nil
})
return fd, err // Use result in frame.
}
// Open implements linux syscall open(2).
func Open(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
flags := uint(args[1].Uint())
if flags&syscall.O_CREAT != 0 {
mode := linux.FileMode(args[2].ModeT())
n, err := createAt(t, linux.AT_FDCWD, addr, flags, mode)
return n, nil, err
}
n, err := openAt(t, linux.AT_FDCWD, addr, flags)
return n, nil, err
}
// Openat implements linux syscall openat(2).
func Openat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
dirFD := kdefs.FD(args[0].Int())
addr := args[1].Pointer()
flags := uint(args[2].Uint())
if flags&syscall.O_CREAT != 0 {
mode := linux.FileMode(args[3].ModeT())
n, err := createAt(t, dirFD, addr, flags, mode)
return n, nil, err
}
n, err := openAt(t, dirFD, addr, flags)
return n, nil, err
}
// Creat implements linux syscall creat(2).
func Creat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
mode := linux.FileMode(args[1].ModeT())
n, err := createAt(t, linux.AT_FDCWD, addr, syscall.O_WRONLY|syscall.O_TRUNC, mode)
return n, nil, err
}
// accessContext is a context that overrides the credentials used, but
// otherwise carries the same values as the embedded context.
//
// accessContext should only be used for access(2).
type accessContext struct {
context.Context
creds auth.Credentials
}
// Value implements context.Context.
func (ac accessContext) Value(key interface{}) interface{} {
switch key {
case auth.CtxCredentials:
return &ac.creds
default:
return ac.Context.Value(key)
}
}
func accessAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr, resolve bool, mode uint) error {
const rOK = 4
const wOK = 2
const xOK = 1
path, _, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return err
}
// Sanity check the mode.
if mode&^(rOK|wOK|xOK) != 0 {
return syserror.EINVAL
}
return fileOpOn(t, dirFD, path, resolve, func(root *fs.Dirent, d *fs.Dirent) error {
// access(2) and faccessat(2) check permissions using real
// UID/GID, not effective UID/GID.
//
// "access() needs to use the real uid/gid, not the effective
// uid/gid. We do this by temporarily clearing all FS-related
// capabilities and switching the fsuid/fsgid around to the
// real ones." -fs/open.c:faccessat
creds := t.Credentials()
creds.EffectiveKUID = creds.RealKUID
creds.EffectiveKGID = creds.RealKGID
if creds.EffectiveKUID.In(creds.UserNamespace) == auth.RootUID {
creds.EffectiveCaps = creds.PermittedCaps
} else {
creds.EffectiveCaps = 0
}
ctx := &accessContext{
Context: t,
creds: creds,
}
if err := d.Inode.CheckPermission(ctx, fs.PermMask{
Read: mode&rOK != 0,
Write: mode&wOK != 0,
Execute: mode&xOK != 0,
}); err != nil {
return err
}
return nil
})
}
// Access implements linux syscall access(2).
func Access(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
mode := args[1].ModeT()
return 0, nil, accessAt(t, linux.AT_FDCWD, addr, true, mode)
}
// Faccessat implements linux syscall faccessat(2).
func Faccessat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
dirFD := kdefs.FD(args[0].Int())
addr := args[1].Pointer()
mode := args[2].ModeT()
flags := args[3].Int()
return 0, nil, accessAt(t, dirFD, addr, flags&linux.AT_SYMLINK_NOFOLLOW == 0, mode)
}
// Ioctl implements linux syscall ioctl(2).
func Ioctl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
fd := kdefs.FD(args[0].Int())
request := int(args[1].Int())
file := t.FDMap().GetFile(fd)
if file == nil {
return 0, nil, syserror.EBADF
}
defer file.DecRef()
// Shared flags between file and socket.
switch request {
case linux.FIONCLEX:
t.FDMap().SetFlags(fd, kernel.FDFlags{
CloseOnExec: false,
})
return 0, nil, nil
case linux.FIOCLEX:
t.FDMap().SetFlags(fd, kernel.FDFlags{
CloseOnExec: true,
})
return 0, nil, nil
case linux.FIONBIO:
var set int32
if _, err := t.CopyIn(args[2].Pointer(), &set); err != nil {
return 0, nil, err
}
flags := file.Flags()
if set != 0 {
flags.NonBlocking = true
} else {
flags.NonBlocking = false
}
file.SetFlags(flags.Settable())
return 0, nil, nil
default:
ret, err := file.FileOperations.Ioctl(t, t.MemoryManager(), args)
if err != nil {
return 0, nil, err
}
return ret, nil, nil
}
}
// Getcwd implements the linux syscall getcwd(2).
func Getcwd(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
size := args[1].SizeT()
cwd := t.FSContext().WorkingDirectory()
defer cwd.DecRef()
root := t.FSContext().RootDirectory()
defer root.DecRef()
// Get our fullname from the root and preprend unreachable if the root was
// unreachable from our current dirent this is the same behavior as on linux.
s, reachable := cwd.FullName(root)
if !reachable {
s = "(unreachable)" + s
}
// Note this is >= because we need a terminator.
if uint(len(s)) >= size {
return 0, nil, syserror.ERANGE
}
// Copy out the path name for the node.
bytes, err := t.CopyOutBytes(addr, []byte(s))
if err != nil {
return 0, nil, err
}
// Top it off with a terminator.
_, err = t.CopyOut(addr+usermem.Addr(bytes), []byte("\x00"))
return uintptr(bytes + 1), nil, err
}
// Chroot implements the linux syscall chroot(2).
func Chroot(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
if !t.HasCapability(linux.CAP_SYS_CHROOT) {
return 0, nil, syserror.EPERM
}
path, _, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return 0, nil, err
}
return 0, nil, fileOpOn(t, linux.AT_FDCWD, path, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent) error {
// Is it a directory?
if !fs.IsDir(d.Inode.StableAttr) {
return syserror.ENOTDIR
}
// Does it have execute permissions?
if err := d.Inode.CheckPermission(t, fs.PermMask{Execute: true}); err != nil {
return err
}
t.FSContext().SetRootDirectory(d)
return nil
})
}
// Chdir implements the linux syscall chdir(2).
func Chdir(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
path, _, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return 0, nil, err
}
return 0, nil, fileOpOn(t, linux.AT_FDCWD, path, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent) error {
// Is it a directory?
if !fs.IsDir(d.Inode.StableAttr) {
return syserror.ENOTDIR
}
// Does it have execute permissions?
if err := d.Inode.CheckPermission(t, fs.PermMask{Execute: true}); err != nil {
return err
}
t.FSContext().SetWorkingDirectory(d)
return nil
})
}
// Fchdir implements the linux syscall fchdir(2).
func Fchdir(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
fd := kdefs.FD(args[0].Int())
file := t.FDMap().GetFile(fd)
if file == nil {
return 0, nil, syserror.EBADF
}
defer file.DecRef()
// Is it a directory?
if !fs.IsDir(file.Dirent.Inode.StableAttr) {
return 0, nil, syserror.ENOTDIR
}
// Does it have execute permissions?
if err := file.Dirent.Inode.CheckPermission(t, fs.PermMask{Execute: true}); err != nil {
return 0, nil, err
}
t.FSContext().SetWorkingDirectory(file.Dirent)
return 0, nil, nil
}
// Close implements linux syscall close(2).
func Close(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
fd := kdefs.FD(args[0].Int())
file, ok := t.FDMap().Remove(fd)
if !ok {
return 0, nil, syserror.EBADF
}
defer file.DecRef()
err := file.Flush(t)
return 0, nil, handleIOError(t, false /* partial */, err, syscall.EINTR, "close", file)
}
// Dup implements linux syscall dup(2).
func Dup(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
fd := kdefs.FD(args[0].Int())
file := t.FDMap().GetFile(fd)
if file == nil {
return 0, nil, syserror.EBADF
}
defer file.DecRef()
newfd, err := t.FDMap().NewFDFrom(0, file, kernel.FDFlags{}, t.ThreadGroup().Limits())
if err != nil {
return 0, nil, syserror.EMFILE
}
return uintptr(newfd), nil, nil
}
// Dup2 implements linux syscall dup2(2).
func Dup2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
oldfd := kdefs.FD(args[0].Int())
newfd := kdefs.FD(args[1].Int())
// If oldfd is a valid file descriptor, and newfd has the same value as oldfd,
// then dup2() does nothing, and returns newfd.
if oldfd == newfd {
oldFile := t.FDMap().GetFile(oldfd)
if oldFile == nil {
return 0, nil, syserror.EBADF
}
defer oldFile.DecRef()
return uintptr(newfd), nil, nil
}
// Zero out flags arg to be used by Dup3.
args[2].Value = 0
return Dup3(t, args)
}
// Dup3 implements linux syscall dup3(2).
func Dup3(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
oldfd := kdefs.FD(args[0].Int())
newfd := kdefs.FD(args[1].Int())
flags := args[2].Uint()
if oldfd == newfd {
return 0, nil, syserror.EINVAL
}
oldFile := t.FDMap().GetFile(oldfd)
if oldFile == nil {
return 0, nil, syserror.EBADF
}
defer oldFile.DecRef()
err := t.FDMap().NewFDAt(newfd, oldFile, kernel.FDFlags{CloseOnExec: flags&syscall.O_CLOEXEC != 0}, t.ThreadGroup().Limits())
if err != nil {
return 0, nil, err
}
return uintptr(newfd), nil, nil
}
// Fcntl implements linux syscall fcntl(2).
func Fcntl(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
fd := kdefs.FD(args[0].Int())
cmd := args[1].Int()
file, flags := t.FDMap().GetDescriptor(fd)
if file == nil {
return 0, nil, syserror.EBADF
}
defer file.DecRef()
switch cmd {
case syscall.F_DUPFD, syscall.F_DUPFD_CLOEXEC:
from := kdefs.FD(args[2].Int())
fdFlags := kernel.FDFlags{CloseOnExec: cmd == syscall.F_DUPFD_CLOEXEC}
fd, err := t.FDMap().NewFDFrom(from, file, fdFlags, t.ThreadGroup().Limits())
if err != nil {
return 0, nil, err
}
return uintptr(fd), nil, nil
case syscall.F_GETFD:
return uintptr(fdFlagsToLinux(flags)), nil, nil
case syscall.F_SETFD:
flags := args[2].Uint()
t.FDMap().SetFlags(fd, kernel.FDFlags{
CloseOnExec: flags&syscall.FD_CLOEXEC != 0,
})
case syscall.F_GETFL:
return uintptr(flagsToLinux(file.Flags())), nil, nil
case syscall.F_SETFL:
flags := uint(args[2].Uint())
file.SetFlags(linuxToSettableFlags(flags))
case syscall.F_SETLK, syscall.F_SETLKW:
// In Linux the file system can choose to provide lock operations for an inode.
// Normally pipe and socket types lack lock operations. We diverge and use a heavy
// hammer by only allowing locks on files and directories.
if !fs.IsFile(file.Dirent.Inode.StableAttr) && !fs.IsDir(file.Dirent.Inode.StableAttr) {
return 0, nil, syserror.EBADF
}
// Copy in the lock request.
flockAddr := args[2].Pointer()
var flock syscall.Flock_t
if _, err := t.CopyIn(flockAddr, &flock); err != nil {
return 0, nil, err
}
// Compute the lock whence.
var sw fs.SeekWhence
switch flock.Whence {
case 0:
sw = fs.SeekSet
case 1:
sw = fs.SeekCurrent
case 2:
sw = fs.SeekEnd
default:
return 0, nil, syserror.EINVAL
}
// Compute the lock offset.
var off int64
switch sw {
case fs.SeekSet:
off = 0
case fs.SeekCurrent:
// Note that Linux does not hold any mutexes while retrieving the file offset,
// see fs/locks.c:flock_to_posix_lock and fs/locks.c:fcntl_setlk.
off = file.Offset()
case fs.SeekEnd:
uattr, err := file.Dirent.Inode.UnstableAttr(t)
if err != nil {
return 0, nil, err
}
off = uattr.Size
default:
return 0, nil, syserror.EINVAL
}
// Compute the lock range.
rng, err := lock.ComputeRange(flock.Start, flock.Len, off)
if err != nil {
return 0, nil, err
}
// The lock uid is that of the Task's FDMap.
lockUniqueID := lock.UniqueID(t.FDMap().ID())
// These locks don't block; execute the non-blocking operation using the inode's lock
// context directly.
switch flock.Type {
case syscall.F_RDLCK:
if !file.Flags().Read {
return 0, nil, syserror.EBADF
}
if cmd == syscall.F_SETLK {
// Non-blocking lock, provide a nil lock.Blocker.
if !file.Dirent.Inode.LockCtx.Posix.LockRegion(lockUniqueID, lock.ReadLock, rng, nil) {
return 0, nil, syserror.EAGAIN
}
} else {
// Blocking lock, pass in the task to satisfy the lock.Blocker interface.
if !file.Dirent.Inode.LockCtx.Posix.LockRegion(lockUniqueID, lock.ReadLock, rng, t) {
return 0, nil, syserror.EINTR
}
}
return 0, nil, nil
case syscall.F_WRLCK:
if !file.Flags().Write {
return 0, nil, syserror.EBADF
}
if cmd == syscall.F_SETLK {
// Non-blocking lock, provide a nil lock.Blocker.
if !file.Dirent.Inode.LockCtx.Posix.LockRegion(lockUniqueID, lock.WriteLock, rng, nil) {
return 0, nil, syserror.EAGAIN
}
} else {
// Blocking lock, pass in the task to satisfy the lock.Blocker interface.
if !file.Dirent.Inode.LockCtx.Posix.LockRegion(lockUniqueID, lock.WriteLock, rng, t) {
return 0, nil, syserror.EINTR
}
}
return 0, nil, nil
case syscall.F_UNLCK:
file.Dirent.Inode.LockCtx.Posix.UnlockRegion(lockUniqueID, rng)
return 0, nil, nil
default:
return 0, nil, syserror.EINVAL
}
default:
// Everything else is not yet supported.
return 0, nil, syserror.EINVAL
}
return 0, nil, nil
}
const (
_FADV_NORMAL = 0
_FADV_RANDOM = 1
_FADV_SEQUENTIAL = 2
_FADV_WILLNEED = 3
_FADV_DONTNEED = 4
_FADV_NOREUSE = 5
)
// Fadvise64 implements linux syscall fadvise64(2).
// This implementation currently ignores the provided advice.
func Fadvise64(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
fd := kdefs.FD(args[0].Int())
offset := args[1].Int64()
length := args[2].Uint()
advice := args[3].Int()
if offset < 0 || length < 0 {
return 0, nil, syserror.EINVAL
}
file := t.FDMap().GetFile(fd)
if file == nil {
return 0, nil, syserror.EBADF
}
defer file.DecRef()
switch advice {
case _FADV_NORMAL:
case _FADV_RANDOM:
case _FADV_SEQUENTIAL:
case _FADV_WILLNEED:
case _FADV_DONTNEED:
case _FADV_NOREUSE:
default:
return 0, nil, syserror.EINVAL
}
// Sure, whatever.
return 0, nil, nil
}
func mkdirAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr, mode linux.FileMode) error {
path, _, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return err
}
return fileOpAt(t, dirFD, path, func(root *fs.Dirent, d *fs.Dirent, name string) error {
if !fs.IsDir(d.Inode.StableAttr) {
return syserror.ENOTDIR
}
// Does this directory exist already?
f, err := t.MountNamespace().FindInode(t, root, d, name, linux.MaxSymlinkTraversals)
switch err {
case nil:
// The directory existed.
defer f.DecRef()
return syserror.EEXIST
case syserror.EACCES:
// Permission denied while walking to the directory.
return err
default:
// Do we have write permissions on the parent?
if err := d.Inode.CheckPermission(t, fs.PermMask{Write: true, Execute: true}); err != nil {
return err
}
// Create the directory.
perms := fs.FilePermsFromMode(mode &^ linux.FileMode(t.FSContext().Umask()))
return d.CreateDirectory(t, root, name, perms)
}
})
}
// Mkdir implements linux syscall mkdir(2).
func Mkdir(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
mode := linux.FileMode(args[1].ModeT())
return 0, nil, mkdirAt(t, linux.AT_FDCWD, addr, mode)
}
// Mkdirat implements linux syscall mkdirat(2).
func Mkdirat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
dirFD := kdefs.FD(args[0].Int())
addr := args[1].Pointer()
mode := linux.FileMode(args[2].ModeT())
return 0, nil, mkdirAt(t, dirFD, addr, mode)
}
func rmdirAt(t *kernel.Task, dirFD kdefs.FD, addr usermem.Addr) error {
path, _, err := copyInPath(t, addr, false /* allowEmpty */)
if err != nil {
return err
}
// Special case: rmdir rejects anything with '.' as last component.
// This would be handled by the busy check for the current working
// directory, but this is how it's done.
if (len(path) == 1 && path == ".") || (len(path) > 1 && path[len(path)-2:] == "/.") {
return syserror.EINVAL
}
return fileOpAt(t, dirFD, path, func(root *fs.Dirent, d *fs.Dirent, name string) error {
if !fs.IsDir(d.Inode.StableAttr) {
return syserror.ENOTDIR
}
if err := fs.MayDelete(t, root, d, name); err != nil {
return err
}
return d.RemoveDirectory(t, root, name)
})
}
// Rmdir implements linux syscall rmdir(2).
func Rmdir(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
return 0, nil, rmdirAt(t, linux.AT_FDCWD, addr)
}
func symlinkAt(t *kernel.Task, dirFD kdefs.FD, newAddr usermem.Addr, oldAddr usermem.Addr) error {
newPath, dirPath, err := copyInPath(t, newAddr, false /* allowEmpty */)
if err != nil {
return err
}
if dirPath {
return syserror.ENOENT
}
// The oldPath is copied in verbatim. This is because the symlink
// will include all details, including trailing slashes.
oldPath, err := t.CopyInString(oldAddr, syscall.PathMax)