github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/mount/loop/loop_linux.go (about) 1 // Copyright 2018-2020 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package loop provides an interface to interacting with Linux loop devices. 6 // 7 // A loop device exposes a regular file as if it were a block device. 8 package loop 9 10 import ( 11 "github.com/mvdan/u-root-coreutils/pkg/mount" 12 ) 13 14 // Loop represents a regular file exposed as a loop block device. 15 // 16 // Loop implements mount.Mounter. 17 type Loop struct { 18 // Dev is the loop device path. 19 Dev string 20 21 // Source is the regular file to use as a block device. 22 Source string 23 24 // FSType is the file system to use when mounting the block device. 25 FSType string 26 27 // Data is the data to pass to mount(2). 28 Data string 29 } 30 31 var _ mount.Mounter = &Loop{} 32 33 // New initializes a Loop struct and allocates a loop device to it. 34 // 35 // source is the file to use as a loop block device. fstype the file system 36 // name. data is the data argument to the mount(2) syscall. 37 func New(source, fstype string, data string) (*Loop, error) { 38 devicename, err := FindDevice() 39 if err != nil { 40 return nil, err 41 } 42 if err := SetFile(devicename, source); err != nil { 43 return nil, err 44 } 45 return &Loop{ 46 Dev: devicename, 47 Source: source, 48 FSType: fstype, 49 Data: data, 50 }, nil 51 } 52 53 // DevName implements mount.Mounter. 54 func (l *Loop) DevName() string { 55 return l.Dev 56 } 57 58 // Mount mounts the provided source file, with type fstype, and flags and data options 59 // (which are usually 0 and ""), using the allocated loop device. 60 func (l *Loop) Mount(path string, flags uintptr, opts ...func() error) (*mount.MountPoint, error) { 61 return mount.Mount(l.Dev, path, l.FSType, l.Data, flags, opts...) 62 } 63 64 // Free frees the loop device. 65 // 66 // All mount points must have been unmounted prior to calling this. 67 func (l *Loop) Free() error { 68 return ClearFile(l.Dev) 69 }