github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/fsimpl/host/save_restore.go (about) 1 // Copyright 2020 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package host 16 17 import ( 18 "fmt" 19 "io" 20 "sync/atomic" 21 22 "golang.org/x/sys/unix" 23 "github.com/SagerNet/gvisor/pkg/fdnotifier" 24 "github.com/SagerNet/gvisor/pkg/hostarch" 25 "github.com/SagerNet/gvisor/pkg/safemem" 26 "github.com/SagerNet/gvisor/pkg/sentry/hostfd" 27 ) 28 29 // beforeSave is invoked by stateify. 30 func (i *inode) beforeSave() { 31 if !i.savable { 32 panic("host.inode is not savable") 33 } 34 if i.ftype == unix.S_IFIFO { 35 // If this pipe FD is readable, drain it so that bytes in the pipe can 36 // be read after restore. (This is a legacy VFS1 feature.) We don't 37 // know if the pipe FD is readable, so just try reading and tolerate 38 // EBADF from the read. 39 i.bufMu.Lock() 40 defer i.bufMu.Unlock() 41 var buf [hostarch.PageSize]byte 42 for { 43 n, err := hostfd.Preadv2(int32(i.hostFD), safemem.BlockSeqOf(safemem.BlockFromSafeSlice(buf[:])), -1 /* offset */, 0 /* flags */) 44 if n != 0 { 45 i.buf = append(i.buf, buf[:n]...) 46 } 47 if err != nil { 48 if err == io.EOF || err == unix.EAGAIN || err == unix.EBADF { 49 break 50 } 51 panic(fmt.Errorf("host.inode.beforeSave: buffering from pipe failed: %v", err)) 52 } 53 } 54 if len(i.buf) != 0 { 55 atomic.StoreUint32(&i.haveBuf, 1) 56 } 57 } 58 } 59 60 // afterLoad is invoked by stateify. 61 func (i *inode) afterLoad() { 62 if i.mayBlock { 63 if err := unix.SetNonblock(i.hostFD, true); err != nil { 64 panic(fmt.Sprintf("host.inode.afterLoad: failed to set host FD %d non-blocking: %v", i.hostFD, err)) 65 } 66 if err := fdnotifier.AddFD(int32(i.hostFD), &i.queue); err != nil { 67 panic(fmt.Sprintf("host.inode.afterLoad: fdnotifier.AddFD(%d) failed: %v", i.hostFD, err)) 68 } 69 } 70 } 71 72 // afterLoad is invoked by stateify. 73 func (c *ConnectedEndpoint) afterLoad() { 74 if err := c.initFromOptions(); err != nil { 75 panic(fmt.Sprintf("initFromOptions failed: %v", err)) 76 } 77 }