| 1 | //go:build darwin || linux |
| 2 | |
| 3 | package osfs |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "io" |
| 8 | "math" |
| 9 | "os" |
| 10 | "runtime" |
| 11 | "sync" |
| 12 | |
| 13 | "golang.org/x/sys/unix" |
| 14 | ) |
| 15 | |
| 16 | // mmapFile is a billy.File backed by a read-only memory map. It is |
| 17 | // returned from BoundOS/RootOS.OpenFile when the filesystem was |
| 18 | // constructed with [WithMmap] and the file is opened without write |
| 19 | // flags. Read and Seek track a real cursor over the mapped bytes, |
| 20 | // ReadAt is concurrent-safe (multiple goroutines may call it in |
| 21 | // parallel against the same handle) and serialised against Close |
| 22 | // via an RWMutex so munmap cannot run while a read is in flight. |
| 23 | // Write/WriteAt/Truncate return [os.ErrPermission] — the file is |
| 24 | // read-only by construction. |
| 25 | type mmapFile struct { |
| 26 | f *os.File |
| 27 | data []byte |
| 28 | name string |
| 29 | |
| 30 | mu sync.RWMutex |
| 31 | cursor int64 |
| 32 | closed bool |
| 33 | |
| 34 | cleanup runtime.Cleanup |
| 35 | } |
| 36 | |
| 37 | // mmapResources holds the resorces to be cleaned up when mmapFile is GC. |
| 38 | type mmapResources struct { |
| 39 | data []byte |
| 40 | file *os.File |
| 41 | } |
| 42 | |
| 43 | // newMmapFile maps f read-only and returns an [*mmapFile] that owns |
| 44 | // f. On success the returned handle is responsible for closing the |
| 45 | // underlying [*os.File] via [(*mmapFile).Close]. |
| 46 | // |
| 47 | // If mmap is unavailable for this particular file (zero size, size |
| 48 | // beyond platform int, mmap rejected by the kernel for pipes/devices |
| 49 | // etc.) the function returns [errMmapUnavailable] without closing f |
| 50 | // so the caller can fall back to a regular [*file] wrapper. |
| 51 | // |
| 52 | // Any other error (e.g. fstat failing) is propagated as-is and f is |
| 53 | // closed before returning — the caller must not use it. |
| 54 | func newMmapFile(f *os.File, name string) (*mmapFile, error) { |
| 55 | info, err := f.Stat() |
| 56 | if err != nil { |
| 57 | _ = f.Close() |
| 58 | return nil, err |
| 59 | } |
| 60 | |
| 61 | size := info.Size() |
| 62 | if size <= 0 || size > int64(math.MaxInt) { |
| 63 | // unix.Mmap rejects size 0, and 32-bit platforms can't |
| 64 | // represent very large mappings as an int. Either case |
| 65 | // is fine for the regular fd wrapper. |
| 66 | return nil, errMmapUnavailable |
| 67 | } |
| 68 | |
| 69 | data, err := unix.Mmap(int(f.Fd()), 0, int(size), unix.PROT_READ, unix.MAP_SHARED) |
| 70 | if err != nil { |
| 71 | // Many failure modes here are legitimate (pipes, devices, |
| 72 | // FS quirks). Defer to the fd wrapper. |
| 73 | return nil, errMmapUnavailable |
| 74 | } |
| 75 | |
| 76 | m := &mmapFile{f: f, data: data, name: name} |
| 77 | |
| 78 | // unmap and close the file when the mmapFile is garbage collected and no |
| 79 | // Close is called before. |
| 80 | mr := mmapResources{ |
| 81 | data: data, |
| 82 | file: f, |
| 83 | } |
| 84 | closeFunc := func(res mmapResources) { |
| 85 | _ = unix.Munmap(res.data) |
| 86 | _ = res.file.Close() |
| 87 | } |
| 88 | m.cleanup = runtime.AddCleanup(m, closeFunc, mr) |
| 89 | |
| 90 | return m, nil |
| 91 | } |
| 92 | |
| 93 | func (m *mmapFile) Name() string { return m.name } |
| 94 | |
| 95 | // Stat returns the underlying *os.File's FileInfo unchanged so that |
| 96 | // f.Stat().Name() matches the basename returned by the fd-backed |
| 97 | // *file across both backings. |
| 98 | func (m *mmapFile) Stat() (os.FileInfo, error) { |
| 99 | return m.f.Stat() |
| 100 | } |
| 101 | |
| 102 | // Read implements [io.Reader]. It holds the write lock because it |
| 103 | // mutates the shared cursor; concurrent Read+Read would otherwise |
| 104 | // race on m.cursor even though both could read m.data under RLock. |
| 105 | // Random-access callers should use ReadAt, which is the parallel API. |
| 106 | func (m *mmapFile) Read(p []byte) (int, error) { |
| 107 | if len(p) == 0 { |
| 108 | return 0, nil |
| 109 | } |
| 110 | m.mu.Lock() |
| 111 | defer m.mu.Unlock() |
| 112 | if m.closed { |
| 113 | return 0, os.ErrClosed |
| 114 | } |
| 115 | if m.cursor >= int64(len(m.data)) { |
| 116 | return 0, io.EOF |
| 117 | } |
| 118 | n := copy(p, m.data[m.cursor:]) |
| 119 | m.cursor += int64(n) |
| 120 | return n, nil |
| 121 | } |
| 122 | |
| 123 | func (m *mmapFile) ReadAt(p []byte, off int64) (int, error) { |
| 124 | if len(p) == 0 { |
| 125 | return 0, nil |
| 126 | } |
| 127 | m.mu.RLock() |
| 128 | defer m.mu.RUnlock() |
| 129 | if m.closed { |
| 130 | return 0, os.ErrClosed |
| 131 | } |
| 132 | if off < 0 { |
| 133 | return 0, &os.PathError{Op: "readat", Path: m.name, Err: errors.New("negative offset")} |
| 134 | } |
| 135 | if off >= int64(len(m.data)) { |
| 136 | return 0, io.EOF |
| 137 | } |
| 138 | n := copy(p, m.data[off:]) |
| 139 | if n < len(p) { |
| 140 | return n, io.EOF |
| 141 | } |
| 142 | return n, nil |
| 143 | } |
| 144 | |
| 145 | func (m *mmapFile) Seek(offset int64, whence int) (int64, error) { |
| 146 | m.mu.Lock() |
| 147 | defer m.mu.Unlock() |
| 148 | if m.closed { |
| 149 | return 0, os.ErrClosed |
| 150 | } |
| 151 | var abs int64 |
| 152 | switch whence { |
| 153 | case io.SeekStart: |
| 154 | abs = offset |
| 155 | case io.SeekCurrent: |
| 156 | abs = m.cursor + offset |
| 157 | case io.SeekEnd: |
| 158 | abs = int64(len(m.data)) + offset |
| 159 | default: |
| 160 | return 0, &os.PathError{Op: "seek", Path: m.name, Err: errors.New("invalid whence")} |
| 161 | } |
| 162 | if abs < 0 { |
| 163 | return 0, &os.PathError{Op: "seek", Path: m.name, Err: errors.New("negative position")} |
| 164 | } |
| 165 | m.cursor = abs |
| 166 | return abs, nil |
| 167 | } |
| 168 | |
| 169 | func (m *mmapFile) Write(p []byte) (int, error) { |
| 170 | return 0, &os.PathError{Op: "write", Path: m.name, Err: os.ErrPermission} |
| 171 | } |
| 172 | |
| 173 | func (m *mmapFile) WriteAt(p []byte, off int64) (int, error) { |
| 174 | return 0, &os.PathError{Op: "writeat", Path: m.name, Err: os.ErrPermission} |
| 175 | } |
| 176 | |
| 177 | func (m *mmapFile) Truncate(size int64) error { |
| 178 | return &os.PathError{Op: "truncate", Path: m.name, Err: os.ErrPermission} |
| 179 | } |
| 180 | |
| 181 | func (m *mmapFile) Close() error { |
| 182 | m.mu.Lock() |
| 183 | defer m.mu.Unlock() |
| 184 | if m.closed { |
| 185 | return os.ErrClosed |
| 186 | } |
| 187 | m.closed = true |
| 188 | m.cleanup.Stop() |
| 189 | |
| 190 | munmapErr := unix.Munmap(m.data) |
| 191 | m.data = nil |
| 192 | closeErr := m.f.Close() |
| 193 | return errors.Join(munmapErr, closeErr) |
| 194 | } |