@@ -115,7 +115,8 @@ type File struct {
115115 Symbols []Symbol // sorted by Name
116116 Info * Info
117117
118- raw []byte // entire file contents (source for the raw view + section data)
118+ raw []byte // entire file contents (mmap'd; source for the raw view + section data)
119+ unmap func () error // releases the mmap backing raw (nil-safe via Close)
119120 arch disasm.Arch
120121 entry uint64
121122 addrWidth int // hex digits in a printed address (8 or 16)
@@ -141,29 +142,34 @@ type lineEntry struct {
141142
142143// Open reads path, detects its container format, and builds the neutral model.
143144func Open (path string ) (* File , error ) {
144- raw , err := os . ReadFile (path )
145+ raw , closer , err := mapFile (path )
145146 if err != nil {
146147 return nil , err
147148 }
148149 f := & File {
149150 Path : path ,
150151 raw : raw ,
152+ unmap : closer ,
151153 sources : map [string ][]string {},
152154 }
153155 switch {
154156 case len (raw ) >= 4 && raw [0 ] == 0x7f && raw [1 ] == 'E' && raw [2 ] == 'L' && raw [3 ] == 'F' :
155157 if err := f .loadELF (); err != nil {
158+ f .Close ()
156159 return nil , err
157160 }
158161 case isMachO (raw ):
159162 if err := f .loadMachO (); err != nil {
163+ f .Close ()
160164 return nil , err
161165 }
162166 case len (raw ) >= 2 && raw [0 ] == 'M' && raw [1 ] == 'Z' :
163167 if err := f .loadPE (); err != nil {
168+ f .Close ()
164169 return nil , err
165170 }
166171 default :
172+ f .Close ()
167173 return nil , fmt .Errorf ("unrecognised file format (not ELF, Mach-O, or PE)" )
168174 }
169175
@@ -172,6 +178,18 @@ func Open(path string) (*File, error) {
172178 return f , nil
173179}
174180
181+ // Close releases the memory-mapped file. Safe to call more than once; after it
182+ // the raw bytes (and anything slicing into them) must no longer be used.
183+ func (f * File ) Close () error {
184+ if f == nil || f .unmap == nil {
185+ return nil
186+ }
187+ err := f .unmap ()
188+ f .unmap = nil
189+ f .raw = nil
190+ return err
191+ }
192+
175193// finalizeSymbols sorts symbols, fills in missing sizes, and builds the
176194// address-indexed copy used for reverse lookups. Loaders append unsorted
177195// symbols with their Size left at 0 when the container doesn't record one
0 commit comments