github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/mm/shm.go (about) 1 // Copyright 2018 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 mm 16 17 import ( 18 "github.com/SagerNet/gvisor/pkg/context" 19 "github.com/SagerNet/gvisor/pkg/errors/linuxerr" 20 "github.com/SagerNet/gvisor/pkg/hostarch" 21 "github.com/SagerNet/gvisor/pkg/sentry/kernel/shm" 22 ) 23 24 // DetachShm unmaps a sysv shared memory segment. 25 func (mm *MemoryManager) DetachShm(ctx context.Context, addr hostarch.Addr) error { 26 if addr != addr.RoundDown() { 27 // "... shmaddr is not aligned on a page boundary." - man shmdt(2) 28 return linuxerr.EINVAL 29 } 30 31 var detached *shm.Shm 32 mm.mappingMu.Lock() 33 defer mm.mappingMu.Unlock() 34 35 // Find and remove the first vma containing an address >= addr that maps a 36 // segment originally attached at addr. 37 vseg := mm.vmas.LowerBoundSegment(addr) 38 for vseg.Ok() { 39 vma := vseg.ValuePtr() 40 if shm, ok := vma.mappable.(*shm.Shm); ok && vseg.Start() >= addr && uint64(vseg.Start()-addr) == vma.off { 41 detached = shm 42 vseg = mm.unmapLocked(ctx, vseg.Range()).NextSegment() 43 break 44 } else { 45 vseg = vseg.NextSegment() 46 } 47 } 48 49 if detached == nil { 50 // There is no shared memory segment attached at addr. 51 return linuxerr.EINVAL 52 } 53 54 // Remove all vmas that could have been created by the same attach. 55 end := addr + hostarch.Addr(detached.EffectiveSize()) 56 for vseg.Ok() && vseg.End() <= end { 57 vma := vseg.ValuePtr() 58 if vma.mappable == detached && uint64(vseg.Start()-addr) == vma.off { 59 vseg = mm.unmapLocked(ctx, vseg.Range()).NextSegment() 60 } else { 61 vseg = vseg.NextSegment() 62 } 63 } 64 65 return nil 66 }