Debian Codegraph @

src/cmd/link/internal/ld/outbuf.go

raw
1 // Copyright 2017 The Go 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 ld
6
7 import (
8 "cmd/internal/sys"
9 "cmd/link/internal/loader"
10 "encoding/binary"
11 "errors"
12 "log"
13 "os"
14 )
15
16 // If fallocate is not supported on this platform, return this error. The error
17 // is ignored where needed, and OutBuf writes to heap memory.
18 var errNoFallocate = errors.New("operation not supported")
19
20 const outbufMode = 0775
21
22 // OutBuf is a buffered file writer.
23 //
24 // It is similar to the Writer in cmd/internal/bio with a few small differences.
25 //
26 // First, it tracks the output architecture and uses it to provide
27 // endian helpers.
28 //
29 // Second, it provides a very cheap offset counter that doesn't require
30 // any system calls to read the value.
31 //
32 // Third, it also mmaps the output file (if available). The intended usage is:
33 // - Mmap the output file
34 // - Write the content
35 // - possibly apply any edits in the output buffer
36 // - possibly write more content to the file. These writes take place in a heap
37 // backed buffer that will get synced to disk.
38 // - Munmap the output file
39 //
40 // And finally, it provides a mechanism by which you can multithread the
41 // writing of output files. This mechanism is accomplished by copying a OutBuf,
42 // and using it in the thread/goroutine.
43 //
44 // Parallel OutBuf is intended to be used like:
45 //
46 // func write(out *OutBuf) {
47 // var wg sync.WaitGroup
48 // for i := 0; i < 10; i++ {
49 // wg.Add(1)
50 // view, err := out.View(start[i])
51 // if err != nil {
52 // // handle output
53 // continue
54 // }
55 // go func(out *OutBuf, i int) {
56 // // do output
57 // wg.Done()
58 // }(view, i)
59 // }
60 // wg.Wait()
61 // }
62 type OutBuf struct {
63 arch *sys.Arch
64 off int64
65
66 buf []byte // backing store of mmap'd output file
67 heap []byte // backing store for non-mmapped data
68
69 name string
70 f *os.File
71 encbuf [8]byte // temp buffer used by WriteN methods
72 isView bool // true if created from View()
73 }
74
75 func (out *OutBuf) Open(name string) error {
76 if out.f != nil {
77 return errors.New("cannot open more than one file")
78 }
79 f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, outbufMode)
80 if err != nil {
81 return err
82 }
83 out.off = 0
84 out.name = name
85 out.f = f
86 return nil
87 }
88
89 func NewOutBuf(arch *sys.Arch) *OutBuf {
90 return &OutBuf{
91 arch: arch,
92 }
93 }
94
95 func (out *OutBuf) View(start uint64) *OutBuf {
96 return &OutBuf{
97 arch: out.arch,
98 name: out.name,
99 buf: out.buf,
100 heap: out.heap,
101 off: int64(start),
102 isView: true,
103 }
104 }
105
106 var viewCloseError = errors.New("cannot Close OutBuf from View")
107
108 func (out *OutBuf) Close() error {
109 if out.isView {
110 return viewCloseError
111 }
112 if out.isMmapped() {
113 out.copyHeap()
114 out.purgeSignatureCache()
115 out.munmap()
116 }
117 if out.f == nil {
118 return nil
119 }
120 if len(out.heap) != 0 {
121 if _, err := out.f.Write(out.heap); err != nil {
122 return err
123 }
124 }
125 if err := out.f.Close(); err != nil {
126 return err
127 }
128 out.f = nil
129 return nil
130 }
131
132 // ErrorClose closes the output file (if any).
133 // It is supposed to be called only at exit on error, so it doesn't do
134 // any clean up or buffer flushing, just closes the file.
135 func (out *OutBuf) ErrorClose() {
136 if out.isView {
137 panic(viewCloseError)
138 }
139 if out.f == nil {
140 return
141 }
142 out.f.Close() // best effort, ignore error
143 out.f = nil
144 }
145
146 // isMmapped returns true if the OutBuf is mmaped.
147 func (out *OutBuf) isMmapped() bool {
148 return len(out.buf) != 0
149 }
150
151 // Data returns the whole written OutBuf as a byte slice.
152 func (out *OutBuf) Data() []byte {
153 if out.isMmapped() {
154 out.copyHeap()
155 return out.buf
156 }
157 return out.heap
158 }
159
160 // copyHeap copies the heap to the mmapped section of memory, returning true if
161 // a copy takes place.
162 func (out *OutBuf) copyHeap() bool {
163 if !out.isMmapped() { // only valuable for mmapped OutBufs.
164 return false
165 }
166 if out.isView {
167 panic("can't copyHeap a view")
168 }
169
170 bufLen := len(out.buf)
171 heapLen := len(out.heap)
172 total := uint64(bufLen + heapLen)
173 if heapLen != 0 {
174 if err := out.Mmap(total); err != nil { // Mmap will copy out.heap over to out.buf
175 Exitf("mapping output file failed: %v", err)
176 }
177 }
178 return true
179 }
180
181 // maxOutBufHeapLen limits the growth of the heap area.
182 const maxOutBufHeapLen = 10 << 20
183
184 // writeLoc determines the write location if a buffer is mmaped.
185 // We maintain two write buffers, an mmapped section, and a heap section for
186 // writing. When the mmapped section is full, we switch over the heap memory
187 // for writing.
188 func (out *OutBuf) writeLoc(lenToWrite int64) (int64, []byte) {
189 // See if we have enough space in the mmaped area.
190 bufLen := int64(len(out.buf))
191 if out.off+lenToWrite <= bufLen {
192 return out.off, out.buf
193 }
194
195 // Not enough space in the mmaped area, write to heap area instead.
196 heapPos := out.off - bufLen
197 heapLen := int64(len(out.heap))
198 lenNeeded := heapPos + lenToWrite
199 if lenNeeded > heapLen { // do we need to grow the heap storage?
200 // The heap variables aren't protected by a mutex. For now, just bomb if you
201 // try to use OutBuf in parallel. (Note this probably could be fixed.)
202 if out.isView {
203 panic("cannot write to heap in parallel")
204 }
205 // See if our heap would grow to be too large, and if so, copy it to the end
206 // of the mmapped area.
207 if heapLen > maxOutBufHeapLen && out.copyHeap() {
208 heapPos -= heapLen
209 lenNeeded = heapPos + lenToWrite
210 heapLen = 0
211 }
212 out.heap = append(out.heap, make([]byte, lenNeeded-heapLen)...)
213 }
214 return heapPos, out.heap
215 }
216
217 func (out *OutBuf) SeekSet(p int64) {
218 out.off = p
219 }
220
221 func (out *OutBuf) Offset() int64 {
222 return out.off
223 }
224
225 // Write writes the contents of v to the buffer.
226 func (out *OutBuf) Write(v []byte) (int, error) {
227 n := len(v)
228 pos, buf := out.writeLoc(int64(n))
229 copy(buf[pos:], v)
230 out.off += int64(n)
231 return n, nil
232 }
233
234 func (out *OutBuf) Write8(v uint8) {
235 pos, buf := out.writeLoc(1)
236 buf[pos] = v
237 out.off++
238 }
239
240 // WriteByte is an alias for Write8 to fulfill the io.ByteWriter interface.
241 func (out *OutBuf) WriteByte(v byte) error {
242 out.Write8(v)
243 return nil
244 }
245
246 func (out *OutBuf) Write16(v uint16) {
247 out.arch.ByteOrder.PutUint16(out.encbuf[:], v)
248 out.Write(out.encbuf[:2])
249 }
250
251 func (out *OutBuf) Write32(v uint32) {
252 out.arch.ByteOrder.PutUint32(out.encbuf[:], v)
253 out.Write(out.encbuf[:4])
254 }
255
256 func (out *OutBuf) Write32b(v uint32) {
257 binary.BigEndian.PutUint32(out.encbuf[:], v)
258 out.Write(out.encbuf[:4])
259 }
260
261 func (out *OutBuf) Write64(v uint64) {
262 out.arch.ByteOrder.PutUint64(out.encbuf[:], v)
263 out.Write(out.encbuf[:8])
264 }
265
266 func (out *OutBuf) Write64b(v uint64) {
267 binary.BigEndian.PutUint64(out.encbuf[:], v)
268 out.Write(out.encbuf[:8])
269 }
270
271 func (out *OutBuf) WriteString(s string) {
272 pos, buf := out.writeLoc(int64(len(s)))
273 n := copy(buf[pos:], s)
274 if n != len(s) {
275 log.Fatalf("WriteString truncated. buffer size: %d, offset: %d, len(s)=%d", len(out.buf), out.off, len(s))
276 }
277 out.off += int64(n)
278 }
279
280 // WriteStringN writes the first n bytes of s.
281 // If n is larger than len(s) then it is padded with zero bytes.
282 func (out *OutBuf) WriteStringN(s string, n int) {
283 out.WriteStringPad(s, n, zeros[:])
284 }
285
286 // WriteStringPad writes the first n bytes of s.
287 // If n is larger than len(s) then it is padded with the bytes in pad (repeated as needed).
288 func (out *OutBuf) WriteStringPad(s string, n int, pad []byte) {
289 if len(s) >= n {
290 out.WriteString(s[:n])
291 } else {
292 out.WriteString(s)
293 n -= len(s)
294 for n > len(pad) {
295 out.Write(pad)
296 n -= len(pad)
297
298 }
299 out.Write(pad[:n])
300 }
301 }
302
303 // WriteSym writes the content of a Symbol, and returns the output buffer
304 // that we just wrote, so we can apply further edit to the symbol content.
305 // For generator symbols, it also sets the symbol's Data to the output
306 // buffer.
307 func (out *OutBuf) WriteSym(ldr *loader.Loader, s loader.Sym) []byte {
308 if !ldr.IsGeneratedSym(s) {
309 P := ldr.Data(s)
310 n := int64(len(P))
311 pos, buf := out.writeLoc(n)
312 copy(buf[pos:], P)
313 out.off += n
314 ldr.FreeData(s)
315 return buf[pos : pos+n]
316 } else {
317 n := ldr.SymSize(s)
318 pos, buf := out.writeLoc(n)
319 out.off += n
320 ldr.MakeSymbolUpdater(s).SetData(buf[pos : pos+n])
321 return buf[pos : pos+n]
322 }
323 }