github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/src/cmd/link/internal/ld/util.go (about) 1 // Copyright 2015 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 "bytes" 9 "encoding/binary" 10 "log" 11 "os" 12 "runtime" 13 "runtime/pprof" 14 "strings" 15 "time" 16 ) 17 18 func cstring(x []byte) string { 19 i := bytes.IndexByte(x, '\x00') 20 if i >= 0 { 21 x = x[:i] 22 } 23 return string(x) 24 } 25 26 func tokenize(s string) []string { 27 var f []string 28 for { 29 s = strings.TrimLeft(s, " \t\r\n") 30 if s == "" { 31 break 32 } 33 quote := false 34 i := 0 35 for ; i < len(s); i++ { 36 if s[i] == '\'' { 37 if quote && i+1 < len(s) && s[i+1] == '\'' { 38 i++ 39 continue 40 } 41 quote = !quote 42 } 43 if !quote && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r' || s[i] == '\n') { 44 break 45 } 46 } 47 next := s[:i] 48 s = s[i:] 49 if strings.Contains(next, "'") { 50 var buf []byte 51 quote := false 52 for i := 0; i < len(next); i++ { 53 if next[i] == '\'' { 54 if quote && i+1 < len(next) && next[i+1] == '\'' { 55 i++ 56 buf = append(buf, '\'') 57 } 58 quote = !quote 59 continue 60 } 61 buf = append(buf, next[i]) 62 } 63 next = string(buf) 64 } 65 f = append(f, next) 66 } 67 return f 68 } 69 70 var atExitFuncs []func() 71 72 func AtExit(f func()) { 73 atExitFuncs = append(atExitFuncs, f) 74 } 75 76 func Exit(code int) { 77 for i := len(atExitFuncs) - 1; i >= 0; i-- { 78 f := atExitFuncs[i] 79 atExitFuncs = atExitFuncs[:i] 80 f() 81 } 82 os.Exit(code) 83 } 84 85 var ( 86 cpuprofile string 87 memprofile string 88 memprofilerate int64 89 ) 90 91 func startProfile() { 92 if cpuprofile != "" { 93 f, err := os.Create(cpuprofile) 94 if err != nil { 95 log.Fatalf("%v", err) 96 } 97 if err := pprof.StartCPUProfile(f); err != nil { 98 log.Fatalf("%v", err) 99 } 100 AtExit(pprof.StopCPUProfile) 101 } 102 if memprofile != "" { 103 if memprofilerate != 0 { 104 runtime.MemProfileRate = int(memprofilerate) 105 } 106 f, err := os.Create(memprofile) 107 if err != nil { 108 log.Fatalf("%v", err) 109 } 110 AtExit(func() { 111 runtime.GC() // profile all outstanding allocations 112 if err := pprof.WriteHeapProfile(f); err != nil { 113 log.Fatalf("%v", err) 114 } 115 }) 116 } 117 } 118 119 func artrim(x []byte) string { 120 i := 0 121 j := len(x) 122 for i < len(x) && x[i] == ' ' { 123 i++ 124 } 125 for j > i && x[j-1] == ' ' { 126 j-- 127 } 128 return string(x[i:j]) 129 } 130 131 func stringtouint32(x []uint32, s string) { 132 for i := 0; len(s) > 0; i++ { 133 var buf [4]byte 134 s = s[copy(buf[:], s):] 135 x[i] = binary.LittleEndian.Uint32(buf[:]) 136 } 137 } 138 139 var start = time.Now() 140 141 func elapsed() float64 { 142 return time.Since(start).Seconds() 143 }