github.com/AndrienkoAleksandr/go@v0.0.19/src/go/internal/gcimporter/exportdata.go (about) 1 // Copyright 2011 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 // This file implements FindExportData. 6 7 package gcimporter 8 9 import ( 10 "bufio" 11 "fmt" 12 "io" 13 "strconv" 14 "strings" 15 ) 16 17 func readGopackHeader(r *bufio.Reader) (name string, size int, err error) { 18 // See $GOROOT/include/ar.h. 19 hdr := make([]byte, 16+12+6+6+8+10+2) 20 _, err = io.ReadFull(r, hdr) 21 if err != nil { 22 return 23 } 24 // leave for debugging 25 if false { 26 fmt.Printf("header: %s", hdr) 27 } 28 s := strings.TrimSpace(string(hdr[16+12+6+6+8:][:10])) 29 size, err = strconv.Atoi(s) 30 if err != nil || hdr[len(hdr)-2] != '`' || hdr[len(hdr)-1] != '\n' { 31 err = fmt.Errorf("invalid archive header") 32 return 33 } 34 name = strings.TrimSpace(string(hdr[:16])) 35 return 36 } 37 38 // FindExportData positions the reader r at the beginning of the 39 // export data section of an underlying GC-created object/archive 40 // file by reading from it. The reader must be positioned at the 41 // start of the file before calling this function. The hdr result 42 // is the string before the export data, either "$$" or "$$B". 43 func FindExportData(r *bufio.Reader) (hdr string, size int, err error) { 44 // Read first line to make sure this is an object file. 45 line, err := r.ReadSlice('\n') 46 if err != nil { 47 err = fmt.Errorf("can't find export data (%v)", err) 48 return 49 } 50 51 if string(line) == "!<arch>\n" { 52 // Archive file. Scan to __.PKGDEF. 53 var name string 54 if name, size, err = readGopackHeader(r); err != nil { 55 return 56 } 57 58 // First entry should be __.PKGDEF. 59 if name != "__.PKGDEF" { 60 err = fmt.Errorf("go archive is missing __.PKGDEF") 61 return 62 } 63 64 // Read first line of __.PKGDEF data, so that line 65 // is once again the first line of the input. 66 if line, err = r.ReadSlice('\n'); err != nil { 67 err = fmt.Errorf("can't find export data (%v)", err) 68 return 69 } 70 } 71 72 // Now at __.PKGDEF in archive or still at beginning of file. 73 // Either way, line should begin with "go object ". 74 if !strings.HasPrefix(string(line), "go object ") { 75 err = fmt.Errorf("not a Go object file") 76 return 77 } 78 size -= len(line) 79 80 // Skip over object header to export data. 81 // Begins after first line starting with $$. 82 for line[0] != '$' { 83 if line, err = r.ReadSlice('\n'); err != nil { 84 err = fmt.Errorf("can't find export data (%v)", err) 85 return 86 } 87 size -= len(line) 88 } 89 hdr = string(line) 90 91 return 92 }