Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/link/internal/ld

     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 simlar 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  var viewError = errors.New("output not mmapped")
    96  
    97  func (out *OutBuf) View(start uint64) (*OutBuf, error) {
    98  	return &OutBuf{
    99  		arch:   out.arch,
   100  		name:   out.name,
   101  		buf:    out.buf,
   102  		heap:   out.heap,
   103  		off:    int64(start),
   104  		isView: true,
   105  	}, nil
   106  }
   107  
   108  var viewCloseError = errors.New("cannot Close OutBuf from View")
   109  
   110  func (out *OutBuf) Close() error {
   111  	if out.isView {
   112  		return viewCloseError
   113  	}
   114  	if out.isMmapped() {
   115  		out.copyHeap()
   116  		out.purgeSignatureCache()
   117  		out.munmap()
   118  	}
   119  	if out.f == nil {
   120  		return nil
   121  	}
   122  	if len(out.heap) != 0 {
   123  		if _, err := out.f.Write(out.heap); err != nil {
   124  			return err
   125  		}
   126  	}
   127  	if err := out.f.Close(); err != nil {
   128  		return err
   129  	}
   130  	out.f = nil
   131  	return nil
   132  }
   133  
   134  // isMmapped returns true if the OutBuf is mmaped.
   135  func (out *OutBuf) isMmapped() bool {
   136  	return len(out.buf) != 0
   137  }
   138  
   139  // Data returns the whole written OutBuf as a byte slice.
   140  func (out *OutBuf) Data() []byte {
   141  	if out.isMmapped() {
   142  		out.copyHeap()
   143  		return out.buf
   144  	}
   145  	return out.heap
   146  }
   147  
   148  // copyHeap copies the heap to the mmapped section of memory, returning true if
   149  // a copy takes place.
   150  func (out *OutBuf) copyHeap() bool {
   151  	if !out.isMmapped() { // only valuable for mmapped OutBufs.
   152  		return false
   153  	}
   154  	if out.isView {
   155  		panic("can't copyHeap a view")
   156  	}
   157  
   158  	bufLen := len(out.buf)
   159  	heapLen := len(out.heap)
   160  	total := uint64(bufLen + heapLen)
   161  	if heapLen != 0 {
   162  		if err := out.Mmap(total); err != nil { // Mmap will copy out.heap over to out.buf
   163  			panic(err)
   164  		}
   165  	}
   166  	return true
   167  }
   168  
   169  // maxOutBufHeapLen limits the growth of the heap area.
   170  const maxOutBufHeapLen = 10 << 20
   171  
   172  // writeLoc determines the write location if a buffer is mmaped.
   173  // We maintain two write buffers, an mmapped section, and a heap section for
   174  // writing. When the mmapped section is full, we switch over the heap memory
   175  // for writing.
   176  func (out *OutBuf) writeLoc(lenToWrite int64) (int64, []byte) {
   177  	// See if we have enough space in the mmaped area.
   178  	bufLen := int64(len(out.buf))
   179  	if out.off+lenToWrite <= bufLen {
   180  		return out.off, out.buf
   181  	}
   182  
   183  	// Not enough space in the mmaped area, write to heap area instead.
   184  	heapPos := out.off - bufLen
   185  	heapLen := int64(len(out.heap))
   186  	lenNeeded := heapPos + lenToWrite
   187  	if lenNeeded > heapLen { // do we need to grow the heap storage?
   188  		// The heap variables aren't protected by a mutex. For now, just bomb if you
   189  		// try to use OutBuf in parallel. (Note this probably could be fixed.)
   190  		if out.isView {
   191  			panic("cannot write to heap in parallel")
   192  		}
   193  		// See if our heap would grow to be too large, and if so, copy it to the end
   194  		// of the mmapped area.
   195  		if heapLen > maxOutBufHeapLen && out.copyHeap() {
   196  			heapPos -= heapLen
   197  			lenNeeded = heapPos + lenToWrite
   198  			heapLen = 0
   199  		}
   200  		out.heap = append(out.heap, make([]byte, lenNeeded-heapLen)...)
   201  	}
   202  	return heapPos, out.heap
   203  }
   204  
   205  func (out *OutBuf) SeekSet(p int64) {
   206  	out.off = p
   207  }
   208  
   209  func (out *OutBuf) Offset() int64 {
   210  	return out.off
   211  }
   212  
   213  // Write writes the contents of v to the buffer.
   214  func (out *OutBuf) Write(v []byte) (int, error) {
   215  	n := len(v)
   216  	pos, buf := out.writeLoc(int64(n))
   217  	copy(buf[pos:], v)
   218  	out.off += int64(n)
   219  	return n, nil
   220  }
   221  
   222  func (out *OutBuf) Write8(v uint8) {
   223  	pos, buf := out.writeLoc(1)
   224  	buf[pos] = v
   225  	out.off++
   226  }
   227  
   228  // WriteByte is an alias for Write8 to fulfill the io.ByteWriter interface.
   229  func (out *OutBuf) WriteByte(v byte) error {
   230  	out.Write8(v)
   231  	return nil
   232  }
   233  
   234  func (out *OutBuf) Write16(v uint16) {
   235  	out.arch.ByteOrder.PutUint16(out.encbuf[:], v)
   236  	out.Write(out.encbuf[:2])
   237  }
   238  
   239  func (out *OutBuf) Write32(v uint32) {
   240  	out.arch.ByteOrder.PutUint32(out.encbuf[:], v)
   241  	out.Write(out.encbuf[:4])
   242  }
   243  
   244  func (out *OutBuf) Write32b(v uint32) {
   245  	binary.BigEndian.PutUint32(out.encbuf[:], v)
   246  	out.Write(out.encbuf[:4])
   247  }
   248  
   249  func (out *OutBuf) Write64(v uint64) {
   250  	out.arch.ByteOrder.PutUint64(out.encbuf[:], v)
   251  	out.Write(out.encbuf[:8])
   252  }
   253  
   254  func (out *OutBuf) Write64b(v uint64) {
   255  	binary.BigEndian.PutUint64(out.encbuf[:], v)
   256  	out.Write(out.encbuf[:8])
   257  }
   258  
   259  func (out *OutBuf) WriteString(s string) {
   260  	pos, buf := out.writeLoc(int64(len(s)))
   261  	n := copy(buf[pos:], s)
   262  	if n != len(s) {
   263  		log.Fatalf("WriteString truncated. buffer size: %d, offset: %d, len(s)=%d", len(out.buf), out.off, len(s))
   264  	}
   265  	out.off += int64(n)
   266  }
   267  
   268  // WriteStringN writes the first n bytes of s.
   269  // If n is larger than len(s) then it is padded with zero bytes.
   270  func (out *OutBuf) WriteStringN(s string, n int) {
   271  	out.WriteStringPad(s, n, zeros[:])
   272  }
   273  
   274  // WriteStringPad writes the first n bytes of s.
   275  // If n is larger than len(s) then it is padded with the bytes in pad (repeated as needed).
   276  func (out *OutBuf) WriteStringPad(s string, n int, pad []byte) {
   277  	if len(s) >= n {
   278  		out.WriteString(s[:n])
   279  	} else {
   280  		out.WriteString(s)
   281  		n -= len(s)
   282  		for n > len(pad) {
   283  			out.Write(pad)
   284  			n -= len(pad)
   285  
   286  		}
   287  		out.Write(pad[:n])
   288  	}
   289  }
   290  
   291  // WriteSym writes the content of a Symbol, and returns the output buffer
   292  // that we just wrote, so we can apply further edit to the symbol content.
   293  // For generator symbols, it also sets the symbol's Data to the output
   294  // buffer.
   295  func (out *OutBuf) WriteSym(ldr *loader.Loader, s loader.Sym) []byte {
   296  	if !ldr.IsGeneratedSym(s) {
   297  		P := ldr.Data(s)
   298  		n := int64(len(P))
   299  		pos, buf := out.writeLoc(n)
   300  		copy(buf[pos:], P)
   301  		out.off += n
   302  		ldr.FreeData(s)
   303  		return buf[pos : pos+n]
   304  	} else {
   305  		n := ldr.SymSize(s)
   306  		pos, buf := out.writeLoc(n)
   307  		out.off += n
   308  		ldr.MakeSymbolUpdater(s).SetData(buf[pos : pos+n])
   309  		return buf[pos : pos+n]
   310  	}
   311  }
   312  

View as plain text